问:
Can't integrate INNER JOIN in my query
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

```<code>SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC
</code>```

.

```<code>users.username INNER JOIN users ON messages.user_id = users.user_id;
</code>```

答:
I think this is correct... finally.  The not exists filters out responses after the start.. the inner query grabs the most recent conversation. This should match the expected output.

```<code>SELECT dT.maxid AS message_id
      ,(SELECT msg FROM messages M WHERE M.message_id = dT.maxid) AS message_id
      ,(SELECT username FROM users U WHERE U.user_id = dT.owner_id) AS user_id
  FROM (
         SELECT MAX(message_id) as maxid
               ,owner_id
               ,recipient_id
           FROM messages M
         GROUP BY owner_id, recipient_id
       ) AS dT
WHERE NOT EXISTS(SELECT *
                   FROM messages M2
                  WHERE M2.recipient_id = dT.owner_id
                    AND M2.owner_id = dT.recipient_id
                    AND M2.message_id > dT.maxid)
ORDER BY dT.maxid
</code>```

Produces output:

```<code>message_id  message_id                                             user_id
8           you should Now see this instead even with the          User2
            owner_id flipped.. The users_id in the query is 1
            and it gets the conversation with user_id 2
9           You should also see this                               User1
</code>```

fiddle

Title: Can't integrate INNER JOIN in my query

Body:
Hello I'm using the query below to select the latest message from each unique conversation. Everything works perfectly except when I try to integrate an INNER JOIN to try to link the user's user_id with their username in the users table.

I've tried pretty much every combination to integrate the INNER JOIN so I decided to separate it from the working query until I get help.

I made a Fiddle http://sqlfiddle.com/#!9/a9bbc/1   I just want user_id on the right to print the user's username

SELECT message_id,
       msg,
       user_id
FROM   messages
   JOIN (SELECT user_id,
                Max(dat) m
         FROM   ((SELECT message_id,
                         recipient_id user_id,
                         dat
                  FROM   messages
                  WHERE  owner_id = 1)
                 UNION
                 (SELECT message_id,
                         owner_id user_id,
                         dat
                  FROM   messages
                  WHERE  recipient_id = 1)) t1
         GROUP  BY user_id) t2
     ON ( ( owner_id = 1
            AND recipient_id = user_id )
           OR ( owner_id = user_id
                AND recipient_id = 1 ) )
        AND ( dat = m )
 ORDER  BY dat DESC

.

users.username INNER JOIN users ON messages.user_id = users.user_id;

Body:
I think this is correct... finally.  The not exists filters out responses after the start.. the inner query grabs the most recent conversation. This should match the expected output.

SELECT dT.maxid AS message_id
      ,(SELECT msg FROM messages M WHERE M.message_id = dT.maxid) AS message_id
      ,(SELECT username FROM users U WHERE U.user_id = dT.owner_id) AS user_id
  FROM (
         SELECT MAX(message_id) as maxid
               ,owner_id
               ,recipient_id
           FROM messages M
         GROUP BY owner_id, recipient_id
       ) AS dT
WHERE NOT EXISTS(SELECT *
                   FROM messages M2
                  WHERE M2.recipient_id = dT.owner_id
                    AND M2.owner_id = dT.recipient_id
                    AND M2.message_id > dT.maxid)
ORDER BY dT.maxid

Produces output:

message_id  message_id                                             user_id
8           you should Now see this instead even with the          User2
            owner_id flipped.. The users_id in the query is 1
            and it gets the conversation with user_id 2
9           You should also see this                               User1

fiddle


来源: stackexchange

问:
Compliererror for certain fields in DExif-Package
I installed the package DEXIF and am able to read some EXIF-Entries. But not computed values as described in the documentation.
The following code shows what works. For the commented lines I get the Error: identifier idents no member "focalLenght" and so on..
How can I get hold on these and more fields?</p>

```<code>procedure TForm1.EXIFAnzeigen(filename: string);
var
  ImgData: TImgData;
  i :integer;
begin
  //EDitor leeren

  ValueListEditor1.Strings.Clear;
  if FileExists(filename) then begin
     ImgData:= TImgData.Create();
     ImgData.Tracelevel :=1;
     try
        if uppercase(ExtractFileExt(filename)) = '.JPG' then begin
           if ImgData.ProcessFile(filename) then begin
              if ImgData.HasEXIF then begin
                 ValueListEditor1.InsertRow('Camera Make',
                 ImgData.ExifObj.CameraMake,True);
                 ValueListEditor1.InsertRow('Camera Modell',
                 ImgData.ExifObj.CameraModel,True);
                 ValueListEditor1.InsertRow('Picture DateTime',
                 FormatDateTime(ISO_DATETIME_FORMAT, ImgData.ExifObj.GetImgDateTime),True);
                 ValueListEditor1.InsertRow('Width',
                 inttostr(ImgData.ExifObj.Width),True);
                 ValueListEditor1.InsertRow('FlashUsed',
                 intToStr(ImgData.ExifObj.FlashUsed),True);

//               ValueListEditor1.InsertRow('FocalLength',
//               inttostr(ImgData.ExifObj.FocalLength),True);
//               ValueListEditor1.InsertRow('ApertureFNumber',
//               ImgData.ExifObj.ApertureFNumber,True);
//               ValueListEditor1.InsertRow('ExposureTime',
//               ImgData.ExifObj.ExposureTime,True);
//               ValueListEditor1.InsertRow('Distance',
//               ImgData.ExifObj.Distance,True);
//               ValueListEditor1.InsertRow('Process',
//               ImgData.ExifObj.Process,True);
              end else begin
                  ValueListEditor1.InsertRow('No EXIF','No Data',True);
              end;
           end else begin
               ValueListEditor1.InsertRow('No EXIF','Processdata',True);
           end;
        end else begin
          ValueListEditor1.Strings.Clear;
        end;
    finally
      ImgData.Free;
    end;
  end;
end;
</code>```

答:
The documentation says:

Some of the more common fields are accessible as properties of the
  EXIFObj of the ImgData.

and shows an example reading those properties, partly same as you succeed to read with your code.

But the FocalLength, and the others that fail in your code, have to be accessed in another way as the document says:

Other EXIF field can be read by using the property TagValue and
  specifying    the name of the EXIF property

The following example clarifies:

```<code>ValueListEditor1.InsertRow('FocalLength',
inttostr(ImgData.ExifObj.TagValue['FocalLength']),True);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I installed the package DEXIF and am able to read some EXIF-Entries. But not computed values as described in the documentation.
The following code shows what works. For the commented lines I get the Error: identifier idents no member "focalLenght" and so on..
How can I get hold on these and more fields?

procedure TForm1.EXIFAnzeigen(filename: string);
var
  ImgData: TImgData;
  i :integer;
begin
  //EDitor leeren

  ValueListEditor1.Strings.Clear;
  if FileExists(filename) then begin
     ImgData:= TImgData.Create();
     ImgData.Tracelevel :=1;
     try
        if uppercase(ExtractFileExt(filename)) = '.JPG' then begin
           if ImgData.ProcessFile(filename) then begin
              if ImgData.HasEXIF then begin
                 ValueListEditor1.InsertRow('Camera Make',
                 ImgData.ExifObj.CameraMake,True);
                 ValueListEditor1.InsertRow('Camera Modell',
                 ImgData.ExifObj.CameraModel,True);
                 ValueListEditor1.InsertRow('Picture DateTime',
                 FormatDateTime(ISO_DATETIME_FORMAT, ImgData.ExifObj.GetImgDateTime),True);
                 ValueListEditor1.InsertRow('Width',
                 inttostr(ImgData.ExifObj.Width),True);
                 ValueListEditor1.InsertRow('FlashUsed',
                 intToStr(ImgData.ExifObj.FlashUsed),True);

//               ValueListEditor1.InsertRow('FocalLength',
//               inttostr(ImgData.ExifObj.FocalLength),True);
//               ValueListEditor1.InsertRow('ApertureFNumber',
//               ImgData.ExifObj.ApertureFNumber,True);
//               ValueListEditor1.InsertRow('ExposureTime',
//               ImgData.ExifObj.ExposureTime,True);
//               ValueListEditor1.InsertRow('Distance',
//               ImgData.ExifObj.Distance,True);
//               ValueListEditor1.InsertRow('Process',
//               ImgData.ExifObj.Process,True);
              end else begin
                  ValueListEditor1.InsertRow('No EXIF','No Data',True);
              end;
           end else begin
               ValueListEditor1.InsertRow('No EXIF','Processdata',True);
           end;
        end else begin
          ValueListEditor1.Strings.Clear;
        end;
    finally
      ImgData.Free;
    end;
  end;
end;

Body:
The documentation says:

Some of the more common fields are accessible as properties of the
  EXIFObj of the ImgData.

and shows an example reading those properties, partly same as you succeed to read with your code.

But the FocalLength, and the others that fail in your code, have to be accessed in another way as the document says:

Other EXIF field can be read by using the property TagValue and
  specifying    the name of the EXIF property

The following example clarifies:

ValueListEditor1.InsertRow('FocalLength',
inttostr(ImgData.ExifObj.TagValue['FocalLength']),True);


问:
How to calculating time difference for timezone in Ruby
I am trying to see if the current time is after noon (lunch).

```<code>  noon_time = Time.parse "12:00 pm"
  current_time = Time.now
  if current_time < noon_time
    #eat a big meal or sleep its after lunch time
  else
    #work hard its not time to eat
  end
</code>```

When I run this code at 9:38pm it says "eat a big meal".

Do I need to do something like this and capture the time that is set for my website by the user?

```<code>  offset = Time.now.in_time_zone(current_user.time_zone).gmt_offset/60/60
</code>```

答:
You could try parsing the time from the perspective of the user:

```<code>Time.zone(current_user.time_zone).parse("12:00pm")
</code>```

If you use Time.now you're using it in the default time zone which is, presumably, UTC. It might be a good idea make a wrapper method time_current for your User model that returns the time in the correct time zone? The offset itself in isolation is not meaningful.

You could also do the same thing with time_parse and then your code would look like:

```<code>if current_user.time_current >= current_user.time_parse("12:00pm")
  # ... Lunch time!
end
</code>```

Or more succinctly:

```<code>if current_user.time_current.hour >= 12
  # ... Lunch time!
end
</code>```

Body:
I am trying to see if the current time is after noon (lunch).

  noon_time = Time.parse "12:00 pm"
  current_time = Time.now
  if current_time < noon_time
    #eat a big meal or sleep its after lunch time
  else
    #work hard its not time to eat
  end

When I run this code at 9:38pm it says "eat a big meal".

Do I need to do something like this and capture the time that is set for my website by the user?

  offset = Time.now.in_time_zone(current_user.time_zone).gmt_offset/60/60

Body:
You could try parsing the time from the perspective of the user:

Time.zone(current_user.time_zone).parse("12:00pm")

If you use Time.now you're using it in the default time zone which is, presumably, UTC. It might be a good idea make a wrapper method time_current for your User model that returns the time in the correct time zone? The offset itself in isolation is not meaningful.

You could also do the same thing with time_parse and then your code would look like:

if current_user.time_current >= current_user.time_parse("12:00pm")
  # ... Lunch time!
end

Or more succinctly:

if current_user.time_current.hour >= 12
  # ... Lunch time!
end


问:
Failed to install pymssql using pip and linking to FreeTDS installed using fink on a Mac
I am running MacOS 10.11.6 (El Capitan) on an iMac. I have set up a Python 3.4.7 virtual environment and I have pip (9.0.1) installed various packages including numpy, pandas, scipy etc. However, I'm having difficulty installing pymssql using. I understand that I need to install FreeTDS first and I have done that using fink (which installed freetds version 0.91-5). However, when I activate a virtual environment and run:

pip install pymssql

I get the following error message (apologies for the size of it):

```<code>Collecting pymssql
  Using cached pymssql-2.1.3.tar.gz
    Complete output from command python setup.py egg_info:
    Download error on https://pypi.python.org/simple/setuptools_git/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    Download error on https://pypi.python.org/simple/setuptools-git/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    Couldn't find index page for 'setuptools_git' (maybe misspelled?)
    Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    No local packages or working download links found for setuptools_git
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/75/qtnqhywh8xj9760059b8dbd80000gq/T/pip-build-pyxahulz/pymssql/setup.py", line 477, in <module>
        ext_modules = ext_modules(),
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/__init__.py", line 128, in setup
        _install_setup_requires(attrs)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/__init__.py", line 123, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/dist.py", line 453, in fetch_build_eggs
        replace_conflicting=True,
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 866, in resolve
        replace_conflicting=replace_conflicting
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1146, in best_match
        return self.obtain(req, installer)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1158, in obtain
        return installer(requirement)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/dist.py", line 520, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 666, in easy_install
        raise DistutilsError(msg)
    distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('setuptools_git')
    setup.py: platform.system() => 'Darwin'
    setup.py: platform.architecture() => ('64bit', '')
    setup.py: platform.libc_ver() => ('', '')
    setup.py: Detected Darwin/Mac OS X.
        You can install FreeTDS with Homebrew or MacPorts, or by downloading
        and compiling it yourself.

        Homebrew (http://brew.sh/)
        --------------------------
        brew install freetds

        MacPorts (http://www.macports.org/)
        -----------------------------------
        sudo port install freetds

    setup.py: Not using bundled FreeTDS
    setup.py: include_dirs = ['/sw/include']
    setup.py: library_dirs = ['/usr/local/lib', '/sw/lib', '/opt/local/lib']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/75/qtnqhywh8xj9760059b8dbd80000gq/T/pip-build-pyxahulz/pymssql/
</code>```

Online instructions describe using Homebrew to install FreeTDS but I've always used fink and don't want to cause conflicts with code installed by two systems.

I've updated fink and pip and I've installed the latest setuptools.

I've tried running:

```<code>pip install --global-option=build_ext --global-option="-L/sw/lib" --global-option="-I/sw/include" pymssql
</code>```

...but no luck.

And I've tried installing an earlier version of pymssql:

```<code>pip install pymssql==2.1.1
</code>```

Again, no joy.

Or is the 'certificate verify failed' comment at the start of the error output the key?

I'm sure I've install MSSQL previously on other machines and I don't recall a problem. I also don't recall what I did differently (if anything).

Can anyone help me to resolve this issue, please.

答:
The original virtual environment had been created using Python 3.4.7 that had been installed using fink.

I ended up deleting this virtual environment and recreating a new virtual environment using python 3.4.4 downloaded from python.org. The packages were reinstalled (using pip freeze) and pymssql installed with no problems at all.

So, although I still don't know what caused the original problem, at least I now have a working environment.

Body:
I am running MacOS 10.11.6 (El Capitan) on an iMac. I have set up a Python 3.4.7 virtual environment and I have pip (9.0.1) installed various packages including numpy, pandas, scipy etc. However, I'm having difficulty installing pymssql using. I understand that I need to install FreeTDS first and I have done that using fink (which installed freetds version 0.91-5). However, when I activate a virtual environment and run:

pip install pymssql

I get the following error message (apologies for the size of it):

Collecting pymssql
  Using cached pymssql-2.1.3.tar.gz
    Complete output from command python setup.py egg_info:
    Download error on https://pypi.python.org/simple/setuptools_git/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    Download error on https://pypi.python.org/simple/setuptools-git/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    Couldn't find index page for 'setuptools_git' (maybe misspelled?)
    Download error on https://pypi.python.org/simple/: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600) -- Some packages may not be found!
    No local packages or working download links found for setuptools_git
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/private/var/folders/75/qtnqhywh8xj9760059b8dbd80000gq/T/pip-build-pyxahulz/pymssql/setup.py", line 477, in <module>
        ext_modules = ext_modules(),
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/__init__.py", line 128, in setup
        _install_setup_requires(attrs)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/__init__.py", line 123, in _install_setup_requires
        dist.fetch_build_eggs(dist.setup_requires)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/dist.py", line 453, in fetch_build_eggs
        replace_conflicting=True,
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 866, in resolve
        replace_conflicting=replace_conflicting
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1146, in best_match
        return self.obtain(req, installer)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/pkg_resources/__init__.py", line 1158, in obtain
        return installer(requirement)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/dist.py", line 520, in fetch_build_egg
        return cmd.easy_install(req)
      File "/Users/xyz/Documents/python_projects/general_python34_projects/env34/lib/python3.4/site-packages/setuptools/command/easy_install.py", line 666, in easy_install
        raise DistutilsError(msg)
    distutils.errors.DistutilsError: Could not find suitable distribution for Requirement.parse('setuptools_git')
    setup.py: platform.system() => 'Darwin'
    setup.py: platform.architecture() => ('64bit', '')
    setup.py: platform.libc_ver() => ('', '')
    setup.py: Detected Darwin/Mac OS X.
        You can install FreeTDS with Homebrew or MacPorts, or by downloading
        and compiling it yourself.

        Homebrew (http://brew.sh/)
        --------------------------
        brew install freetds

        MacPorts (http://www.macports.org/)
        -----------------------------------
        sudo port install freetds

    setup.py: Not using bundled FreeTDS
    setup.py: include_dirs = ['/sw/include']
    setup.py: library_dirs = ['/usr/local/lib', '/sw/lib', '/opt/local/lib']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /private/var/folders/75/qtnqhywh8xj9760059b8dbd80000gq/T/pip-build-pyxahulz/pymssql/

Online instructions describe using Homebrew to install FreeTDS but I've always used fink and don't want to cause conflicts with code installed by two systems.

I've updated fink and pip and I've installed the latest setuptools.

I've tried running:

pip install --global-option=build_ext --global-option="-L/sw/lib" --global-option="-I/sw/include" pymssql

...but no luck.

And I've tried installing an earlier version of pymssql:

pip install pymssql==2.1.1

Again, no joy.

Or is the 'certificate verify failed' comment at the start of the error output the key?

I'm sure I've install MSSQL previously on other machines and I don't recall a problem. I also don't recall what I did differently (if anything).

Can anyone help me to resolve this issue, please.


问:
MVC route rule to default to Home controller when no controller passed in url
I have some simple views like "About Us" and "Contact Us" that live in the Home controller.

I would prefer the url not have the home part in it like www.xyz.com/ContactUs instead of www.xyz.com/Home/ContactUs

I added a new route that takes care of this but breaks other controllers when not specifying an action in the url

```<code>// Home Routes
RouteTable.Routes.MapRoute("HomeRoute", "{action}", new { controller = "Home", action = "Index" });

// Default
RouteTable.Routes.MapRoute("Default", "{controller}/{action}", new { controller = "Home", action = "Index" });
</code>```

This is obviously because the route engine can't tell which route to use for a url like www.xyz.com/ContactUs and uses the 1st one to match.

I also know I can make controllers for each but this seems like a less efficient way. I'd hate to end up with 30 controllers just to wrap one empty view action per view.

I'll probably end up making controllers for each anyway but wanted to know if there is a way to make a route that says something like "If only one parameter is passed, first check to see if it matches a controller, if not assume it's for the home controller."

答:
You can use MVC Attribute routing to create these SEO friendly routes.

```<code>[Route("About")]
public ActionResult About()
{
    return View();
}
[Route("Contact")]
public ActionResult Contact()
{
    return View();
}
</code>```

Assuming you have attribute routing enabled.

```<code>public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index",
                                                          id = UrlParameter.Optional }

    );
}
</code>```

Another option is to have 2 route registrations similar to what you have tried. It will work for handing the request like yourSite/About/ (it will render executes the About action in your HomeController). But when you request something like yourSite/Books, it will not be handled by Index action of Books controller as that url is matching to the first pattern we defined for SEO friendly routes and you will get a 404 if there is no Books action method in HomeController! (If you did not have this route registration, it would have worked)

```<code>routes.MapRoute(
    name: "JustActions",
    url: "{action}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
</code>```

Another option, if you do not prefer the attribute routing approach, you can register  routes in your RegisterRoutes method for this specific routes one by one. (This is similar to defining the route via attribute routing, but we do it in a single place. Make sure to have the specific routes registered before the generic default one). I personally prefer attribute routing over that as i feel that is more readable.

Body:
I have some simple views like "About Us" and "Contact Us" that live in the Home controller.

I would prefer the url not have the home part in it like www.xyz.com/ContactUs instead of www.xyz.com/Home/ContactUs

I added a new route that takes care of this but breaks other controllers when not specifying an action in the url

// Home Routes
RouteTable.Routes.MapRoute("HomeRoute", "{action}", new { controller = "Home", action = "Index" });

// Default
RouteTable.Routes.MapRoute("Default", "{controller}/{action}", new { controller = "Home", action = "Index" });

This is obviously because the route engine can't tell which route to use for a url like www.xyz.com/ContactUs and uses the 1st one to match.

I also know I can make controllers for each but this seems like a less efficient way. I'd hate to end up with 30 controllers just to wrap one empty view action per view.

I'll probably end up making controllers for each anyway but wanted to know if there is a way to make a route that says something like "If only one parameter is passed, first check to see if it matches a controller, if not assume it's for the home controller."

Body:
You can use MVC Attribute routing to create these SEO friendly routes.

[Route("About")]
public ActionResult About()
{
    return View();
}
[Route("Contact")]
public ActionResult Contact()
{
    return View();
}

Assuming you have attribute routing enabled.

public static void RegisterRoutes(RouteCollection routes)
{
    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

    routes.MapMvcAttributeRoutes();

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index",
                                                          id = UrlParameter.Optional }

    );
}

Another option is to have 2 route registrations similar to what you have tried. It will work for handing the request like yourSite/About/ (it will render executes the About action in your HomeController). But when you request something like yourSite/Books, it will not be handled by Index action of Books controller as that url is matching to the first pattern we defined for SEO friendly routes and you will get a 404 if there is no Books action method in HomeController! (If you did not have this route registration, it would have worked)

routes.MapRoute(
    name: "JustActions",
    url: "{action}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);

Another option, if you do not prefer the attribute routing approach, you can register  routes in your RegisterRoutes method for this specific routes one by one. (This is similar to defining the route via attribute routing, but we do it in a single place. Make sure to have the specific routes registered before the generic default one). I personally prefer attribute routing over that as i feel that is more readable.


Title: Replacing JSON pattern

Body:
My JSON file is like:

{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]

I want to change all the "File" name as "E.kmp". That's why I need to replace "D.kmp" with "E.kmp".If it is possible with python or R, please help me out. Python is preferable.

Body:
Just replace D.kmp with E.kmp

import json
text = '''
{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]
'''

json_data = json.loads(text)
for element in json_data["A"]:
      if element["File"] == "D.kmp":
          element["File"] = "E.kmp"


问:
How to order a list of objects using a list of object attributes
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

```<code>ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break
</code>```

答:
Here's a variation of the scheme using the built-in sorted() function with a custom comparison function. (It may seem like a lot of code, but a significant portion of it is only there for setting up a somewhat realistic test case.)

```<code>from functools import cmp_to_key
import random

random.seed(13)  # Gets consistent "random" ordering during testing.

class User:
    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
        return '{}({!r}, id={!r})'.format(self.__class__.__name__, self.name, self.id)

@cmp_to_key  # Converts cmp function to a key function.
def cmp(x, y):
    """ Return -1 if the position of User x in list_of_ids < index of User y
        otherwise return 1.
    """
    p1, p2 = -1, -1
    try:
        p1 = list_of_ids.index(x.id)
        p2 = list_of_ids.index(y.id)
    except ValueError:
        pass
    return -1 if p1 < p2 else 1

list_of_ids = [3, 2, 5, 8, 9]
# Create a random list of users with these ids.
shuffled_ids = random.sample(list_of_ids, k=len(list_of_ids))
users = [User(name, id) for name, id in zip(['Andy', 'Simon', 'Nick', 'John',
                                             'Roger'], shuffled_ids)]

print('Desired id order:', list_of_ids)
print()
print(' Before:', users)
ordered_result = sorted(users, key=cmp)
print('Ordered:', ordered_result)
</code>```

Output:

Desired id order: [3, 2, 5, 8, 9]

 Before: [User('Andy', id=5), User('Simon', id=9), User('Nick', id=8), User('John', id=3), User('Roger', id=2)]
Ordered: [User('John', id=3), User('Roger', id=2), User('Andy', id=5), User('Nick', id=8), User('Simon', id=9)]
```

Body:
I have a list of objects with ids (object.id) and a list of ids. What is the most efficient way to use the list of ids to order the object list? I have the following solution... just wondering whether there is a faster one?

Input:

result = list of user objects with user ids (user.id)

list_of_ids = list of user ids e.g. [3, 2, 5, 8, 9]

Output:

list of user objects ordered according to list_of_ids

Code:

ordered_result = []
for user_id in list_of_ids:
    for user in result:
        if user_id == user.id:
            ordered_result.append(user)
            break

Body:
Here's a variation of the scheme using the built-in sorted() function with a custom comparison function. (It may seem like a lot of code, but a significant portion of it is only there for setting up a somewhat realistic test case.)

from functools import cmp_to_key
import random

random.seed(13)  # Gets consistent "random" ordering during testing.

class User:
    def __init__(self, name, id):
        self.name = name
        self.id = id

    def __repr__(self):
        return '{}({!r}, id={!r})'.format(self.__class__.__name__, self.name, self.id)

@cmp_to_key  # Converts cmp function to a key function.
def cmp(x, y):
    """ Return -1 if the position of User x in list_of_ids < index of User y
        otherwise return 1.
    """
    p1, p2 = -1, -1
    try:
        p1 = list_of_ids.index(x.id)
        p2 = list_of_ids.index(y.id)
    except ValueError:
        pass
    return -1 if p1 < p2 else 1

list_of_ids = [3, 2, 5, 8, 9]
# Create a random list of users with these ids.
shuffled_ids = random.sample(list_of_ids, k=len(list_of_ids))
users = [User(name, id) for name, id in zip(['Andy', 'Simon', 'Nick', 'John',
                                             'Roger'], shuffled_ids)]

print('Desired id order:', list_of_ids)
print()
print(' Before:', users)
ordered_result = sorted(users, key=cmp)
print('Ordered:', ordered_result)

Output:

Desired id order: [3, 2, 5, 8, 9]

 Before: [User('Andy', id=5), User('Simon', id=9), User('Nick', id=8), User('John', id=3), User('Roger', id=2)]
Ordered: [User('John', id=3), User('Roger', id=2), User('Andy', id=5), User('Nick', id=8), User('Simon', id=9)]


问:
Where can I get Professional Crystal Reports developer support?
I have been struggling for days with a crystal report now. No one can answer my query on stack overflow so is there anywhere I can get some developer support for crystal.

Ideally I want a business objects developer to connect to my machine, look at my code and tell me why the database name refuses to change in any of the examples crystal have provided.

If anyone knows of anyone offering this kind of service, or has some working code to change the database of a crystal report at runtime.

I have asked the question at https://stackoverflow.com/questions/4723903/crystal-report-pain-cant-seem-to-change-database

Why is something that should be so simple such a waste of time!?

答:
Part of the problem with your other question is that you didn't include the "Crystal-reports" tag, just the "Crystal-reports 2008" tag.  The former is more common and gives you a much wider audience.  Fixed.

This doesn't happen too often, but your other question is actually giving users a case of "information overload".  I did a print preview and it came out to 7 pages.  Can you cut back on some of the code? (Yes, you might accidently omit the real source of the problem, but that's just life)

Paid consultants may be more dedicated to finding the answer, but he/she isn't necessarily smarter. Try the official support page @ http://www.sdn.sap.com/irj/boc/support. If you purchase a "maintenance agreement" with SAP, you'll get exactly the professional support you're looking for.

(After all this talking, I'd like to just answer your question and be done with it, but I don't know ASP.)

ContentLicense: CC BY-SA 2.5


问:
Basic code help for chrome console
I understand this is extremely basic but I have almost no coding experience and have yet to find why this function always return undefined please help.

```<code><script>
function myFunction() {
    var x,y;
    y = document.getElementById("nent_nonce");
    z = document.getElementById("next_server_seed_hash");
}
</script>
</code>```

the new code i used i took out the script because it kept giving me and unexpected token < which i intend to fix later

```<code>function x() {
return [ $('#next_nonce').html(), $('#next_server_seed_hash').html() ]
}
</code>```

this is what gave me the undefined although trying either document.getelementbyid worked

答:
JavaScript functions return undefined unless you explicitly return something. Consider:

```<code>function x() {
  5;
}
</code>```

When you call x() you get undefined.

Instead:

```<code>function x() {
  return 5;
}
</code>```

If you don't have a good JavaScript reference you will not get very far without one. The good news is Mozilla has fantastic documentation to get you started.

One solution to returning two elements is to use an array, as in:

```<code>function x() {
  return [
    $('#next_nonce').html(),
    $('#next_server_seed_hash').html()
  ];
}
</code>```

Or you can return a JavaScript object:

```<code>function x() {
  return {
    next_nonce: $('#next_nonce').html(),
    next_server_seed_hash: $('#next_server_seed_hash').html()
  };
}
</code>```

Where using html() implies these are standard HTML elements that have content within them, like
 or
. If these are form elements you should use val() to get the value="..." property within the tag.

Title: Basic code help for chrome console

Body:
I understand this is extremely basic but I have almost no coding experience and have yet to find why this function always return undefined please help.

the new code i used i took out the script because it kept giving me and unexpected token < which i intend to fix later

function x() {
return [ $('#next_nonce').html(), $('#next_server_seed_hash').html() ]
}

this is what gave me the undefined although trying either document.getelementbyid worked

Body:
JavaScript functions return undefined unless you explicitly return something. Consider:

function x() {
  5;
}

When you call x() you get undefined.

Instead:

function x() {
  return 5;
}

If you don't have a good JavaScript reference you will not get very far without one. The good news is Mozilla has fantastic documentation to get you started.

One solution to returning two elements is to use an array, as in:

function x() {
  return [
    $('#next_nonce').html(),
    $('#next_server_seed_hash').html()
  ];
}

Or you can return a JavaScript object:

function x() {
  return {
    next_nonce: $('#next_nonce').html(),
    next_server_seed_hash: $('#next_server_seed_hash').html()
  };
}

Where using html() implies these are standard HTML elements that have content within them, like <div> or <p>. If these are form elements you should use val() to get the value="..." property within the tag.


问:
Java Socket Programming in Overrided Start Function
I am new to using JavaFx and its functionality. I am creating a 2 player checkers game that is played by local connection. I understand that in JavaFX you do not need a main class because the @Override on the start function basically serves as your main. Right now I have my connection trying to be made in that start function but it keeps spitting back java.net.BindException and java.lang.RuntimeException every time I try. I looked at my ports and it is not in use. I commented out the connection portion of the code and the app was able to run. Are you not able to connect in the start function?

Client Code:

```<code> @Override
   public void start(Stage primaryStage) throws Exception, ClassNotFoundException, IOException,UnknownHostException {
       Scene scene1 = new Scene(createContent());
       primaryStage.setTitle("Client Side");
       primaryStage.setScene(scene1);
       primaryStage.show();

       socket = new Socket("127.0.0.1",1337);

       boolean end = false;
       boolean turn = true;
       Serializable ObjectInputStream;
        ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
        Serializable ObjectOutputStream;
        ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
        Scanner scan = new Scanner(socket.getInputStream());
        PrintStream p = new PrintStream(socket.getOutputStream());
       do
       {

        while(turn == true)
           {
               temp1 = scan.nextInt();
               temp2 = scan.nextInt();
               Checker check = (Checker) I.readObject();
               check.relocate(temp1, temp2);
               turn = false;
           }
           while(turn == false)
           {

               p.println(sendX);
               p.println(sendY);
               o.writeObject(sendO);
               turn = true;

           }

       }while(end == false);

   }
</code>```

Server Code is just reverse of that:

```<code>   @Override
   public void start(Stage primaryStage) throws Exception,
   ClassNotFoundException, IOException,UnknownHostException {
   Scene scene = new Scene(createContent());
   primaryStage.setTitle("Server Side");
   primaryStage.setScene(scene);
   primaryStage.show();

   serverSocket = new ServerSocket(1337);
   Socket socket = serverSocket.accept();
   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
    ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
    Scanner scan = new Scanner(socket.getInputStream());
    PrintStream p = new PrintStream(socket.getOutputStream());
   do
   {

    while(turn == true)
       {
        p.println(sendX);
        p.println(sendY);
        o.writeObject(sendO);
        turn = false;
       }
       while(turn == false)
       {

        temp1 = scan.nextInt();
        temp2 = scan.nextInt();
        Checker check = (Checker) I.readObject();
        check.relocate(temp1, temp2);
        turn = true;

       }

   }while(end == false);

   }
</code>```

答:
Use Try catch Block

```<code> try {
       serverSocket = new ServerSocket(1337);
       Socket socket = serverSocket.accept();
    }
    catch (IOException e) {
       System.out.println(e);
    }

   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
   ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
   ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
   Scanner scan = new Scanner(socket.getInputStream());
   PrintStream p = new PrintStream(socket.getOutputStream());
  do
  {

     while(turn == true)
   {
    p.println(sendX);
    p.println(sendY);
    o.writeObject(sendO);
    turn = false;
   }
   while(turn == false)
   {

    temp1 = scan.nextInt();
    temp2 = scan.nextInt();
    Checker check = (Checker) I.readObject();
    check.relocate(temp1, temp2);
    turn = true;

   }

   }while(end == false);

   }
</code>```

Body:
I am new to using JavaFx and its functionality. I am creating a 2 player checkers game that is played by local connection. I understand that in JavaFX you do not need a main class because the @Override on the start function basically serves as your main. Right now I have my connection trying to be made in that start function but it keeps spitting back java.net.BindException and java.lang.RuntimeException every time I try. I looked at my ports and it is not in use. I commented out the connection portion of the code and the app was able to run. Are you not able to connect in the start function?

Client Code:

 @Override
   public void start(Stage primaryStage) throws Exception, ClassNotFoundException, IOException,UnknownHostException {
       Scene scene1 = new Scene(createContent());
       primaryStage.setTitle("Client Side");
       primaryStage.setScene(scene1);
       primaryStage.show();

       socket = new Socket("127.0.0.1",1337);

       boolean end = false;
       boolean turn = true;
       Serializable ObjectInputStream;
        ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
        Serializable ObjectOutputStream;
        ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
        Scanner scan = new Scanner(socket.getInputStream());
        PrintStream p = new PrintStream(socket.getOutputStream());
       do
       {

        while(turn == true)
           {
               temp1 = scan.nextInt();
               temp2 = scan.nextInt();
               Checker check = (Checker) I.readObject();
               check.relocate(temp1, temp2);
               turn = false;
           }
           while(turn == false)
           {

               p.println(sendX);
               p.println(sendY);
               o.writeObject(sendO);
               turn = true;

           }

       }while(end == false);

   }

Server Code is just reverse of that:

   @Override
   public void start(Stage primaryStage) throws Exception,
   ClassNotFoundException, IOException,UnknownHostException {
   Scene scene = new Scene(createContent());
   primaryStage.setTitle("Server Side");
   primaryStage.setScene(scene);
   primaryStage.show();

   serverSocket = new ServerSocket(1337);
   Socket socket = serverSocket.accept();
   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
    ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
    ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
    Scanner scan = new Scanner(socket.getInputStream());
    PrintStream p = new PrintStream(socket.getOutputStream());
   do
   {

    while(turn == true)
       {
        p.println(sendX);
        p.println(sendY);
        o.writeObject(sendO);
        turn = false;
       }
       while(turn == false)
       {

        temp1 = scan.nextInt();
        temp2 = scan.nextInt();
        Checker check = (Checker) I.readObject();
        check.relocate(temp1, temp2);
        turn = true;

       }

   }while(end == false);

   }

Body:
Use Try catch Block

 try {
       serverSocket = new ServerSocket(1337);
       Socket socket = serverSocket.accept();
    }
    catch (IOException e) {
       System.out.println(e);
    }

   boolean end = false;
   boolean turn = true;
   Serializable ObjectInputStream;
   Serializable ObjectOutputStream;
   ObjectInputStream I = new ObjectInputStream(socket.getInputStream());
   ObjectOutputStream o = new ObjectOutputStream(socket.getOutputStream());
   Scanner scan = new Scanner(socket.getInputStream());
   PrintStream p = new PrintStream(socket.getOutputStream());
  do
  {

     while(turn == true)
   {
    p.println(sendX);
    p.println(sendY);
    o.writeObject(sendO);
    turn = false;
   }
   while(turn == false)
   {

    temp1 = scan.nextInt();
    temp2 = scan.nextInt();
    Checker check = (Checker) I.readObject();
    check.relocate(temp1, temp2);
    turn = true;

   }

   }while(end == false);

   }


问:
Split from a specific delimiter
How to rip a URL like http://www.facebook.com/pages/create.php to have a result like this: www.facebook.com?

I tried this way, but doesn't work:

```<code>line.split('/', 2)[2]
</code>```

My problem is probably with that two forward slashes // and some of the URLs start from the www strings.

Thanks for your help, Adia

答:
You might want to look at Python's urlparse module.</p>

```<code>>>> from urlparse import urlparse
>>> o = urlparse('http://www.facebook.com/pages/create.php')
>>> o.netloc
'www.facebook.com'
</code>```

Title: Split from a specific delimiter

Body:
How to rip a URL like http://www.facebook.com/pages/create.php to have a result like this: www.facebook.com?

I tried this way, but doesn't work:

line.split('/', 2)[2]

My problem is probably with that two forward slashes // and some of the URLs start from the www strings.

Thanks for your help, Adia

Body:
You might want to look at Python's urlparse module.

>>> from urlparse import urlparse
>>> o = urlparse('http://www.facebook.com/pages/create.php')
>>> o.netloc
'www.facebook.com'


问:
IronPython: Unexpected token 'from'
i was running python script from .net using IronPython, below is my python script

```<code>import tensorflow as tf
print('Tensorflow Imported')
</code>```

below is C# Code

```<code>using System;
using System.Text;
using System.IO;
using IronPython.Hosting;
using System.Collections.Generic;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main()
        {
            var py = Python.CreateEngine();
            List<string> searchPaths = new List<string>();
            searchPaths.Add(@"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib)");
            searchPaths.Add(@"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib\site-packages)");
            py.SetSearchPaths(searchPaths);
            try
            {
                py.ExecuteFile("script.py");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}
</code>```

below is my output

Unexpected token 'from'

if i remove import statement then python script executes fine. I tried including os,sys all those were imported without any issue. I have installed TensorFlow via pip, when i run above script through python console(v3.5) it works fine.

Update: in TF doc its written "TensorFlow only supports version 3.5.x of Python on Windows". but official release of IronPython is version 2.7
I was happy to find IronPython on GitHub, tried building it (i just typed build in console and got freaked out with the long list of error messages it showed! :D
couldn't find pre-compiled binaries

is there any alternative way to import tensorflow in IronPython 2.7 or run Python in .net?

答:
Prakash - as you found in the documentation, TensorFlow requires Python 3.5 or 3.6 when running on Windows.  It won't run in IronPython 2.7.

One user on GitHub successfully (with a lot of work and in a not-easy-to-do) way got TF running on Windows under Python2.7, and you might be able to build on their work, but it's not exactly the solution you were looking for for IronPython.  My best suggestion is to go with 3.5 or 3.6.

Title: IronPython: Unexpected token 'from'

Body:
i was running python script from .net using IronPython, below is my python script

import tensorflow as tf
print('Tensorflow Imported')

below is C# Code

using System;
using System.Text;
using System.IO;
using IronPython.Hosting;
using System.Collections.Generic;
using Microsoft.Scripting.Hosting;

namespace ConsoleApplication1
{
    class Program
    {
        private static void Main()
        {
            var py = Python.CreateEngine();
            List<string> searchPaths = new List<string>();
            searchPaths.Add(@"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib)");
            searchPaths.Add(@"C:\Users\Admin\AppData\Local\Programs\Python\Python35\Lib\site-packages)");
            py.SetSearchPaths(searchPaths);
            try
            {
                py.ExecuteFile("script.py");
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
    }
}

below is my output

Unexpected token 'from'

if i remove import statement then python script executes fine. I tried including os,sys all those were imported without any issue. I have installed TensorFlow via pip, when i run above script through python console(v3.5) it works fine.

Update: in TF doc its written "TensorFlow only supports version 3.5.x of Python on Windows". but official release of IronPython is version 2.7
I was happy to find IronPython on GitHub, tried building it (i just typed build in console and got freaked out with the long list of error messages it showed! :D
couldn't find pre-compiled binaries

is there any alternative way to import tensorflow in IronPython 2.7 or run Python in .net?


问:
IndexError: Extract table from a webpage using BeautifulSoup
I am trying to extract a table (with columns - flight, carrier, origin, date, scheduled, estimated, status) containing flight arrival information from an airport website, but I got the error below:

```<code>  IndexError Traceback (most recent call last)
  <ipython-input-39-2f7369a95ba9> in <module>()
        6  for cl in cols:
        7  dv = cl.findAll('div')
  ----> 8  if 'col-xs-12 col-sm-6' in dv[0]['class']:
        9  flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
       10 print(flight, carrier, origin, date, scheduled, estimated, status)
  IndexError: list index out of range
</code>```

I have combed stackoverflow for solution but could not find solution. Here is my code:

```<code>  # import libraries
  import urllib3
  import requests
  from bs4 import BeautifulSoup

  # query the website and return the html to the variable ‘page’
  page = requests.get("https://www.aucklandairport.co.nz/flights").text

  soup = BeautifulSoup(page)
  tbody = soup.findAll('tbody')
  for tb in tbody:
    rows = tb.findAll('tr')
    for tr in rows:
      cols = tr.findAll('td')
        for cl in cols:
          dv = cl.findAll('div')
          if 'col-xs-12 col-sm-6' in dv[0]['class']:
             flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
             print(flight, carrier, origin, date, scheduled, estimated, status)
</code>```

Thanks for your contribution.

答:
The problem is that the first td under tr don't have the div, that's why dv will return empty. change your code to:

```<code># import libraries
import requests
from bs4 import BeautifulSoup

# query the website and return the html to the variable ‘page’
page = requests.get("https://www.aucklandairport.co.nz/flights").text

soup = BeautifulSoup(page)
tbody = soup.find('tbody')
rows = tbody.findAll('tr',{'class':'flight-toggle'}) #find tr whose class = flight-toggle
for tr in rows:
    cols = tr.findAll('td',class_=lambda x: x != 'logo') # find td whose class!=logo (exclude the first td)
    dv0 = cols[0].find('div').findAll('div') #flight, carrier, origin under second td
    flight, carrier, origin = [c.text.strip() for c in dv0]
    dv1 = cols[1].find('div').findAll('div') #date, schedule under third td
    date, scheduled = [c.text.strip() for c in dv1]
    dv2 = cols[2].find('div').findAll('div') #estimated, statusunder fouth td
    estimated, status = [c.text.strip() for c in dv2[1:]] # exclude the first div
    print(flight, carrier, origin, date, scheduled, estimated, status)
</code>```

This will print out:

```<code>(u'EK406', u'', u'Dubai / Melbourne', u'18 Nov', u'01:55pm', u'02:47pm', u'Processing')
(u'QF8762', u'EK406', u'Dubai / Melbourne', u'18 Nov', u'01:55pm', u'02:47pm', u'Processing')
(u'EK434', u'', u'Dubai / Brisbane', u'18 Nov', u'02:45pm', u'02:49pm', u'Processing')
...
</code>```

Body:
I am trying to extract a table (with columns - flight, carrier, origin, date, scheduled, estimated, status) containing flight arrival information from an airport website, but I got the error below:

  IndexError Traceback (most recent call last)
  <ipython-input-39-2f7369a95ba9> in <module>()
        6  for cl in cols:
        7  dv = cl.findAll('div')
  ----> 8  if 'col-xs-12 col-sm-6' in dv[0]['class']:
        9  flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
       10 print(flight, carrier, origin, date, scheduled, estimated, status)
  IndexError: list index out of range

I have combed stackoverflow for solution but could not find solution. Here is my code:

  # import libraries
  import urllib3
  import requests
  from bs4 import BeautifulSoup

  # query the website and return the html to the variable ‘page’
  page = requests.get("https://www.aucklandairport.co.nz/flights").text

  soup = BeautifulSoup(page)
  tbody = soup.findAll('tbody')
  for tb in tbody:
    rows = tb.findAll('tr')
    for tr in rows:
      cols = tr.findAll('td')
        for cl in cols:
          dv = cl.findAll('div')
          if 'col-xs-12 col-sm-6' in dv[0]['class']:
             flight, carrier, origin, date, scheduled, estimated, status = [c.text for c in dv]
             print(flight, carrier, origin, date, scheduled, estimated, status)

Thanks for your contribution.

Body:
The problem is that the first td under tr don't have the div, that's why dv will return empty. change your code to:

# import libraries
import requests
from bs4 import BeautifulSoup

# query the website and return the html to the variable ‘page’
page = requests.get("https://www.aucklandairport.co.nz/flights").text

soup = BeautifulSoup(page)
tbody = soup.find('tbody')
rows = tbody.findAll('tr',{'class':'flight-toggle'}) #find tr whose class = flight-toggle
for tr in rows:
    cols = tr.findAll('td',class_=lambda x: x != 'logo') # find td whose class!=logo (exclude the first td)
    dv0 = cols[0].find('div').findAll('div') #flight, carrier, origin under second td
    flight, carrier, origin = [c.text.strip() for c in dv0]
    dv1 = cols[1].find('div').findAll('div') #date, schedule under third td
    date, scheduled = [c.text.strip() for c in dv1]
    dv2 = cols[2].find('div').findAll('div') #estimated, statusunder fouth td
    estimated, status = [c.text.strip() for c in dv2[1:]] # exclude the first div
    print(flight, carrier, origin, date, scheduled, estimated, status)

This will print out:

(u'EK406', u'', u'Dubai / Melbourne', u'18 Nov', u'01:55pm', u'02:47pm', u'Processing')
(u'QF8762', u'EK406', u'Dubai / Melbourne', u'18 Nov', u'01:55pm', u'02:47pm', u'Processing')
(u'EK434', u'', u'Dubai / Brisbane', u'18 Nov', u'02:45pm', u'02:49pm', u'Processing')
...


问:
How to limit the amount of characters a javafx textfield
I´m using a FXML to set my form, but I need to set the limit of characters in textfields. How can I made this ?</p>

答:
I use a simple call to ChangeListener, where I test the condition to perform stops.</p>

```<code>textFild.addListener((observable, oldValue, newValue) -> {
    if (newValue.length() == MAX_SIZE) {
        textField.setText(oldValue);
    }
});
</code>```

Body:
I use a simple call to ChangeListener, where I test the condition to perform stops.

textFild.addListener((observable, oldValue, newValue) -> {
    if (newValue.length() == MAX_SIZE) {
        textField.setText(oldValue);
    }
});


问:
Making list of unique numbers
I am trying to make a list of unique numbers and I am getting the wrong output.

I want to get each unique number from a file where each line has two numbers:
friends=['4 6', '4 7', '4 8', '5 9', '6 8', '7 8', '100 112', '112 114', '78 44']

Answer:
user=['4', '6', '7', '8','44','78', '100', '112', '114']

However my following code outputs user= ['0', '1', '2', '4', '5', '6', '7', '8', '9'] instead

I am unsure of how to make my code recognize two and three digit numbers in the file, basically this my problem

```<code>user=[]
for row in friends:
    for column in row:
            if column not in user and column.isdigit():
                user.append(column)

    user.sort()
print(user)
</code>```

*I am not allowed to use dictionaries, sets, deque, bisect module

答:
@downshift, I think I got it!! Thank you :)</p>

```<code>def get_numbers(mylist):
    nums = []
    for i in mylist:
        nums.append(i.split())
        for i in range(len(nums)):
            for j in range(len(nums[0])):
                nums[i][j]= int(nums[i][j])
    return nums

print(get_numbers(mylist))
</code>```

Title: Making list of unique numbers

Body:
I am trying to make a list of unique numbers and I am getting the wrong output.

I want to get each unique number from a file where each line has two numbers:
friends=['4 6', '4 7', '4 8', '5 9', '6 8', '7 8', '100 112', '112 114', '78 44']

Answer:
user=['4', '6', '7', '8','44','78', '100', '112', '114']

However my following code outputs user= ['0', '1', '2', '4', '5', '6', '7', '8', '9'] instead

I am unsure of how to make my code recognize two and three digit numbers in the file, basically this my problem

user=[]
for row in friends:
    for column in row:
            if column not in user and column.isdigit():
                user.append(column)

    user.sort()
print(user)

*I am not allowed to use dictionaries, sets, deque, bisect module

Body:
@downshift, I think I got it!! Thank you :)

def get_numbers(mylist):
    nums = []
    for i in mylist:
        nums.append(i.split())
        for i in range(len(nums)):
            for j in range(len(nums[0])):
                nums[i][j]= int(nums[i][j])
    return nums

print(get_numbers(mylist))


问:
tensorflow Protobuf Compilation issue
I want to compile protobuf libraries for google object detection API. I followed the official tutorial and typed protoc object_detection/protos/*.proto --python_out=.. Then what I got is "object_detection/protos/*.proto: Invalid argument". Can anyone tell me what should I do? Thanks!

答:
If your operating system is windows, then *. may not work. A good way to solve this problem is to use bash. Download git for windows, don't forget to select git bash when you install it.
From tensorflow/models/research/, right click, select git bash, then paste the command, it works well on my laptop.</p>

Title: tensorflow Protobuf Compilation issue


问:
How to check which values have overlapping keys in a dictionary?
I have a dictionary:

```<code>{0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
</code>```

And then I take an input which references one of the keys:

```<code>flag = 0
user = input("Enter an integer for a user ID: ")
if isinstance(user, float):
    flag = 1
if user.isdigit() and int(user) >= 0 and int(user) <= (len(network)-1) and flag == 0:
    return(user)
else:
    while user.isdigit() == False or int(user) < 0 or int(user) > (len(network)-1):
        user = input("Enter an integer for a user ID: ")
</code>```

So now I need to help to understand to find the values with overlapping keys, for example, if the user chooses 4 the code would output:

```<code>"For user with ID 4 we recommend the user with ID 2"
"That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else."
</code>```

Also the users cannot know each other.  So even though 4 has more in common with 0, they know each other and therefore do not work.

Thanks!

答:
The easiest is to convert your friend lists to sets. You can do this using a dict comprehension like so

```<code>d  = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
ds = {k:set(v) for k, v in d.items()}
</code>```

Now you can find the shared friends of, say, 2 and 4 by intersecting

```<code>ds[2] & ds[4]

-> {0, 8, 6}
</code>```

and you can count them using len

```<code>len(ds[2] & ds[4])
</code>```

Finally, you can make a loop to find the best match (a is the input, b is the output):

```<code>def best_match_for(a):
    b = None
    af = ds[a]
    best = -1
    for k, v in ds.items():
        if k!=a and not k in af:
            ovlp = len(af & v)
            if ovlp > best:
                best = ovlp
                b = k
    return b, best if best > 0 else None
</code>```

Body:
I have a dictionary:

{0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}

And then I take an input which references one of the keys:

flag = 0
user = input("Enter an integer for a user ID: ")
if isinstance(user, float):
    flag = 1
if user.isdigit() and int(user) >= 0 and int(user) <= (len(network)-1) and flag == 0:
    return(user)
else:
    while user.isdigit() == False or int(user) < 0 or int(user) > (len(network)-1):
        user = input("Enter an integer for a user ID: ")

So now I need to help to understand to find the values with overlapping keys, for example, if the user chooses 4 the code would output:

"For user with ID 4 we recommend the user with ID 2"
"That is because users 4 and 2 have 3 common friends and user 4 does not have more common friends with anyone else."

Also the users cannot know each other.  So even though 4 has more in common with 0, they know each other and therefore do not work.

Thanks!

Body:
The easiest is to convert your friend lists to sets. You can do this using a dict comprehension like so

d  = {0: [1, 2, 3, 4, 5, 6, 7, 8, 9], 1: [0, 9, 4, 6, 7], 2: [8, 9, 3, 6, 0], 3: [8, 9, 2, 0], 4: [8, 0, 1, 6, 7], 5: [0, 9], 6: [8, 0, 2, 4, 1], 7: [8, 0, 4, 1], 8: [0, 2, 3, 4, 6, 7], 9: [0, 1, 2, 3, 5]}
ds = {k:set(v) for k, v in d.items()}

Now you can find the shared friends of, say, 2 and 4 by intersecting

ds[2] & ds[4]

-> {0, 8, 6}

and you can count them using len

len(ds[2] & ds[4])

Finally, you can make a loop to find the best match (a is the input, b is the output):

def best_match_for(a):
    b = None
    af = ds[a]
    best = -1
    for k, v in ds.items():
        if k!=a and not k in af:
            ovlp = len(af & v)
            if ovlp > best:
                best = ovlp
                b = k
    return b, best if best > 0 else None


问:
Send-MailMessage command in a single line not working
I am trying to make a single line Send-MailMessage command. I came out with this code:

```<code>Send-MailMessage -SmtpServer 'smtp.gmail.com' -Port 587 -From 'my_email@gmail.com' -To 'someone_email@gmail.com' -Subject 'Test' -Body 'Body' -UseSsl -Credential (New-Object System.Management.Automation.PSCredential('my_email@gmail.com', (ConvertTo-SecureString 'my_pass' -AsPlainText -Force)))
</code>```

And I got this error:

```<code>Send-MailMessage : A parameter cannot be found that matches parameter name 'Port'.
At G:\Send_email\TEST-SEND-EMAIL.ps1:1 char:23
+ Send-MailMessage -Port <<<<  587 -SmtpServer 'smtp.gmail.com' -From 'my_email@gmail.com' -To 'someone_email@gmail.com' -Subject 'Test' -Body 'Body' -UseSsl -Credential (New-Object system.Management.Automation.PSCredential('my_email@gmail.com', (ConvertTo-SecureString 'my_password' -AsPlainText -Force)))
+ CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SendMailMessage
</code>```

Please help me!!

答: The Port parameter did not appear until PowerShell V 3.0. Download and install the latest Windows Management Framework and try it.</p>

Body:
I am trying to make a single line Send-MailMessage command. I came out with this code:

Send-MailMessage -SmtpServer 'smtp.gmail.com' -Port 587 -From 'my_email@gmail.com' -To 'someone_email@gmail.com' -Subject 'Test' -Body 'Body' -UseSsl -Credential (New-Object System.Management.Automation.PSCredential('my_email@gmail.com', (ConvertTo-SecureString 'my_pass' -AsPlainText -Force)))

And I got this error:

Send-MailMessage : A parameter cannot be found that matches parameter name 'Port'.
At G:\Send_email\TEST-SEND-EMAIL.ps1:1 char:23
+ Send-MailMessage -Port <<<<  587 -SmtpServer 'smtp.gmail.com' -From 'my_email@gmail.com' -To 'someone_email@gmail.com' -Subject 'Test' -Body 'Body' -UseSsl -Credential (New-Object system.Management.Automation.PSCredential('my_email@gmail.com', (ConvertTo-SecureString 'my_password' -AsPlainText -Force)))
+ CategoryInfo          : InvalidArgument: (:) [Send-MailMessage], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.SendMailMessage

Please help me!!


答:
Since I can't see your entire JSON structure, here is how to do it with replace()</p>

```<code>with open('file.json', 'r') as file :
    data = file.read()

data = data.replace('"File": "D.kmp"', '"File": "E.kmp"')

with open('file.json', 'w') as file:
    file.write(data)
</code>```

Title: Replacing JSON pattern

Body:
My JSON file is like:

{"A":[
{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp", "C":{....},
{"Timestamp": "2017-11-14 14:40:32", "File": "E.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:41:32", "File": "E.kmp", "L":{....},
................................................................,
{"Timestamp": "2017-11-14 14:42:32", "File": "D.kmp", "L":{....},
{"Timestamp": "2017-11-14 14:43:32", "File": "D.kmp", "L":{....}
]

I want to change all the "File" name as "E.kmp". That's why I need to replace "D.kmp" with "E.kmp".If it is possible with python or R, please help me out. Python is preferable.

Body:
Since I can't see your entire JSON structure, here is how to do it with replace()

with open('file.json', 'r') as file :
    data = file.read()

data = data.replace('"File": "D.kmp"', '"File": "E.kmp"')

with open('file.json', 'w') as file:
    file.write(data)


答:
I guess there are simple way:</p>

```<code>your_json['A'] =[i for i in your_json['A'] if not i.update({"File":"D.kmp"})]
</code>```

Title: Replacing JSON pattern

Body:
I guess there are simple way:

your_json['A'] =[i for i in your_json['A'] if not i.update({"File":"D.kmp"})]


问:
How to display the average of multiple runs on tensorboard
Is there a way to display the average of multiple different runs on tensorflow?
 I can only see them on the same graph (by sending the path of the different runs), but I want to see their average on the graph</p>

答: Please follow issue 376 to see progress on this.  It's an active feature request with some progress in the last month, but as of now, there's not a way to do what you want.  Yet.</p>


问:
How is recursion possible in AVR Assembly?
I can't seem to wrap my head around recursion in Assembly Language. I understand how it works in higher level languages, but I don't understand how it is possible in assembly when the return value cannot be passed directly to the function. </p>

<p>I'm trying to make a recursive factorial function in AVR, but I don't understand how the stack passes the value when factorial requires n * (n-1), requiring both n and n-1 simultaneously </p>

答:
Using addition instead of multiplication

```<code>unsigned int accumulate(unsigned int n)
{
    if(n) return(n+accumulate(n-1));
    return(1);
}
</code>```

and a different instruction set, perhaps easier to follow

```<code>00000000 <accumulate>:
   0:   e3500000    cmp r0, #0
   4:   0a000005    beq 20 <accumulate+0x20>
   8:   e3a03000    mov r3, #0
   c:   e0833000    add r3, r3, r0
  10:   e2500001    subs    r0, r0, #1
  14:   1afffffc    bne c <accumulate+0xc>
  18:   e2830001    add r0, r3, #1
  1c:   e12fff1e    bx  lr
  20:   e3a00001    mov r0, #1
  24:   e12fff1e    bx  lr
</code>```

In this case the compiler didnt actually call the function, it detected what was going on and just made a loop.

Since there is nothing magic about recursion there is no difference in whether you call the same function or some other function.

```<code>unsigned int otherfun ( unsigned int );
unsigned int accumulate(unsigned int n)
{
    if(n) return(n+otherfun(n-1));
    return(1);
}

00000000 <accumulate>:
   0:   e92d4010    push    {r4, lr}
   4:   e2504000    subs    r4, r0, #0
   8:   03a00001    moveq   r0, #1
   c:   0a000002    beq 1c <accumulate+0x1c>
  10:   e2440001    sub r0, r4, #1
  14:   ebfffffe    bl  0 <otherfun>
  18:   e0800004    add r0, r0, r4
  1c:   e8bd4010    pop {r4, lr}
  20:   e12fff1e    bx  lr
</code>```

so this shows how it works.  Instead of using the stack to store the sum, the cheaper solution if you have the registers is to use a non-volatile register save that register to the stack then use that register during the funciton, depends on how many registers you have and how many local intermediate values you need to track.  So r4 gets a copy of n coming in, then that is added (for factorial it is a multiply which depending on the instruction set and code can produce a lot more code that can confuse the understanding so I used addition instead) to the return value from the call to the next function (with recursion where the compiler didnt figure out what we were doing this would have been a call to ourselves, and we can write this asm and make it a call to ourselves to see how it works)

Then the function returns the sum.

If we assume that otherfun is really accumulate we enter this function with a 4 lets say

```<code>00000000 <accumulate>:
   0:   e92d4010    push    {r4, lr}
   4:   e2504000    subs    r4, r0, #0
   8:   03a00001    moveq   r0, #1
   c:   0a000002    beq 1c <accumulate+0x1c>
  10:   e2440001    sub r0, r4, #1
  14:   ebxxxxxx    bl  accumulate
  18:   e0800004    add r0, r0, r4
  1c:   e8bd4010    pop {r4, lr}
  20:   e12fff1e    bx  lr

r4 and lr are saved on the stack (call this r4-4 and lr-4)
r4 = n (4)
r0 = n-1 (3)
call accumulate with n-1 (3)
r4 (4) and lr are saved on the stack (r4-3, lr-3) lr now points back into
r4 = n (3)
r0 = n-1 (2)
call accumulate with n-1 (2)
r4 (3) and lr are saved on the stack (r4-2, lr-2)
r4 = n (2)
r0 = n-1 (1)
call accumulate with n-1 (1)
r4 (2) and lr are saved on the stack (r4-1, lr-1)
r0 = n-1 (0)
call accumulate with n-1 (0)
now things change...
r0 = 1
return to lr-1 which is into accumulate after the call to accumulate
r4 gets 2 from the stack
r0 (1) = r0 (1) + r4 (2) = 3
return to lr-2 which is into accumulate r4 gets 3 from the stack
r0 (3) = r0 (3) + r4 (3) = 6
return to lr-3 which is into accumulate r4 gets 4 from the stack
r0 (6) = r0 (6) + r4 (4) = 10
return to lr-4 which is the function that called accumulate r4 is restored
to what it was before accumulate was first called, r4 is non-volatile you have to for this instruction set return r4 the way you found it (as well
as others, but we didnt modify those)
</code>```

so the addition in this case multiplication in your desired case is

result = 1 + 2 + 3 + 4

How that happened is we basically pushed n on the stack then called the function with n-1.  In this case we push 4, 3, 2, 1 then we start to unwind that and each return processes 1 then 2 then 3 then 4 as it returns
taking those from the stack essentially.

the bottom line is you dont have to care about recursion to support recursion simply use an abi that supports recursion, which is not hard to
do, then hand code the instructions in assembly as if you were the compiler

Maybe this makes it easier to see.  n coming in is both a parameter coming in but also for the duration of the function it is a local variable, local
variables go on the stack.

```<code>unsigned int accumulate(unsigned int n)
{
    unsigned int m;
    m = n;
    if(n) return(m+accumulate(n-1));
    return(1);
}
</code>```

back to this

```<code>unsigned int accumulate(unsigned int n)
{
    if(n) return(n+accumulate(n-1));
    return(1);
}
</code>```

so independent of the instruction set

```<code>accumulate:
  if(n!=0) jump over
  return_reg = 1
  return
  over:
  push n on the stack
  first parameter (stack or register) = n - 1
  call accumulate
  pop or load n from the stack
  return_reg = return_reg + n
  clean stack
  return
</code>```

And also deal with return addresses for the instruction set if required.
The ABI may use the stack to pass parameters or registers.

If I didnt follow the arm abi I could implement

```<code>accumulate:
   cmp r0,#0
   bne over
   mov r0,#1
   bx lr
over:
   push {lr}
   push {r0}
   sub r0,#1
   bl accumulate
   pop {r1}
   add r0,r0,r1
   pop {lr}
   bx lr
</code>```

for grins an instruction set that uses the stack for most things not
registers

```<code>00000000 <_accumulate>:
   0:   1166            mov r5, -(sp)
   2:   1185            mov sp, r5
   4:   10a6            mov r2, -(sp)
   6:   1d42 0004       mov 4(r5), r2
   a:   0206            bne 18 <_accumulate+0x18>
   c:   15c0 0001       mov $1, r0
  10:   1d42 fffc       mov -4(r5), r2
  14:   1585            mov (sp)+, r5
  16:   0087            rts pc
  18:   1080            mov r2, r0
  1a:   0ac0            dec r0
  1c:   1026            mov r0, -(sp)
  1e:   09f7 ffde       jsr pc, 0 <_accumulate>
  22:   6080            add r2, r0
  24:   65c6 0002       add $2, sp
  28:   1d42 fffc       mov -4(r5), r2
  2c:   1585            mov (sp)+, r5
  2e:   0087            rts pc

it does a stack frame thing
gets the n parameter from the stack
saves that n parameter to the stack
compares and branches if not zero
in the if zero case we set the return value to 1
clean up the stack and return
now in the if not zero case
make the first parameter n-1
call a function (ourself)
do the addition and return
</code>```

Body:
I can't seem to wrap my head around recursion in Assembly Language. I understand how it works in higher level languages, but I don't understand how it is possible in assembly when the return value cannot be passed directly to the function.

I'm trying to make a recursive factorial function in AVR, but I don't understand how the stack passes the value when factorial requires n * (n-1), requiring both n and n-1 simultaneously

Body:
Using addition instead of multiplication

unsigned int accumulate(unsigned int n)
{
    if(n) return(n+accumulate(n-1));
    return(1);
}

and a different instruction set, perhaps easier to follow

00000000 <accumulate>:
   0:   e3500000    cmp r0, #0
   4:   0a000005    beq 20 <accumulate+0x20>
   8:   e3a03000    mov r3, #0
   c:   e0833000    add r3, r3, r0
  10:   e2500001    subs    r0, r0, #1
  14:   1afffffc    bne c <accumulate+0xc>
  18:   e2830001    add r0, r3, #1
  1c:   e12fff1e    bx  lr
  20:   e3a00001    mov r0, #1
  24:   e12fff1e    bx  lr

In this case the compiler didnt actually call the function, it detected what was going on and just made a loop.

Since there is nothing magic about recursion there is no difference in whether you call the same function or some other function.

unsigned int otherfun ( unsigned int );
unsigned int accumulate(unsigned int n)
{
    if(n) return(n+otherfun(n-1));
    return(1);
}

00000000 <accumulate>:
   0:   e92d4010    push    {r4, lr}
   4:   e2504000    subs    r4, r0, #0
   8:   03a00001    moveq   r0, #1
   c:   0a000002    beq 1c <accumulate+0x1c>
  10:   e2440001    sub r0, r4, #1
  14:   ebfffffe    bl  0 <otherfun>
  18:   e0800004    add r0, r0, r4
  1c:   e8bd4010    pop {r4, lr}
  20:   e12fff1e    bx  lr

so this shows how it works.  Instead of using the stack to store the sum, the cheaper solution if you have the registers is to use a non-volatile register save that register to the stack then use that register during the funciton, depends on how many registers you have and how many local intermediate values you need to track.  So r4 gets a copy of n coming in, then that is added (for factorial it is a multiply which depending on the instruction set and code can produce a lot more code that can confuse the understanding so I used addition instead) to the return value from the call to the next function (with recursion where the compiler didnt figure out what we were doing this would have been a call to ourselves, and we can write this asm and make it a call to ourselves to see how it works)

Then the function returns the sum.

If we assume that otherfun is really accumulate we enter this function with a 4 lets say

00000000 <accumulate>:
   0:   e92d4010    push    {r4, lr}
   4:   e2504000    subs    r4, r0, #0
   8:   03a00001    moveq   r0, #1
   c:   0a000002    beq 1c <accumulate+0x1c>
  10:   e2440001    sub r0, r4, #1
  14:   ebxxxxxx    bl  accumulate
  18:   e0800004    add r0, r0, r4
  1c:   e8bd4010    pop {r4, lr}
  20:   e12fff1e    bx  lr

r4 and lr are saved on the stack (call this r4-4 and lr-4)
r4 = n (4)
r0 = n-1 (3)
call accumulate with n-1 (3)
r4 (4) and lr are saved on the stack (r4-3, lr-3) lr now points back into
r4 = n (3)
r0 = n-1 (2)
call accumulate with n-1 (2)
r4 (3) and lr are saved on the stack (r4-2, lr-2)
r4 = n (2)
r0 = n-1 (1)
call accumulate with n-1 (1)
r4 (2) and lr are saved on the stack (r4-1, lr-1)
r0 = n-1 (0)
call accumulate with n-1 (0)
now things change...
r0 = 1
return to lr-1 which is into accumulate after the call to accumulate
r4 gets 2 from the stack
r0 (1) = r0 (1) + r4 (2) = 3
return to lr-2 which is into accumulate r4 gets 3 from the stack
r0 (3) = r0 (3) + r4 (3) = 6
return to lr-3 which is into accumulate r4 gets 4 from the stack
r0 (6) = r0 (6) + r4 (4) = 10
return to lr-4 which is the function that called accumulate r4 is restored
to what it was before accumulate was first called, r4 is non-volatile you have to for this instruction set return r4 the way you found it (as well
as others, but we didnt modify those)

so the addition in this case multiplication in your desired case is

result = 1 + 2 + 3 + 4

How that happened is we basically pushed n on the stack then called the function with n-1.  In this case we push 4, 3, 2, 1 then we start to unwind that and each return processes 1 then 2 then 3 then 4 as it returns
taking those from the stack essentially.

the bottom line is you dont have to care about recursion to support recursion simply use an abi that supports recursion, which is not hard to
do, then hand code the instructions in assembly as if you were the compiler

Maybe this makes it easier to see.  n coming in is both a parameter coming in but also for the duration of the function it is a local variable, local
variables go on the stack.

unsigned int accumulate(unsigned int n)
{
    unsigned int m;
    m = n;
    if(n) return(m+accumulate(n-1));
    return(1);
}

back to this

unsigned int accumulate(unsigned int n)
{
    if(n) return(n+accumulate(n-1));
    return(1);
}

so independent of the instruction set

accumulate:
  if(n!=0) jump over
  return_reg = 1
  return
  over:
  push n on the stack
  first parameter (stack or register) = n - 1
  call accumulate
  pop or load n from the stack
  return_reg = return_reg + n
  clean stack
  return

And also deal with return addresses for the instruction set if required.
The ABI may use the stack to pass parameters or registers.

If I didnt follow the arm abi I could implement

accumulate:
   cmp r0,#0
   bne over
   mov r0,#1
   bx lr
over:
   push {lr}
   push {r0}
   sub r0,#1
   bl accumulate
   pop {r1}
   add r0,r0,r1
   pop {lr}
   bx lr

for grins an instruction set that uses the stack for most things not
registers

00000000 <_accumulate>:
   0:   1166            mov r5, -(sp)
   2:   1185            mov sp, r5
   4:   10a6            mov r2, -(sp)
   6:   1d42 0004       mov 4(r5), r2
   a:   0206            bne 18 <_accumulate+0x18>
   c:   15c0 0001       mov $1, r0
  10:   1d42 fffc       mov -4(r5), r2
  14:   1585            mov (sp)+, r5
  16:   0087            rts pc
  18:   1080            mov r2, r0
  1a:   0ac0            dec r0
  1c:   1026            mov r0, -(sp)
  1e:   09f7 ffde       jsr pc, 0 <_accumulate>
  22:   6080            add r2, r0
  24:   65c6 0002       add $2, sp
  28:   1d42 fffc       mov -4(r5), r2
  2c:   1585            mov (sp)+, r5
  2e:   0087            rts pc

it does a stack frame thing
gets the n parameter from the stack
saves that n parameter to the stack
compares and branches if not zero
in the if zero case we set the return value to 1
clean up the stack and return
now in the if not zero case
make the first parameter n-1
call a function (ourself)
do the addition and return


问:
bit stuffing example
I'm going over an example that reads

Bit Stuffing. Suppose the following bit string is received by the data link layer from the network layer: 01110111101111101111110.
  What is the resulting string after bit stuffing? Bold each bit that has been added.

Answer:

```<code>0111011110111110011111010
               ^      ^
</code>```

How is this answer reached? My understanding is that bit stuffing works by inserting a certain sequence of bits (known as a flag value) at the beginning and end of a frame. What I don't get is:

We aren't told the flag value!

We aren't told how big a frame is, so how do we know where to put the flag?

Aditional Information: I think this network is Ethernet.

Aditional Information 2: The bit flag is 01111110

Honestly I think I understand but isn't the answer incomplete because they didn't add the flag 01111110 to the end or beginging? They just took care of when that pattern of bits appeared in the message.

Other example: here they do it too.

答:
Whenever you have to perform bit stuffing , you will always be given the starting and ending marker FLAG bit value
The easiest trick is to remove the last two bits of the flag and note down the new bit series , whenever you get the same series in your data , you have to stuff one bit there .
For eg -
Given data is 011111011110
Here my FLAG is 0111110  So my my new FLAG will be 01111
I will stuff a bit whenever I get (01111) in my data series ,
So , the data after stuffing will be -
01111(0)101111(0)0
Brackets imply stuffing here .</p>

Title: bit stuffing example

Body:
I'm going over an example that reads

Bit Stuffing. Suppose the following bit string is received by the data link layer from the network layer: 01110111101111101111110.
  What is the resulting string after bit stuffing? Bold each bit that has been added.

Answer:

0111011110111110011111010
               ^      ^

How is this answer reached? My understanding is that bit stuffing works by inserting a certain sequence of bits (known as a flag value) at the beginning and end of a frame. What I don't get is:

We aren't told the flag value!

We aren't told how big a frame is, so how do we know where to put the flag?

Aditional Information: I think this network is Ethernet.

Aditional Information 2: The bit flag is 01111110

Honestly I think I understand but isn't the answer incomplete because they didn't add the flag 01111110 to the end or beginging? They just took care of when that pattern of bits appeared in the message.

Other example: here they do it too.


问:
The Meaning of @override in Android Studio
I am completely new to Android Studio and I want to know the purpose of the @Override statement in Android Studio.

答: It's an annotation in Java. It marks that the method is meant to override a method in a superclass.</p>

ContentLicense: CC BY-SA 4.0


问:
Background image as banner and the related text to it query
I am here to know where I'm going wrong with the code, I am new to HTML/CSS and trying to Google but no luck.

Issue :

Unable to place image and text as needed.

Image is not replacing itself with mobile version when I'm using media query.

Break-point is around 819px and below for mobile.

This is my code

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
    color: #3A1F17;
  }
}

@media (max-width: 819px) {
  .banner-container {
    background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
    text-align: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='main-wrapper'>
  <div class="banner-container" style="background: url('https://serving.photos.photobox.com/65771836f3f64d3b55f2ce69b7a8e93c69a822788f766366b80f47332a7b4c69dc47e4ef.jpg')">
    <div class="banner-content">
      <h1>Auto-Delivery</h1>
      <p>NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL <br>PRODUCTS AGAIN.</p>
    </div>
  </div>
</div></code>```

My final design should look like this :

For desktop :

For mobile :

答:
This should help you out, you had a couple of issues with your css. And I am not quite sure if the first image you want for the Desktop is possible with what you provided for the background.

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
background-image: url("https://serving.photos.photobox.com/65771836f3f64d3b55f2ce69b7a8e93c69a822788f766366b80f47332a7b4c69dc47e4ef.jpg") !important;
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
color: #3A1F17;
  }
}

 @media only screen and (max-width: 819px) {
  .banner-container {
background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
text-align: center;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class='main-wrapper'>
  <div class="banner-container">
<div class="banner-content">
  <h1>Auto-Delivery</h1>
  <p>NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL <br>PRODUCTS AGAIN.</p>
</div>
  </div>
</div></code>```

Body:
I am here to know where I'm going wrong with the code, I am new to HTML/CSS and trying to Google but no luck.

Issue :

Unable to place image and text as needed.

Image is not replacing itself with mobile version when I'm using media query.

Break-point is around 819px and below for mobile.

This is my code

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
    color: #3A1F17;
  }
}

@media (max-width: 819px) {
  .banner-container {
    background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
    text-align: center;
  }
}

Auto-Delivery

NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL
PRODUCTS AGAIN.

My final design should look like this :

For desktop :

For mobile :

Body:
This should help you out, you had a couple of issues with your css. And I am not quite sure if the first image you want for the Desktop is possible with what you provided for the background.

.main-wrapper {
  max-width: 1300px;
}

img {
  max-width: 100%;
}

.banner-container {
background-image: url("https://serving.photos.photobox.com/65771836f3f64d3b55f2ce69b7a8e93c69a822788f766366b80f47332a7b4c69dc47e4ef.jpg") !important;
  padding: 150px 0;
  background-repeat: no-repeat !important;
  background-size: cover;
  background-position: center right !important;
  .banner-content {
color: #3A1F17;
  }
}

 @media only screen and (max-width: 819px) {
  .banner-container {
background-image: url("https://serving.photos.photobox.com/00758490381c3770325173d6abe930e9148d8f0582ad2407e9e775d8fe03b471331704e1.jpg") !important;
  }
  .banner-content {
text-align: center;
  }
}

<div class='main-wrapper'>
  <div class="banner-container">
<div class="banner-content">
  <h1>Auto-Delivery</h1>
  <p>NEVER RUN OUT OF YOUR FAVORITE MOROCCANOIL <br>PRODUCTS AGAIN.</p>
</div>
  </div>
</div>


问:
How do I assign a value depending on an outcome of and If-Statement in Prolog?
So I'm given a maze and I am trying to find out the number of open neighbors (adjacent spots that have the character 'g' or '-').

```<code>openNeighbors(Maze,(R,C),Answer):-
openCount(Maze,(R-1,C),Up),
openCount(Maze,(R+1,C),Down),
openCount(Maze,(R,C-1),Left),
openCount(Maze,(R,C+1),Right),

Answer is Up+Down+Left+Right.

openCount(Maze,Space,Count):-
    find2D(Maze,What,Space),
    (   What =:= - ->
            Count is 1
    ;   What =:= g ->
            Count is 1
    ;       Count is 0
    )
</code>```

My thought process is that I could just call the openCount function for up, down, left, and right but how do I format my if statement within the openCount function? I'm not sure how to compare my 'What' variable with 'g' and '-'.

The Java equivalent for what I want to do is:

```<code>if(What.equals('g')||What.equals('-')){
    return 1;
}else{
    return 0;
}
</code>```

答:
aaargh....

Do yourself a favor - right now, banish -> from your mind. It was introduced to make it easy to avoid one line predicates, and for experienced prolog programmers, it's ok (and can avoid grue choice points, fwiw).

=:= is 'numerically equal', as in 5 =:= 3+2

What =:= g

will freak out with 'g is not a function'.  = is 'unify' - which tries to force the sides to be the same thing, and fails if it can't.
 == is 'same', which succeeds if it is sure the sides are the same. Like, do you and I live in the same kind of building? Quite possible, we both probably live in an apartment or a house, but we don't know. It never binds things.

You also might want to do arithmetic.  'is' is the operator for that.

X is 5+ 6*Y

notice that you can't do arithmetic automatically, like in lesser languages -
     calling foo(5 + Y) doesn't work, it passes '+'(5,Y)  to foo. This inconvenience is countered by lots of wonderfulness, notably that foo can decide what to do with it's arguments.  So matrix_math(5*X + Y*Z)  could evaluate matrices. You can make up the language as you go.  8cD this is good.

Somewhere in the class notes is probably the fact that units of code encapsulation are called predicates, not 'functions'.

So, while I assume when you talk about functions, you're meaning predicates, but hopefully the maintainer who wrote 'g is not a function' knows the proper terminology and really meant function here.

Yup - that's because they meant the built in functions, of which there are a few. They go into arithmetic formula.

Height is Radius * sin(Theta)

sin is the sin function.  You can't define your own functions.  If you were on a prolog with no sin function and wanted to define it you'd need to return the value somehow and use a predicate.

sin(Theta, SinTheta) :-
    ... some code ... .

I'm sure at the moment all of this seem arbitrary and slightly crazy.

The parens around the second argument of openCount aren't useful.
and you don't want to pass openCount '+'(C,1)

succ(Prev,Next) is a useful built-in predicate, 'successor of'

succ(Left, C),
succ(C, Right),
succ(Above, R),
succ(R, Below)

I really encourage indenting the body of the rule one level.

Finally, predicate_names_are_like_this_by_convention.
thisTooIsAnAtomSoItsAPredicateNameButDontDoIt.   <-- you are doing this
ThisIsRightOutAndWontCompile.

Body:
So I'm given a maze and I am trying to find out the number of open neighbors (adjacent spots that have the character 'g' or '-').

openNeighbors(Maze,(R,C),Answer):-
openCount(Maze,(R-1,C),Up),
openCount(Maze,(R+1,C),Down),
openCount(Maze,(R,C-1),Left),
openCount(Maze,(R,C+1),Right),

Answer is Up+Down+Left+Right.

openCount(Maze,Space,Count):-
    find2D(Maze,What,Space),
    (   What =:= - ->
            Count is 1
    ;   What =:= g ->
            Count is 1
    ;       Count is 0
    )

My thought process is that I could just call the openCount function for up, down, left, and right but how do I format my if statement within the openCount function? I'm not sure how to compare my 'What' variable with 'g' and '-'.

The Java equivalent for what I want to do is:

if(What.equals('g')||What.equals('-')){
    return 1;
}else{
    return 0;
}


答:
A simple solution is to use a for loop to iterate over the dictionaries and replace the value.

```<code>json_val = {"A":[{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp"},
                 {"Timestamp": "2017-11-14 14:49:54", "File": "D.kmp"},
                 {"Timestamp": "2017-11-14 14:59:54", "File": "D.kmp"}
                ]}
for dic in json_val['A']:
    if dic['File'] != 'E.kmp':
        dic['File'] = 'E.kmp'
print json_val
</code>```

The above snippet replaces the value of the key File in all the dictionaries inside the list if the value is not E.kmp.

You need not do json.loads(json_val) as python can handle json.

Output will be as:

```<code>{'A': [{'Timestamp': '2017-11-14 14:39:54', 'File': 'E.kmp'},
       {'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'},
       {'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'}
      ]}
</code>```

Title: Replacing JSON pattern

Body:
A simple solution is to use a for loop to iterate over the dictionaries and replace the value.

json_val = {"A":[{"Timestamp": "2017-11-14 14:39:54", "File": "E.kmp"},
                 {"Timestamp": "2017-11-14 14:49:54", "File": "D.kmp"},
                 {"Timestamp": "2017-11-14 14:59:54", "File": "D.kmp"}
                ]}
for dic in json_val['A']:
    if dic['File'] != 'E.kmp':
        dic['File'] = 'E.kmp'
print json_val

The above snippet replaces the value of the key File in all the dictionaries inside the list if the value is not E.kmp.

You need not do json.loads(json_val) as python can handle json.

Output will be as:

{'A': [{'Timestamp': '2017-11-14 14:39:54', 'File': 'E.kmp'},
       {'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'},
       {'Timestamp': '2017-11-14 14:49:54', 'File': 'E.kmp'}
      ]}