text:
Q: Problem adding sharepoint group in list item on itemupdated event I have this code below and I am trying to add a sharepoint group to an item in a list in itemUpdated event handler. the problem is that the update never happens. The problem is with this line of code properties.ListItem.RoleAssignments.Add(rAssignment);
When I debug my code that's where the debugger stops and finishes. So it does not reach the update method. So no group has been added to the item's permission list.
When I remove it, (properties.ListItem.RoleAssignments.Add(rAssignment)), the update happens but I have to refresh the page twice to see the update in the title, for example.
Any idea how can I sovle this?
Here is the code that I am using, together with a class that handles the event firing. I removed the class too but nothing happend.
public override void ItemUpdated(SPItemEventProperties properties)
        {

  base.ItemUpdated(properties);
            using (DisableEventFiring scope = new DisableEventFiring())
            {

               SPWeb web = properties.ListItem.Web;

               SPGroup group = web.SiteGroups["HRTR"];
                SPPrincipal principal = (SPPrincipal)group;
                SPRoleAssignment rAssignment = new SPRoleAssignment(principal);

               properties.ListItem.BreakRoleInheritance(true);
                properties.ListItem.Web.AllowUnsafeUpdates = true;
                properties.ListItem["Title"] = "A cool new title!" + DateTime.Now;
                properties.ListItem.RoleAssignments.Add(rAssignment);

               properties.ListItem.Update();
                properties.ListItem.Web.AllowUnsafeUpdates = false;

           }

}

-----------

    class DisableEventFiring : SPItemEventReceiver, IDisposable
    {
         // Boolean to hold the original value of the EventFiringEnabled property
         bool  _originalValue;
         public DisableEventFiring()
        {
            // Save off the original value of EventFiringEnabled
            _originalValue = base.EventFiringEnabled;
            // Set EventFiringEnabled to false to disable it
            base .EventFiringEnabled = false ;
        }
        public  void  Dispose()
        {
            // Set EventFiringEnabled back to its original value
            base.EventFiringEnabled = _originalValue;
        }
     }

A: You have not added any role definition for the role assignment. Below is a sample code
    base.EventFiringEnabled = false;

SPSecurity.RunWithElevatedPrivilages(() =>
{
using(SPSite site = new SPSite(properties.Web.Url))
{
   using(SPWeb web = site.OpenWeb())
   {
      SPList list = web.Lists[properties.List.Title]
      SPListItem item = list.GetItemById(properties.ListItemId);

      if(!item.HasUniqueRoleAssignments)
      {
          item.BreakRoleInheritance(true);
      }

      SPGroup group = web.SiteGroups["TestGroup"];
      SPRoleAssignment role = new SPRoleAssignment(group);
      SPRoleDefinition definition = item.ParentWeb.RoleDefinitions["Contribute"];
      role.RoleDefinitionBindings.Add(definition);

      item.RoleAssignments.Add(role);
      item.Update()
   }
 }
});

base.EventFiringEnabled = true;

A: Could give you some suggestion.
1) Try out if you get some exception using try catch in the line
properties.ListItem.RoleAssignments.Add(rAssignment);

2) Instead of using ListItem.Update(); try to use ListItem.SystemUpdate(false);
3) In the EventReceiver use the following method to update
Comment these lines available in the EventReceiver

       base.ItemUpdated(properties);
       base.ItemUpdating(properties);
       base.EventFiringEnabled = false;

for updating use the following method

        base.EventFiringEnabled = false;
        try
        {
            ListItem.SystemUpdate(false);
        }
        finally
        {
            base.EventFiringEnabled = true;
        }

A: Unless all of the users of the list have the ability to modify permissions, you will need to use SPSecurity.RunWithElevatedPrivileges or some other method to get higher permissions. Inside that method, you need to re-load the site/web/ListItem for the higher permissions to take effect.
Also - I doubt it's causing a problem, but making a DisableEventFiring class is more something you do to get that functionality somewhere other than an event receiver. Inside an event receiver you can just call the properties directly.


text:
Q: Query parent og child record and return parent record I'm working on a product database (PDB) to be used both for a webshop and as articles in our ERP-system. Most of the data comes directly from our suppliers as CSV-files, and we've added options to override certain fields, which has resulted in a table structure I can't figure out how to efficiently query.
In essence the table structure consists of two tables, article and extended_article, where the last table contains a field called parent_article_code used to combine women articles into men for display purposes. Not all articles contain extended_articles and not all articles with extended_articles has a value in parent_article_code.
I need to perform a query returning all articles with a match, but only show the parent article where either the parent or child matches the query. This is a really simplefied version of the tables and I'll also add a query to show how the data is actually structured.
article table:
    -------------------------------------------------------------------------
    |  id  |  code    |  name          |  description                       |
    |  1   |  029320  |  T-shirt       |  Nice t-shirt with awsome logo     |
    |  2   |  029321  |  T-shirt Lady  |  Nice t-shirt with awsome logo     |
    |  3   |  029322  |  Sweatshirt    |  Nice sweatshirt with awsome logo  |
    |  4   |  029323  |  Pants         |  Nice pants with awsome logo       |
    -------------------------------------------------------------------------

extended_article table:
    -------------------------------------------------------------------------------------------------
    |  id  |  article_code  |  parent_article_code  |  name_override       |  description_override  |
    |  1   |  029320        |                       |  T-shirt with print  |                        |
    |  2   |  029321        |  029320               |                      |                        |
    |  3   |  029323        |                       |  Awsome pants!       |                        |
    -------------------------------------------------------------------------------------------------

Example SQL query (returning all records with match - not only children):
SELECT article.*,
    article.id,
    extended_article.parent_article_code,
    extended_article.impressions,
    extended_article.is_base_assortment,
    extended_article.is_visible,
    extended_article.name_override,
    extended_article.description_override,
    extended_article.additional_description,
    extended_article.preferred_image_file_name,
    supplier.name AS supplier_name,
    brand.name AS brand_name
FROM article
LEFT OUTER JOIN article_sort_order
ON article_sort_order.article_code = article.code AND category_id IS NULL
LEFT OUTER JOIN extended_article
ON extended_article.article_code = article.code
LEFT JOIN supplier
ON supplier.id = article.supplier_id
LEFT JOIN brand
ON brand.id = article.brand_id
WHERE (extended_article.is_base_assortment = 1)
AND  (article.is_expired = 0)
AND (extended_article.is_visible = 1)
AND ((EXISTS
(
    SELECT 1
    FROM article_color_groups
    WHERE article_color_groups.article_code = article.code
    AND article_color_groups.color_group_id = 4
)
))

So my question is this:
How can I efficently query this table structure and have a result set that only contains the parent articles?
EDIT:
I had an idea to move the query part into two subqueries selecting only IDs and using UNION to generate a list to select the appropriate fields from. This seems to work, but might not be the most efficient solution?
SELECT article.*, article.id, extended_article.parent_article_code, extended_article.impressions, extended_article.is_base_assortment, extended_article.is_visible, extended_article.name_override, extended_article.description_override, extended_article.additional_description, extended_article.preferred_image_file_name, supplier.name AS supplier_name, brand.name AS brand_name
FROM article
LEFT OUTER JOIN article_sort_order ON article_sort_order.article_code = article.code AND category_id IS NULL
LEFT OUTER JOIN extended_article ON extended_article.article_code = article.code
LEFT JOIN supplier ON supplier.id = article.supplier_id
LEFT JOIN brand ON brand.id = article.brand_id
WHERE article.code IN (
                SELECT article.code
                FROM article
                LEFT OUTER JOIN article_sort_order ON article_sort_order.article_code = article.code AND category_id IS NULL
                LEFT OUTER JOIN extended_article ON extended_article.article_code = article.code
                LEFT JOIN supplier ON supplier.id = article.supplier_id
                LEFT JOIN brand ON brand.id = article.brand_id
                WHERE   (NULLIF(extended_article.parent_article_code, '') IS NULL)
                        AND
                        (extended_article.is_base_assortment = 1)
                        AND
                        (article.is_expired = 0)
                        AND
                        (extended_article.is_visible = 1)
                        AND
                        ((EXISTS (SELECT 1 FROM article_color_groups WHERE article_color_groups.article_code = article.code AND article_color_groups.color_group_id = 11)))

                UNION

                SELECT extended_article.parent_article_code
                FROM article
                LEFT OUTER JOIN article_sort_order ON article_sort_order.article_code = article.code AND category_id IS NULL
                LEFT OUTER JOIN extended_article ON extended_article.article_code = article.code
                LEFT JOIN supplier ON supplier.id = article.supplier_id
                LEFT JOIN brand ON brand.id = article.brand_id
                WHERE   (NULLIF(extended_article.parent_article_code, '') IS NOT NULL)
                        AND
                        (article.is_expired = 0)
                        AND
                        ((EXISTS (SELECT 1 FROM article_color_groups WHERE article_color_groups.article_code = article.code AND article_color_groups.color_group_id = 11)))
            )
ORDER BY -article_sort_order.sort_order DESC;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a need for an IoC container in TDD unit tests? While I do see the benefits of IoC containers (as I've used them a fair bit), I don't see how they can be incorporated within TDD unit tests (note, I'm only interested in unit tests here, not integration tests).
When I TDD, I refactor constructors to use IoC, so that I can inject fake dependencies wherever I might need to. Implementing a container implies that I'd be deviating from the red-green-refactor-repeat loop and adding code that wouldn't be covered by my tests.
Now let's say that you somehow (with great design prowess) managed to hook in a container in your TDD life-cyle. You certainly aren't meant to create instances in your unit test by resolving dependencies, as strictly speaking, that turns it into an integration test (bringing in multiple production components).
So my questions are:
1) In what scenario might you need a container while unit testing within TDD?
2) Assuming a valid scenario for (1) exists, how would you go about incorporating a container without breaking away from red-green-refactor-repeat?
I should clarify that by 'need', I'm talking about a stage you'd get to where manually managing DI gets tedious because you have a massive object graph.
IMPORTANT: I'm not asking about containers for your test. I'm asking strictly about production containers. I have a feeling that an IoC container cannot be implemented in a TDD life-cyle without breaking away from red-green-refactor-repeat (rgrr) and managing the container would have to be done in a sort of parallel way, if that makes sense.

A: I can do without IoC containers, TDD or not.
I can work with IoC containers, TDD or not.
I can make a grand mess of things with IoC containers, TDD or not.
IoC containers come in a great many flavors and are sold a great many ways. After mastering them and mastering doing without them I've only identified one thing they do that is hard to do on your own. They move construction into a different language.
Rather then just construct your graph of persistent objects in main they have you compose the object graph in some different language like xml or json. This drives home the idea of separating construction code from behavior code. This is a good thing but if you're disciplined enough to do that without training wheels the IoC container isn't getting you much.
But, if you are going to use IoC containers, for whatever reason. then first be sure you're not spreading it all over the place. A IoC container that shows up once in main is no more an anti pattern then an abstract factory. If every darn object knows about it directly, well you've created a Service Locator. No really, I don't care how popular your IoC container is or how much you paid for it, if you use it that way then you're making a mess. Keep it in one tidy little place where nothing else knows about it and what you have is a factory that pops out object graphs as defined in that screwy xml. This is not the anti pattern. This is fine.
If you want to use TDD while using a IoC container used this way you're fine because the object you're testing doesn't even know the IoC container exists.
Maybe you have some obsessive need to test whatever the IoC container exists in. If you're doing it right then that shouldn't be very many things. But fine. If you must test this too then remember that the IoC container is itself a dependency that can be injected and stubbed. My gut says if you need to test this then you're doing something weird but even if you are then you can still do TDD with a container. Unless you're not just doing something weird but something very wrong.
Remember, when you test something it's your job to give it what it needs in a reliable way so that if other stuff breaks, the test still passes. This test should only fail when the unit under test fails.  Bear in mind that a "unit" might be one object or an entire object graph. Stay true to whatever boundary you set for your test. Make the boundary clear so when the test fails people know where to look.
If that boundary must include some dopy little IoC container then so be it. If it doesn't, but you are stuck depending on it, at least give the test its own independent container.
But that's just a pain in the ass. I much prefer it when most of my objects don't even know a IoC container exists. When they'd don't I can test them without one just fine. What they don't know can't hurt them.

I should clarify that by 'need', I'm talking about a stage you'd get to where manually managing DI gets tedious because you have a massive object graph.

A massive object graph will be tedious to deal with manual or not. If your unit under test really cares about the whole graph and you just don't feel happy making the whole graph by hand without the IoC container then fine. Use one to build what the test needs. But the test gets its own independent instance of the IoC and it's config info (unless that right there is what you're testing). That isolates the test and makes it independant.

IMPORTANT: I'm not asking about containers for your test. I'm asking strictly about production containers. I have a feeling that an IoC container cannot be implemented in a TDD life-cyle without breaking away from red-green-refactor-repeat (rgrr) and managing the container would have to be done in a sort of parallel way, if that makes sense.

If A depends on B and T want's to test A then T needs some Bish thing to build A with. T could get the Bish thing from a IoC container C or it could just make the Bish thing on it's own. Either way the red green refactor cycle is fine.
Neither A nor B even know about C so T can use whatever C thing it likes or no C thing at all to get it's A and B. If you can't say things like this you aren't doing the Inversion of Control part of your IoC container right at all.
The classic red green refactor cycle:
You write T before you write A. You're red.
You write A and feed it some Bish thing (that should already be under some other test) using a C made just for this T. You're green.
you refactor and A changes. T is still green.
Refactoring Against The Red Bar gives us formal steps for refactoring a working test:
You want to refactor T because you decide you don't need C or want a different C. So you change T. Now it's green but untrusted because we've only seen it pass. We've never seen it fail. We've never tested the test. We messed up. Let's go back to the end of the classic red green refactor cycle above where we have A under test T which has been seen to both pass and fail. What we should have done, to refactor how T uses C, was this:

*

*Run the test T

*Note the green bar

*Break the code in A

*Run the test T

*Note the red bar

*Refactor T to change how it uses C

*Run the test T

*Note the red bar

*Un-break the code in A

*Run the test T

*Note the green bar

That's refactoring against the red bar. It lets you refactor tests just as formally as you refactor code under test. I first talked about it here. Using that you should be able to force your IoC container to dance to the tune of TDD just fine.

A: @CandiedOrange answered the Question as to why it's a good idea to use explicit registration and comments provide more detail. I won't repeat that, since I wholeheartedly agree.
If you follow this advice, and do explicit registration in code, testing it is trivial. Even in TDD fashion (which I like a lot), very simple tests and equally simple implementation.
Thus my answer is:

*

*Not necessarily. I do not think testing this is very useful in a UnitTest, I think of it as an orthogonal issue. More like a config file. Some integration tests might be useful.

*If you think it helps to have unit tests for this, going about it seams simple, if you configure it with code in your main function (as suggested by CandiedOrange). In this case, it's simply refactoring. Replacing manual wiring up with registration and startup code, while keeping your tests green.

A: The IoC container becomes useful when part of your software has to instantiate various classes based on runtime information.
For example MVC web controllers must be instantiated when a request comes in which matches the route for the controller.
So your first red test which pushes you down the container road is : 'When a request has path X, Controller Y is created with all its required services'
You might start off writing a hard coded controller factory to make the test pass, but as you develop more and more controllers with different requirements at some stage you will want to refactor into a more generic factory which will resemble a container.
Given that you know such things as containers and generic factories exist prior to starting your code. It's not unreasonable to skip those steps and jump straight into IoC containers.
Proponents of TDD would argue that its very design pushes you towards 'good' code with these advanced structures.
I have a feeling though, that if you are very strict about writing the least amount possible to make a test pass, the heat death of the universe might occur before things like object orientated code and IoC containers 'evolve' from TDD.
Just assume they will eventually and skip those steps.

A:

*

*In what scenario might you need a container while unit testing within TDD?

I don't see how IoC containers factor into this. Even if you were taking a pure DI approach where you write explicit methods to instantiate your components (which in turn chains to all of that component's dependencies' methods), your question would remain the same: how do you test those pure DI methods?
Whether you use a container or a set of prebuilt Pure DI methods that instantiate your objects for you, it serves the same purpose, and you would write the same test for it.
However, as I'll elaborate in this answer, I don't quite agree that you need to write tests for either of them.

note, I'm only interested in unit tests here, not integration tests

This sort of undoes your argument, or at least shifts the goal posts a bit. Unit tests don't care about a chained stack of dependencies, specifically because they are unit tests.
Any issues in wiring the IoC container will be spotted by your integration tests, since those tests are built specifically to test how your individual components are wired together.
To put it another way, a bad IoC registration doesn't in fact invalidate the units that you test themselves, and therefore their unit tests shouldn't fail.

Implementing a container implies that I'd be deviating from the red-green-refactor-repeat loop and adding code that wouldn't be covered by my tests.

There's two approaches here. The pedantically correct one, and the reasonably practical one.
The reasonably practical approach
Most devs I've worked with, including myself, tend to consider the configuration of the DI container to be startup logic, which falls outside of the application logic scope, which is what your tests cover.
Startup logic tends to be trivial, and is the runtime equivalent of linking projects at compile time. It's not the target for unit tests, because it's "meta logic", in the sense that it doesn't contain business logic but rather the setup logic for the framework in which you will be housing your meta logic.
My reasoning for not testing this is that these tests wouldn't exist to test a behavior, but they are just a "write it again" exercise to confirm that the expected object graph is the same in both your production code and your test.
I find it a waste of time for the same reason that I hate "confirm your email address again" textboxes, and I always end up copy/pasting the email address from the first box into the second one, which defeats the purpose entirely.
Another counterargument here, though slightly outdated nowadays, is that some older IoC setups used config files to configure their container, and you can make a reasonable case here for not needing to unit test values from a config file.
The pedantically correct appraoch
But if you choose to read 100% coverage as 100% coverage of everything, nothing is stopping you from writing tests that confirm the IoC container has been hooked up correctly - at least to the point of not throwing exceptions about missing dependency registrations (the specific behaviors are better tested using more concrete integration tests).
In essence, you could consider the wiring up logic as a unit in and of itself, and thus write tests for it to confirm that it correctly wired your object graph.

You certainly aren't meant to create instances in your unit test by resolving dependencies, as strictly speaking, that turns it into an integration test

If I create a container, register one real dependency (i.e. the one I'm unit testing), and then register a bunch of mocks, then I'm not turning my unit test into an integration test.
There's little purpose to using such a custom built container for the purpose of a unit test (though I can't guarantee that it's never useful), but it doesn't inherently turn your unit test into an integration test.


text:
Q: How do you get a *.desktop file to work for a non-repository app? I turned the Amazon cloud reader site https://read.amazon.com into a desktop app with nativefier. It works amazingly well as a standalone reader for books that have been downloaded and also automatically downloads books in the cloud when requested.
Instead of launching /home/myname/kindle-web-linux-x64/kindle-web from the console all the time, I tried to make a Kindle-Web desktop file to place in the launcher. My file won't work in two ways:

*

*It won't launch Kindle-Web.

*It does not display the Kindle icon on the file when viewed in Nautilus.

The code is below. Can anyone tell me where I went wrong. The icon files are in /home/myname/.local/share/icons/hicolor/<resolution-folders>, and /home/myname/.icons/hicolor/*.

[Desktop Entry]
Version=1.0
Name=Kindle-Web
Comment=Desktop app created from Kindle Cloud Reader page (https://read.amazon.com) by nativefier
Exec=/home/myname/kindle-web-linux-x64/kindle-web
Path=/home/myname/
# StartupNotify=true
# StartupWMClass=kindle-web
Icon=0914_Kindle.0
# Terminal=false
Type=Application
Categories=Publishing;Literature;Documentation;Office;

A: If running
/home/myname/kindle-web-linux-x64/kindle-web

in Terminal indeed launches the application whereas the .desktop launcher doesn't, then change the Exec line from
Exec=/home/myname/kindle-web-linux-x64/kindle-web

to
Exec=bash -c '/home/myname/kindle-web-linux-x64/kindle-web'

A: Google Chrome actually has a feature to make a shortcut on desktop, which on Linux will effectively create a .desktop shortcut.
Steps to create:

*

*Open https://read.amazon.com in Google Chrome

*Click on the Chrome's top right menu

*Navigate to More tools →  Create a shortcut
At this point you should have the .desktop file in your home directory, which should launch a single chrome window. You can customize the resulting file if you like.

A: I will answer about my experience.

*

*First I recommend, not using "." on icon names. I am not sure why, but I had in past the same problem with a desktop file with an icon called with org.xxx.xxx style, and icon never shown in "Application Menu".

*I recommend that your icon have at least 128x128 version.

*Call the update-icon-caches
update-icon-caches ~/.local/share/icons

*Copy your desktop file to ~/.local/share/applications and run the update-desktop-database

update-desktop-database ~/.local/share/applications

So now, you should see the app in "Applications Menu" with correct icon displayed


text:
Q: Magento 2: Maintenance Mode I've configured Magento 2 website as maintenance mode from .maintenance.flag it's working, at the same time I have configured released IPs from .maintenance.ip file.
For multiple IPs not working while for single IP it's working fine.
How can I configure to release selected multiple IPs?
For this I have written I have created.
1) .maintenance.flag file from var.
2) .maintenance.ip file from var and written code for release single IP
192.168.0.52

For single I have written above it's working.
192.168.0.52,192.168.0.53

For multiple, I have written above it's not working.
Can you please let me know how can I write to release multiple IP's and also how can I configure to redirect particular page while maintenance Mode?

A: For activating maintenance mode with IP addresses execute below command in CLI
php bin/magento maintenance:enable --ip="192.168.0.52" --ip="192.168.0.86"

the above command will automatically create a .maintenance.flag and .maintenance.ip file under root/var folder.
and .maintenance.ip the file contains the above two IP addresses separated by a comma.
For more Information, you can find from devdocs.
The above information is for maintenance mode.
To redirect a custom page while maintenance mode writes below code in root/index.php.
$maintenanceFile =  __DIR__ . '/var/.maintenance.flag';

if (file_exists($maintenanceFile)) {
    header('Location: http://127.0.0.1/m2ee/Error.php');
    die();
}

If anyone has better approach please update this answer.

A: The Maintenance Mode check-in lib/internal/Magento/Framework/App/Bootstrap.php.
This file calls to lib/internal/Magento/Framework/App/MaintenanceMode.php. If .maintenance.flag file exists in var folder, it returns false.
If you want the redirect to a new page when maintenance enables, you need change lib/internal/Magento/Framework/App/Bootstrap.php file. Add this code below after line 288:
header('Location: http://127.0.0.1'); //your page
die();

A: If you want to design your maintenance page you need to edit file pub/errors/default/503.phtml and for css pub/errors/default/css/styles.css design accordingly.
And in .htaccess page need to comment ##  SetEnv MAGE_MODE developer or production for execute this maintenance page.
and if you are in production mode then this page will excute other then below code error will show.
Unable to proceed: the maintenance mode is enabled.
#0 /backup/html/magento2/vendor/magento/framework/App/Bootstrap.php(256): Magento\Framework\App\Bootstrap->assertMaintenance()
#1 /backup/html/magento2/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#2 {main}

if you want to come back in your website you need to delete var/.maintenance file or run below command in terminal
//For run your website back online.
php bin/magento maintenance:disable
//For on maintenance mode.
php bin/magento maintenance:enable

Also set in .htaccess
SetEnv MAGE_MODE developer
follow up my youtube and block
https://www.youtube.com/channel/UChb7DM9SspzrUVh4hnWL50A
https://php-scripts-form.blogspot.com/


text:
Q: phpthumb() library unable to create external images thumbnail I am trying to generate thumbnail on the fly using phpThumb() library.
It is working fine for those images store in my server. But it is not generating thumbnail
for external images.
Reference :- http://phpthumb.sourceforge.net/demo/demo/phpThumb.demo.demo.php
Working :-

Not working:-

Can anyone guide me if I doing anything wrong here. Or any other php thumbnail library can help me??
Thanks in advance.


text:
Q: How to remove the square brackets in output of the list? items=['a', 'b', 'c', 'd', 'e']
print("The first 3 items in the list are: ")
for item in items[:3]:
    print(item)

#or
print("The first 3 items in the list are: " + str(items[:3]))

Q: How should I make the output of the 'first 3 items' to be horizontal(like the second code) but without the square brackets(like the 1st code)?

A: You can use str.join(iterable), where str is the separator between the items in the iterable. For example:
items = ['a', 'b', 'c', 'd', 'e']
print('The first 3 items in the list are: ' + ', '.join(items[:3]))

This prints:
The first 3 items in the list are: a, b, c

In this case, ', ' is the separator between the items of the list. You can change it according to your needs. For example, using ' '.join(items[:3]) instead would result in:
The first 3 items in the list are: a b c

A: There are several ways. The appropriate here (IMO) is to use
print("items are: " + ', '.join(items[:3]))

Which (depending on your python version) can be simplified to:
print(f'items are: {", ".join(items[:3])}')

or without the comma
Another way is to tell the print to not print linebreaks:
for item in items[:3]:
    print(item, end='')

A: You can write print(item, end=" ") in your loop.

A: This would do it:
print("The first 3 items in the list are: " + str(items[:3])[1:-1])

assuming you don't mind the items separated by commas.


text:
Q: Convert a list of values to a list of intervals in Python I have a list of objects, each containing a flag (boolean) and a value (integer). The value is increasing for each list item. I want to convert the list into a new list with only the first and last value property (the interval) for every time the flag property alternates.
In other words, I want to convert this
[
    {'flag': True, 'value': 0},
    {'flag': True, 'value': 5},
    {'flag': True, 'value': 10},
    {'flag': False, 'value': 15},
    {'flag': False, 'value': 20},
    {'flag': False, 'value': 25},
    {'flag': False, 'value': 30},
    {'flag': False, 'value': 35},
    {'flag': False, 'value': 40},
    {'flag': True, 'value': 45},
    {'flag': True, 'value': 50},
    {'flag': True, 'value': 55},
    {'flag': True, 'value': 60},
    {'flag': False, 'value': 65},
    {'flag': False, 'value': 70},
    {'flag': False, 'value': 75},
    {'flag': False, 'value': 80},
    {'flag': False, 'value': 85},
    {'flag': True, 'value': 90},
    {'flag': True, 'value': 95}
]

into this (or something similar):
[
    {'flag': True, 'values': (0, 10)},
    {'flag': False, 'values': (15, 40)},
    {'flag': True, 'values': (45, 60)},
    {'flag': False, 'values': (65, 85)},
    {'flag': True, 'values': (90, 95)},
]

What is a simple and elegant way of solving this in Python?
I hope the example data isn't too confusing. I've tried solving this both using a for-loop and using reduce, but neither solution seems right.
Thanks!

A: You can use itertools.groupby to group the items by flag and then convert the groups to lists and get the values of the first and last elements of those lists. Here, lst is your original list.
>>> [{"flag": key, "values" : (val[0]["value"], val[-1]["value"])}
...  for key, val in ((key, list(val)) for key, val in itertools.groupby(lst, key=lambda d: d["flag"]))]
[{'flag': True, 'values': (0, 10)},
 {'flag': False, 'values': (15, 40)},
 {'flag': True, 'values': (45, 60)},
 {'flag': False, 'values': (65, 85)},
 {'flag': True, 'values': (90, 95)}]

Or similar, using an inner list comprehension to extract the value keys first, as we have to use an inner generator expression to convert the group iterator to list anyway. The result is the same.
>>> [{"flag": key, "values" : (vals[0], vals[-1])}
...  for key, vals in ((key, [g["value"] for g in grp])
...                    for key, grp in itertools.groupby(lst, key=lambda d: d["flag"]))]

But that's still far from being readable, so I'd suggest splitting this up into two lines:
>>> groups = ((key, [g["value"] for g in grp])
...           for key, grp in itertools.groupby(lst, key=lambda d: d["flag"]))
>>> result = [{"flag": key, "values" : (vals[0], vals[-1])} for key, vals in groups]

A: Pandas solution:
j = [
{'flag': True, 'value': 0}, {'flag': True, 'value': 5},
{'flag': True, 'value': 10}, {'flag': False, 'value': 15},
{'flag': False, 'value': 20}, {'flag': False, 'value': 25},
{'flag': False, 'value': 30}, {'flag': False, 'value': 35},
{'flag': False, 'value': 40}, {'flag': True, 'value': 45},
{'flag': True, 'value': 50}, {'flag': True, 'value': 55},
{'flag': True, 'value': 60}, {'flag': False, 'value': 65},
{'flag': False, 'value': 70}, {'flag': False, 'value': 75},
{'flag': False, 'value': 80}, {'flag': False, 'value': 85},
{'flag': True, 'value': 90}, {'flag': True, 'value': 95}]

import pandas as pd

df = pd.DataFrame(j)

df['group'] = df['flag'].ne(df['flag'].shift()).cumsum() # column to groupby
output = df.groupby("group").apply(lambda x: \
                                   {'flag':x["flag"].tolist()[0],
                                    'values':(x["value"].min(),x["value"].max())})

output.tolist()

Outputs:
[{'flag': True, 'values': (0, 10)},
 {'flag': False, 'values': (15, 40)},
 {'flag': True, 'values': (45, 60)},
 {'flag': False, 'values': (65, 85)},
 {'flag': True, 'values': (90, 95)}]

Dataframe looks like:
    flag    value   group
0   True    0   1
1   True    5   1
2   True    10  1
3   False   15  2
4   False   20  2
5   False   25  2
6   False   30  2
7   False   35  2
8   False   40  2
9   True    45  3
...

A: Manual solution:
lista = [
    {'flag': True, 'value': 0}, {'flag': True, 'value': 5}, {'flag': True, 'value': 10},
    {'flag': False, 'value': 15}, {'flag': False, 'value': 20}, {'flag': False, 'value': 25},
    {'flag': False, 'value': 30}, {'flag': False, 'value': 35}, {'flag': False, 'value': 40},
    {'flag': True, 'value': 45}, {'flag': True, 'value': 50}, {'flag': True, 'value': 55},
    {'flag': True, 'value': 60}, {'flag': False, 'value': 65}, {'flag': False, 'value': 70},
    {'flag': False, 'value': 75}, {'flag': False, 'value': 80}, {'flag': False, 'value': 85},
    {'flag': True, 'value': 90}, {'flag': True, 'value': 95}
]
change = False
output = []
p=[0]*2
flagPast = lista[0]['flag']
for index,item in enumerate(lista):
    if(item['flag'] != flagPast):
        cp=p[:]
        output.append(zip(['flag','values'],[flagPast,cp]))
        p[0]=item['value']
        change = True
    else:
        change = False
    if(not(change)):
        p[1]=item['value']
    flagPast = item['flag']
    if(index==(len(lista)-1)):
        p[1]=item['value']
        cp=p[:]
        output.append(zip(['flag','values'],[flagPast,cp]))


text:
Q: Unable to sign in to Google from the GooglePlusSample code using GooglePlusPlatform I am running the GooglePlusPlatform Sample Code provided by Google to learn about its SDk. However, when I run the application and click on the sign-in button it generates an error as:

Error Domain=com.google.GooglePlusPlatform Code=-1 "keychain error"
  UserInfo=0x1100bdd0 {NSLocalizedDescription=keychain error}

Same error also occurs in another application I have created which uses the GooglePlus Sign in. I Googled about it, but could not find anything useful. Please help!

A: Go to TARGETS > Capabilities > and enable "KeyChain Sharing".

A: I actually filed this bug on the Google Services GitHub repo, and got responses from the coders sayings that it´s an Apple Bug and there´s nothing they can do about it.
https://github.com/googlesamples/google-services/issues/82
Good news is, that the problem only happens when Xcode is attached to the phone. It works fine otherwise. So even though it's a pain to test, we shouldn't worry about it being a problem for end users. (fingers crossed)

A: I see this is not happening in simulator. And on real devices, this happens only when exception break point is created. Just remove that break point and try. It should work.


text:
Q: Silverlight mime-type(s) I have stumbled across the following issue:
Using IIS6, I was trying to run sample Silverlight app. However, I experienced some problems with the mime-types. More specifically, I failed miserably when tried to use the application/x-silverlight-2 type for my Object tag. No content was displayed at all. When I changed the type to application/x-silverlight-app everything seemed to work as expected. What is the difference between these two MIME types? As far as I know, application/x-silverlight-2 is supported by all versions of Sliverlight and there should be no problems to use it even with Siverlight 3 app. In contrast, I was no able to find concrete information what does the application/x-silverlight-app type stand for. Anyone has an idea?

A: Maybe you should check if the correct mime-type are configured in IIS6.
You can learn how to configure IIS6 for silverlight here.


text:
Q: CBB inequality and two comparison triangles / 4-point condition for CBB spaces Assume $(X,d)$ is a CBB($\kappa$) space with $\kappa > 0$. (That is we can find comparison triangles in the model space $(M_\kappa^2, \bar{d})$ and the reverse of the CAT inequality holds; Definition 5.1.12 in Lipschitz Functions - Ştefan Cobzaş, Radu Miculescu, Adriana Nicolae).
Now my question is the following. Assume there are $4$ points $x,y, z_1, z_2$ in $X$ and we take comparison triangles $\Delta(\bar{x},\bar{y},\bar{z_1})$ and $\Delta(\bar{x},\bar{y},\bar{z_2})$ in $M^2_\kappa$ such that the distance between $\bar{z_1}$ and $\bar{z_2}$ becomes minimal. Under what conditions does it hold that $d(z_1, z_2) \geq \bar{d}(\bar{z_1}, \bar{z_2})$?


text:
Q: how to apply time windows with different lengths to a pandas dataframe I have the following dataframe, each row represent a sale transaction:
startDate           INDEX_250   priceDeal
2013-05-02 00:00:00 9312.000    255000.000
2013-09-17 00:00:00 11121.000   368209.000
2013-10-09 00:00:00 11121.000   254000.000
2013-11-14 00:00:00 11121.000   520000.000
2013-11-22 00:00:00 11121.000   201000.000
2014-02-05 00:00:00 11121.000   260000.000
2014-02-28 00:00:00 11121.000   425000.000
2014-03-01 00:00:00 11121.000   315000.000
2014-03-11 00:00:00 9312.000    427000.000
2014-04-27 00:00:00 9312.000    138070.000
2014-06-20 00:00:00 9312.000    270000.000
2014-07-21 00:00:00 9312.000    282000.000
2014-07-31 00:00:00 9312.000    308806.350
2014-09-27 00:00:00 11121.000   170000.000
2014-10-05 00:00:00 11121.000   171658.220
2014-10-11 00:00:00 11121.000   292000.000
2014-10-13 00:00:00 11121.000   125000.000
2014-10-30 00:00:00 9312.000    95000.000
2014-11-18 00:00:00 9312.000    158942.280
2015-01-25 22:00:00 11121.000   238829.370
2015-03-11 00:00:00 11121.000   180695.960
2015-03-14 00:00:00 9312.000    320932.860
2015-03-21 00:00:00 11121.000   139872.000
2015-09-04 00:00:00 11121.000   140000.000
2015-09-09 00:00:00 9312.000    235000.000

i want to see how many sales transactions happened in previous 30 day nrTargets_gr_250_30 and 60 day nrTargets_gr_250_60 for each (grouped by) INDEX_250 from the first sale transaction 2013-09-17. example dataset is only for one INDEX_250 but there are other index numbers as well, following out put is desirable:
      startDate  INDEX_250  nrTargets_gr_250_30 nrTargets_gr_250_60
      2013-10-17    11121   2.000               2.000
      2013-11-16    11121   1.000               3.000
      2013-12-16    11121   1.000               2.000
      2014-01-15    11121   0.000               1.000
      2014-02-14    11121   1.000               1.000
      2014-03-16    11121   2.000               3.000
      2014-04-15    11121   0.000               2.000
      2014-10-12    11121   3.000               3.000
      2014-11-11    11121   1.000               4.000
      2014-12-11    11121   0.000               1.000
      2015-02-09    11121   1.000               1.000
      2015-03-11    11121   0.000               1.000
      2015-04-10    11121   2.000               2.000
      2015-05-10    11121   0.000               2.000
      2015-09-07    11121   1.000               1.000
      2015-10-07    11121   0.000               1.000
      2016-02-04    11121   1.000               1.000
      2016-03-05    11121   0.000               1.000
      2017-01-29    11121   1.000               1.000

A: I noticed that you want startDate changed to the end of the respective
30-days period, starting from your start date.
Another detail is that you want the result grouped by INDEX_250 -
how many previous transactions (in both respective periods) were with
the same value of INDEX_250.
Note also that rolling calculations can be performed on a window
containing rows from a number of future periods, whereas you want
the number of transactions from previous 30 or 60 days and
rolling does not allow negative number of periods.
This is why I took a different approach than "ordinary" rolling.
Start from auxiliary variables:
td30 = pd.Timedelta('30D')
dRng = pd.date_range(start='2013-09-17', end=df.startDate.max() + td30,
    freq='30D', closed='left')

Then define the following function computing both targets:
def targets(grp):
    grp['Prd'] = grp.startDate.apply(lambda x: dRng.asof(x) + td30)
    grp.set_index('Prd', inplace=True)
    trg30 = grp.groupby(level=0).INDEX_250.count()\
        .rename('nrTargets_gr_250_30').reindex(dRng, fill_value=0)
    trg60 = trg30.rolling(2).sum().rename('nrTargets_gr_250_60')\
        .fillna(0, downcast='infer')
    trg30 = trg30[trg30 > 0]
    trg60 = trg60[trg60 > 0]
    return trg30.to_frame().join(trg60, how='outer')\
        .fillna(0, downcast='infer').rename_axis('startDate')

Apply it and reset indices (just in this order, to have proper ordering of columns):
df2 = df[df.startDate >= '2013-09-17'].groupby('INDEX_250')\
    .apply(targets).reset_index(level=[0]).reset_index()

Notes:

*

*I took only rows with startDate on or after the start date you
specified (2013-09-17).

*The type of both target columns is int. I think it is more natural,
as these column contain the number of transactions, which by nature
is just an integer.

And the last thing is to change the type of INDEX_250 to int:
df2.INDEX_250 = df2.INDEX_250.astype(int)

The result for INDEX_250 group is just as you specified, excluding
result rows from 2016 and 2017, which were not included in your
sample data.
Extended version - with average prices
To extend the result by average prices for each "final" date
and both targets, two changes are required.
First, define another function to "reformat" target DataFrame:
def trgReformat(trg):
    trg = trg[trg.nrTargets_gr_250 > 0].copy()
    trg['avgPrice'] = trg.sm / trg.nrTargets_gr_250
    return trg.drop(columns='sm')

Second, define targets function as:
def targets(grp):
    grp['Prd'] = grp.startDate.apply(lambda x: dRng.asof(x) + td30)
    grp.set_index('Prd', inplace=True)
    trg30 = grp.groupby(level=0).agg(
        nrTargets_gr_250=('INDEX_250', 'count'), sm=('priceDeal', 'sum'))\
        .reindex(dRng, fill_value=0)
    trg60 = trg30.rolling(2).sum().fillna(0, downcast='infer')
    trg30 = trgReformat(trg30)
    trg60 = trgReformat(trg60)
    return trg30.join(trg60, how='outer', lsuffix='_30', rsuffix='_60')\
        .fillna(0, downcast='infer').rename_axis('startDate')

This function uses named aggregations, to compute:

*

*nrTargets_gr_250 - the number of rows,

*sm - sum of prices.

The reason is that computing of trg60 is performed using rolling (for
2 consecutive 30-day periods), so average alone would be not sufficient
here.
Computation of the average price can be performed as late as in reformatting
of each target.
Application of this function is just as before.


text:
Q: Java: how to use an object from another class So, I have three classes: TesteFuncionario, Funcionario and Data.
What I want to do is call a method from Funcionario
f1.imprimirFuncionario();

This method prints the information about f1
public void imprimirFuncionario(){
    System.out.println("Nome: "+nome);
    System.out.println("Departamento: "+departamento);
    System.out.println("Salario: "+salario);
    System.out.println("RG: "+rg);
    System.out.println("Data de admissão: "+getData());
}

However, the last line,  System.out.println("Data de admissão: "+getData()); returns null.
I want this line to print the same data that System.out.print("Data de admissão: "+tempDataAtual+"\n"); prints. (This is located in the TesteFuncionario class)
public class TesteFuncionario {

    public static void main(String[] Args) {

        Funcionario f1 = new Funcionario();

        Scanner input = new Scanner(System.in);

        System.out.println("Digite o nome: ");

        String tempNome = input.nextLine();
        f1.setNome(tempNome);

        System.out.println("Digite o RG: ");

        int tempRg = input.nextInt();
        f1.setRg(tempRg);

        System.out.println("Digite o departamento: ");

        String tempDepartamento = input.next();
        f1.setDepartamento (tempDepartamento);

        System.out.println("Digite o salario: ");

        double tempSalario = input.nextDouble();
        f1.setSalario (tempSalario);

        int diaTemp, mesTemp, anoTemp;

        System.out.println("Informe a data de admissão (dd mm aaaa): ");

        diaTemp = input.nextInt();
        mesTemp = input.nextInt();
        anoTemp = input.nextInt();

        Data dataAtual = new Data(diaTemp, mesTemp, anoTemp);

        String tempDataAtual = dataAtual.getData();

        System.out.println("\n *** Antes do aumento ***\n");

        System.out.print("Ganho Anual: ");
        System.out.println(f1.calculaGanhoAnual());
        System.out.print("Data de admissão: "+tempDataAtual+"\n");
        f1.imprimirFuncionario();

        System.out.println("\n *** Depois do aumento ***\n");

        f1.receberAumento(20);

        System.out.print("Ganho Anual: ");
        System.out.println(f1.calculaGanhoAnual());
        System.out.print("Data de admissão: "+tempDataAtual+"\n");
        f1.imprimirFuncionario();
    }
}

public class Data {

    private int dia, mes, ano;

     public Data(int dia, int mes, int ano) {
        this.dia = dia;
        this.mes = mes;
        this.ano = ano;
    }

    public void setDia(int dia){
        this.dia = dia;
    }

    public int getDia(){
        return dia;
    }

    public void setMes(int mes){
        this.mes = mes;
    }

    public int getMes(){
        return mes;
    }

    public void setAno(int ano){
        this.ano = ano;
    }

    public int getAno(){
        return ano;
    }

    public void setData(int dia, int mes, int ano){
        this.dia = dia;
        this.mes = mes;
        this.ano = ano;
    }
    public String getData (){
        return dia + "/" + mes + "/" + ano;
    }

    public void imprimirData(){
        System.out.println("Data: "+dia+"/"+mes+"/"+ano);
    }
}

public class Funcionario {

    private String nome, departamento, data;
    private double salario;
    private int rg;

    public void setNome (String nome){
        this.nome = nome;
    }

    public String getNome (){
        return nome;
    }

    public void setDepartamento(String departamento){
        this.departamento = departamento;
    }

    public String getDepartamento(){
        return departamento;
    }

    public void setData (String data){
        this.data = data;
    }

    public String getData(){
        return data;
    }

    public void setSalario (double salario){
        this.salario = salario;
    }

    public double getSalario (){
        return salario;
    }

    public void setRg(int rg){
        this.rg = rg;
    }

    public int getRg(){
        return rg;
    }

    public void receberAumento(int porcentagem){
        salario = salario + salario*porcentagem/100;
    }

    public double calculaGanhoAnual(){
        return salario*12;
    }

    public void imprimirFuncionario(){
        System.out.println("Nome: "+nome);
        System.out.println("Departamento: "+departamento);
        System.out.println("Salario: "+salario);
        System.out.println("RG: "+rg);
        System.out.println("Data de admissão: "+getData());
    }
}

A: It is null because Funcionario has not had its data String set.
In the main method of main TesteFuncionario you will need to call.
f1.setData("value you want");
This sets the value of data which is then returned in getData().

A: You have to setData on your f1. f1.setData(tempDataAtual);
public class TesteFuncionario {

    public static void main(String[] Args) {

        Funcionario f1 = new Funcionario();

        Scanner input = new Scanner(System.in);

        System.out.println("Digite o nome: ");

        String tempNome = input.nextLine();
        f1.setNome(tempNome);

        System.out.println("Digite o RG: ");

        int tempRg = input.nextInt();
        f1.setRg(tempRg);

        System.out.println("Digite o departamento: ");

        String tempDepartamento = input.next();
        f1.setDepartamento (tempDepartamento);

        System.out.println("Digite o salario: ");

        double tempSalario = input.nextDouble();
        f1.setSalario (tempSalario);

        int diaTemp, mesTemp, anoTemp;

        System.out.println("Informe a data de admissão (dd mm aaaa): ");

        diaTemp = input.nextInt();
        mesTemp = input.nextInt();
        anoTemp = input.nextInt();

        Data dataAtual = new Data(diaTemp, mesTemp, anoTemp);

        String tempDataAtual = dataAtual.getData();
        f1.setData(tempDataAtual);
        System.out.println("\n *** Antes do aumento ***\n");

        System.out.print("Ganho Anual: ");
        System.out.println(f1.calculaGanhoAnual());
        System.out.print("Data de admissão: "+tempDataAtual+"\n");
        f1.imprimirFuncionario();

        System.out.println("\n *** Depois do aumento ***\n");

        f1.receberAumento(20);

        System.out.print("Ganho Anual: ");
        System.out.println(f1.calculaGanhoAnual());
        System.out.print("Data de admissão: "+tempDataAtual+"\n");
        f1.imprimirFuncionario();

    }
}


text:
Q: Is it possible for an Eclipse plugin to make contributions to only a certain view? I have an Eclipse plugin that makes a contribution to the right click menu of the projects in the workspace.
To do that, I use the org.eclipse.ui.menus extension point and the locationURI for my menu contribution is : "popup:org.eclipse.ui.popup.any?after=additions"
The issue is that my plugin is also appearing in the Navigator View but I would like it to appear only in the C/C++ Projects View (id : org.eclipse.cdt.ui.CView)
How could I do that ?


text:
Q: PL SQL : Query to count differents values of a field I have to do counts to the quantity of entitys in the database i have to obtain the quantity of registries for entities that appear
ENTITY OVERALL DATE HOUR
====== ===== ==== ====
ENT1 5 20100318 12:00
ENT2 20 20100318 12:00
ENT3 12 20100318 12:00

CURSOR1
SELECT distinct(rp.cod_entidad),
YYYYYYYYY,
to_date(to_char(SYSDATE,'YYYYMMDD'),'YYYY-MM-DD') as fecha_pago,
to_char(sysdate,'hh-mi-ss') as hora_pago
FROM registry rp, product pc
where pc.nro_solicitud = rp.nro_solicitud
and pc.resp_2= 'OK'
and pc.resp_1= 'OK'

A: select entity, sum(overall)
from registry
group by entity
order by entity

your question is difficult to understand...

A: Use a GROUP BY on the column that you want to be unique.
In order for PL-SQL to not complain you'll have to use an aggregate function that will select a value for the other columns.
I've picked MAX(), but MIN() or the non-existent whatever() will do just as well.
SELECT
  rp.cod_entidad,
  count(*) as rowcount,   -- number of rows per distinct rp.cod_entidad
  MAX(to_date(to_char(SYSDATE,'YYYYMMDD'),'YYYY-MM-DD')) as fecha_pago,
  MAX(to_char(sysdate,'hh-mi-ss')) as hora_pago
FROM registry rp
INNER JOIN product pc ON (pc.nro_solicitud = rp.nro_solicitud)
WHERE pc.resp_2 = 'OK' AND pc.resp_1 = 'OK'
GROUP BY rp.cod_entidad

Implicit where join considered harmful
P.S. please don't use that ugly implicit where join, it is confusing and bad practise, because you are mixing selection criteria with join criteria in your where clause for no reason whatsoever.
We've had explicit join syntax since 1993, I warmly recommend it.
It will make writing correct queries much much easier and it will make your intentions clearer.


text:
Q: WKWebView in Cocoa app can't get the cursor on click I created a simple test app where one field is an NSTextField and another is a <textarea> instead a WKWebView. I can click into the web view once, but if I go back to the NSTextField, I'm unable to get the cursor back into the web view ever again.
Here's a demonstration:

As you can see, the web view is still interactive to some extent, it just can't become (I assume) the first responder again.
Is there something weird about WKWebView and the responder chain? How can I make the WebWebView behave like a normal NSTextField?
Here is a sample project built in Xcode 11.5 in case you want to try it out.
How can this be fixed?

A: The issue seems to be related to the textarea, using content editable <body contenteditable="true"></body> does seem to work.
A workaround for using the textarea is to subclass WKWebView like this:
- (void)mouseDown:(NSEvent *)event
{
    [super mouseDown:event];
    [[self window] makeFirstResponder:self];
}


text:
Q: Implementing contrastive loss and triplet loss in Tensorflow I started to play with TensorFlow two days ago and I'm wondering if there is the triplet and the contrastive losses implemented.
I've been looking at the documentation, but I haven't found any example or description about these things.

A: Update (2018/03/19): I wrote a blog post detailing how to implement triplet loss in TensorFlow.

You need to implement yourself the contrastive loss or the triplet loss, but once you know the pairs or triplets this is quite easy.

Contrastive Loss
Suppose you have as input the pairs of data and their label (positive or negative, i.e. same class or different class). For instance you have images as input of size 28x28x1:
left = tf.placeholder(tf.float32, [None, 28, 28, 1])
right = tf.placeholder(tf.float32, [None, 28, 28, 1])
label = tf.placeholder(tf.int32, [None, 1]). # 0 if same, 1 if different
margin = 0.2

left_output = model(left)  # shape [None, 128]
right_output = model(right)  # shape [None, 128]

d = tf.reduce_sum(tf.square(left_output - right_output), 1)
d_sqrt = tf.sqrt(d)

loss = label * tf.square(tf.maximum(0., margin - d_sqrt)) + (1 - label) * d

loss = 0.5 * tf.reduce_mean(loss)

Triplet Loss
Same as with contrastive loss, but with triplets (anchor, positive, negative). You don't need labels here.
anchor_output = ...  # shape [None, 128]
positive_output = ...  # shape [None, 128]
negative_output = ...  # shape [None, 128]

d_pos = tf.reduce_sum(tf.square(anchor_output - positive_output), 1)
d_neg = tf.reduce_sum(tf.square(anchor_output - negative_output), 1)

loss = tf.maximum(0., margin + d_pos - d_neg)
loss = tf.reduce_mean(loss)

The real trouble when implementing triplet loss or contrastive loss in TensorFlow is how to sample the triplets or pairs. I will focus on generating triplets because it is harder than generating pairs.
The easiest way is to generate them outside of the Tensorflow graph, i.e. in python and feed them to the network through the placeholders. Basically you select images 3 at a time, with the first two from the same class and the third from another class. We then perform a feedforward on these triplets, and compute the triplet loss.
The issue here is that generating triplets is complicated. We want them to be valid triplets, triplets with a positive loss (otherwise the loss is 0 and the network doesn't learn).
To know whether a triplet is good or not you need to compute its loss, so you already make one feedforward through the network...
Clearly, implementing triplet loss in Tensorflow is hard, and there are ways to make it more efficient than sampling in python but explaining them would require a whole blog post !

A:
Tiago,  I don't think you are using the same formula Olivier gave.
Here is the right code (not sure it will work though, just fixing the formula) :
def compute_euclidean_distance(x, y):
    """
    Computes the euclidean distance between two tensorflow variables
    """

    d = tf.reduce_sum(tf.square(tf.sub(x, y)),1)
    return d

def compute_contrastive_loss(left_feature, right_feature, label, margin):

    """
    Compute the contrastive loss as in

    L = 0.5 * Y * D^2 + 0.5 * (Y-1) * {max(0, margin - D)}^2

    **Parameters**
     left_feature: First element of the pair
     right_feature: Second element of the pair
     label: Label of the pair (0 or 1)
     margin: Contrastive margin

    **Returns**
     Return the loss operation

    """

    label = tf.to_float(label)
    one = tf.constant(1.0)

    d = compute_euclidean_distance(left_feature, right_feature)
    d_sqrt = tf.sqrt(compute_euclidean_distance(left_feature, right_feature))
    first_part = tf.mul(one-label, d)# (Y-1)*(d)

    max_part = tf.square(tf.maximum(margin-d_sqrt, 0))
    second_part = tf.mul(label, max_part)  # (Y) * max(margin - d, 0)

    loss = 0.5 * tf.reduce_mean(first_part + second_part)

    return loss

A: Triplet loss with semihard negative mining is now implemented in tf.contrib, as follows:
triplet_semihard_loss(
    labels,
    embeddings,
    margin=1.0
)

where:

Args:

*

*labels: 1-D tf.int32 Tensor with shape [batch_size] of multiclass
integer labels.

*embeddings: 2-D float Tensor of embedding vectors.Embeddings should
be l2 normalized.

*margin: Float, margin term in theloss definition.

Returns:

*

*triplet_loss: tf.float32 scalar.

For further information, check the link bellow:
https://www.tensorflow.org/versions/master/api_docs/python/tf/contrib/losses/metric_learning/triplet_semihard_loss


text:
Q: Two Sum. Difference in return and print I'm doing the famous two sum question from leet code. I noticed, if I wrote:
def findpair(num, target):
    for i in range(len(num)):
        for j in range(i+1, len(num)):
            if num[i] ==num[j]:
                continue
            if num[i] + num[j] == target:
                return(i, j)

mylist = [1, 2, 3 ,4 ,5 , 6]
print(findpair(mylist, 7))

It only returns one pair, which is index 0 and 5.
However, if I change return to print, it will give me all the pair. Why is that?

A: Simply because that's how functions work. when you use the return keyword the function will stop that's why it is returning a single pair.
a better solution is to create a list and each time the condition is true you append the pair to the list. Then when the loop is finished you return the whole list which contains all the pairs.


text:
Q: Debugging PySerial? Log to stdio? Does pySerial provide a logging option for all serial port communications to be logged onto stdio?
I have code like this:
    with serial.Serial('COM62', 921600) as mcu:
        mcu.write('r\r\n')

and I would like to see all the data exchanges happening back and forward


text:
Q: How to display axis label on both sides of the figure in maptplotlib? I want X-axis to be exactly the same both at the bottom and top of my figure. While the ticklabels can be duplicated using ax.tick_params(labeltop=True), it seems to be no analogous command for the label of the axis itself, as ax.xaxis.set_label_position('top') relocates the label instead of duplicating it.
All the similar questions that I found (e.g. In matplotlib, how do you display an axis on both sides of the figure?) seem to be only concerned about the ticklabels, not the axis labels.
I tried using ax.twiny() but it adds a black frame around my plot. Is there a cleaner, minimalist way of duplicating the axis label to the other side of the figure to complement the duplicated ticklabels?
EDIT: minimal working example of the black frame added by ax.twiny():
import seaborn as sns
from matplotlib import pyplot as plt

ax = sns.heatmap([[0, 1], [1, 0]], cbar=None) # no outline around the heatmap
ax.twiny() # adds black frame

A: (Not a matplotlib expert by any means, but regarding your edit):

*

*sns.despine(left=True, bottom=True) will remove the spines.

*You should be able to replicate the xticks, xticklabels, xlim, and xlabel on the twin Axes like so:

ax = sns.heatmap([[0, 1], [1, 0]], cbar=None) # no outline around the heatmap
ax.set_xlabel('foo')

ax1 = ax.twiny() # adds black frame

ax1.set_xticks(ax.get_xticks())
ax1.set_xticklabels(ax.get_xticklabels())
ax1.set_xlabel(ax.get_xlabel())
ax1.set_xlim(ax.get_xlim())

sns.despine(left=True, bottom=True) # remove spines


text:
Q: Oracle Loop delimited list to check if record exist I'm new in PL/SQL, and Got a code from an old program that check if a record exist in a table something like :
     oRetValue := ' ';
  SELECT f1
  INTO oRetValue
  FROM t1
  WHERE w1='w1'
  AND code  = iCode;

it was ok before, but now the application has more than 500 rows to verify. I'd like to pass a string with all the code separated by comma, and the procedure will loop and return all icode not found. Any help would be greatly appreciated.

A: Try this:
select f1
  into oretvalue
  from t1
 where w1 = 'w1'
   and code in
       (select p_code
          from (select level as id,
                       regexp_substr(icode, '[^,]+', 1, level) as p_code
                  from dual
                connect by regexp_substr(icode, '[^,]+', 1, level) is not null));


text:
Q: Change EF 6 Code Generation Strategy from T4 In the past I have successfully created edmx files. This was using EF5 and Visual Studio 2012. I have since upgraded to Visual Studio 2013 and EF6. The existing EF 5 code still works, but now I have a problem. I can create edmx files, and an EntityDataSource, I can configure the data source, it sees the tables and columns fine, but when I try to refresh the schema I get:

The schema could not be determined because of the following error from the EntityDataSource:
Could not find the CLR type for (my type here)

I have seen a solution on-line telling me to change my Code Generation Strategy to default (the existing edmx files created in EF 5 are set as Legacy ObjectContext), but it won't let me do this because the option 'T4' is grayed out.

Is there a way I can force the Code Generation Strategy to not use T4?
EDIT:
Pawel states that EntityDataSource does not support EF 6. Is there a tutorial available that shows an easy step-by-step guide of how to connect to EF 6? I have got all my EF information from the book Beginning ASP.Net 4, but it is now obviously out-dated. I see that EF 6 is still in beta stage. Maybe they'll add support for EntityDataSource at some stage?
EDIT 2:
OK, I've been fiddling around with this for a bit, and I can connect using LinqDataSource. I won't get a chance to play around with it much for a few days, but it looks like this works.
EDIT 3:
Using LinqDataSource doesn't work. The only CRUD operation it can perform is Read. Obviously there must be a way to use the new EF 6.0 framework (Pawel has suggested I use MVC), but they couldn't have broken it completely for my scenario (using web site), could they?
EDIT 4:
I have found a solution for my scenario, see my answer below.

A: In Ef6 you can use legacy context. Just right click the edmx file and in open with option open it in XML viewer. Then search for legacy and set the value of it as true.

A: i already have VS2013 Community, and i was fighting with the same problem. Just like your image, the code generation strategy was disabled, i mean, it wasn't possible to change, but... right click on the property name "Code Generation Strategy" then  just click 'Reset' and the property value will change to Legacy ObjectContext!
I hope that it can help someone!
PD:Sorry, my english is aweful! xP

A: Due to changes in EF6 if you are using EF6 in VS2012/VS2013 the only supported generation strategy is T4. You can get EntityObject based entities and ObjectContext based context by using T4 templates from VS Gallery. Note: EntityDataSource does not currently support EF6.
EDIT
The preview of the EntityDataSourceControl with EF6 support is now available

A: As Pawel mentions you can only use T4 in EF 6. What I did to get my system back to using EF 5 was to uninstall EF 6, using the NuGet package manager (Website -> Manage NuGet Packages -> Installed Packages -> EntityFramework -> Uninstall). Then I had to add EF 5 using NuGet package manager (same menu but Online instead of Installed Packages). Then I had to remove the following from web.config:
<providers>
  <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>

Now when I add an ADO.NET Entity Data Model it asks me what version of Entity Framework I want to use, but Entity Framework 6.0 is grayed out. This is obviously a bug, it should ask this when EF 6.0 is installed, not when it isn't. When it was installed it never asked what version I wanted and just automatically created an edmx for version 6.0

A: I have the same issue and (EF6) and when I changed the Metadata Artifact Processing to "Copy to Output Directory" I still get the same error.  Which has been suggested as a solution to most of my problems.
My steps (to reproduce error):
Create a directory called DAL, add edmx file, allow it to create connection string, add two tables, build.
Create a default.aspx page, drag the EntityDataSource from toolbox, click the flyout Configure DataSource, choose my named Connection from above, and I get the error:
The metatdata specified in the connection string could not be loaded. Consider rebuilding the web project to build assemblies that may contain metadata.  The following error(s) occurred: The provider did not return a ProviderManifest instance.
Been trying to find a solution for about 24h now.
So now when I choose EF5 (not 6) and I do steps above I right click on the Diagram Surface and go to properties I change two setting:
1.) Artifact Processing to "Copy to Output Directory"
2.) Change the Code Generation Strategies to "Legacy ObjectContext" from T4
Which allows me to drag the EntityDataSource from the toolbox, click the flyout Configure DataSource, choose my named Connection from above and everything is back to world of love an programming...
Only took me 24 solid hours and 2 wasted days of coding to finally piece together a suitable solution.  And my laptop got flatten and reinstalled, b/c I was soooo desperate and pulling my hair out.

A: I am using visual studio 2015

*

*Dbl click the xxx.edmx file in the solution explorer, this should open the
diagarm in the designer,

*press alt+enter which opens the property window

*Look for "Code Generation Strategy" property - choose the value T4 from the drop down to Legacy Object Content.


text:
Q: Increment Row Index And Union With Other Tables On Dynamic Dates Question:
I looked at various other examples to increment over rows, but all resulted in the same wrong output. The problem which I encountered was that my code did not successfully increment over rows to build a correct index per new row in the result-set per episode (highlighted in red below).

My first try was:
SET @ep_1 = "Peaky Blinders";
SET @curRow_1 = 0;

SELECT
    DATE_FORMAT(created_at, "%Y%m%d") AS year_month_day,
    @curRow_1 := @curRow_1 + 1 AS row_number,
    @ep_1 AS episode_title,
    COUNT(id) AS episode_plays
FROM netflix.episode_plays
WHERE
    episode_id = "xyz"
    AND created_at >= "2019-07-01" AND created_at <= "2019-07-07"
GROUP BY 1

Other than the rows not incrementing correctly; I also got the following error when I tried setting some variables in the beginning of my code:
Error running query: Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

(Note: I have no affiliation with Netflix, I just used Netflix dummy data to answer my question)

A: I broke down my question in various sections and got to the final answer below.

*

*The most important part was to add the initial result-sets into a subqueries, and thereafter select the data from tables x1,x2, etc.

*The second part of the question was, how to combine multiple datasets together (in my case: how do one not only do it for one specific netflix episode, but multiple episodes)? I settled on the UNION ALL - clause.

*In the first iteration I tried hard-coding the dates, and thereafter found the INTERVAL-function very helpful.

*Finally, the unicode-error I fixed by adding COLLATE utf8_unicode_ci after setting my variables.

If you find mistakes in my code or have any other suggestions, please feel free to suggest them.
-- SET DATA

-- variables for table x1
SET @ep_1 = "Peaky Blinders" COLLATE utf8_unicode_ci;
SET @id_1 = (SELECT id FROM netflix.episodes WHERE episode_title = @ep_1);
SET @date_1 = (SELECT created_at FROM netflix.episodes WHERE episode_title = @ep_1);
SET @curRow_1 = 0;

-- variables for table x2
SET @ep_2 = "Brooklyn Nine-Nine" COLLATE utf8_unicode_ci;
SET @id_2 = (SELECT id FROM netflix.episodes WHERE episode_title = @ep_2);
SET @date_2 = (SELECT created_at FROM netflix.episodes WHERE episode_title = @ep_2);
SET @curRow_2 = 0;

-- QUERY DATA

SELECT
    x1.year_month_day,
    @curRow_1 := @curRow_1 + 1 AS row_number,
    x1.episode_title,
    x1.episode_plays
FROM (
    SELECT
        DATE_FORMAT(created_at, "%Y%m%d") AS year_month_day,
        @ep_1 AS episode_title,
        COUNT(id) AS episode_plays
    FROM netflix.episode_plays
    WHERE
        episode_id = @id_1
        AND created_at >= @date_1 AND created_at <= DATE_ADD(@date_1 , INTERVAL 7 DAY)
    GROUP BY 1) x1

UNION ALL

SELECT
    x2.year_month_day,
    @curRow_2 := @curRow_2 + 1 AS row_number,
    x2.episode_title,
    x2.episode_plays
FROM (
    SELECT
        DATE_FORMAT(created_at, "%Y%m%d") AS year_month_day,
        @ep_2 AS episode_title,
        COUNT(id) AS episode_plays
    FROM netflix.episode_plays
    WHERE
        episode_id = @id_2
        AND created_at >= @date_2 AND created_at <= DATE_ADD(@date_2 , INTERVAL 7 DAY)
    GROUP BY 1) x2


text:
Q: InfluxDB: Use last item from group by time interval I'm trying to move some counters from a 15s daily measurement to a 5min weekly measurement:
SELECT * INTO company."week".foo_counters_5m
FROM company."day".foo_counters
WHERE time > now() - 1d
GROUP BY id,time(5m) fill(none) LIMIT 1

A: As I was writing this question I found an answer using the LAST(<field>) function, not sure if it's the best one:
SELECT LAST(field1),LAST(field2)... INTO company."week".foo_counters_5m
FROM company."day".foo_counters
WHERE time > now() - 1d
GROUP BY id,time(5m) fill(none)

*

*Since LAST operates on fields, I'm quite this query must iterate through each item in the group.

*Unfortunately you can't do LAST(*), you have to SELECT each field

*Tags (id) can be SELECTed by including them in GROUP BY


text:
Q: Run console application without window I have 3 console programs (.exe), and I want to run them from one console application without showing the windows of the 3 console programs.
All programs are written in VC++.
Any suggestions about how I can do this?

A: You can use ShellExecute command to run the other application

A: Take a look at the ShellExecute Function http://msdn.microsoft.com/en-us/library/windows/desktop/bb762153(v=vs.85).aspx
SW_HIDE as last parameter will ... well, hide the window.


text:
Q: How to play a particular item in playlist jwplayer I have a list of mp3 audio files. Suppose i have 10 audio files in playlist then i have 10 buttons to play the playlist item. On first button click 1 audio in playlist will play and so on. I don't want to make separate player for all the 10 audios as then i can play it just using the id of player and play event.
Please anyone have any ideas.
Thanks,


text:
Q: Building a radio telescope! So, I saw recently the idea of a radio telescope and thought how simple they are. So, like any other normal human being, I went on google and searched "how to make a radio telescope" and boom! Almost nothing! Why? I'm pretty sure it isn't classified, nor complicated. Why isn't there any information about making a radio telescope? As a radio amateur myself, I see it as quite strange.
So, anyone willing to provide any ideas on how to make it? Maybe someone will write an article about it somewhere sometime in the near future!
Till now, I know I need these:

*

*A receiver for 1240 MHz (I could try to make it but I have doubts I'll manage since the highest frequency receiver I made was 14 MHz for a ham band)

*An antenna (easily scavenged from old satellite tv gear)

*An amplifier (got one that goes up to 10 GHz and gives around 3-4 dB)

*A pc to plot the data

So, I need some help with the receiver, and maybe antenna (modifying it) and some work on the receiver-pc line.


text:
Q: Why do I get a validation error when trying to disable past dates in datepicker? I have a reactive form that uses ng-bootstrap's datepicker for an optional date field and I'm trying to disable past dates by setting minDate to the current date.

  <input class="form-control" [minDate]="ngdate" placeholder="yyyy-mm-dd" name="dp" formControlName="startDate" ngbDatepicker #d="ngbDatepicker">

    <button class="btn btn-outline-secondary calendar fa fa-calendar" (click)="d.toggle()" type="button"></button>

ngdate: NgbDateStruct = {
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    day: new Date().getDate()
};

this.registerForm = this.formBuilder.group({
    startDate: ['']
});

When I enter a date, this works correcly and all the dates before today are correctly disabled. The problem is that when I submit the form without entering a date, it's invalid with the status errors.ngbdate.
I think this happens because my date field starts out blank (because it's a reactive form) and is not getting initialized.
How can I disable past dates while preventing this validation error from occurring when no date is entered by the user?

A: As per Mr. Jay's comment, this can be solved by changing startDate: [''] to startDate: null.


text:
Q: Carousel adds a useless margin-right to last element I'm having a problem with caroufredsel that I don't know how to resolve.
Here's the code I use for my carousel :
$("#list" + _i).carouFredSel({
                width: '100%',
                align: 'left',
                items: {
                    visible: 5,
                    width: 'auto'
                },
                scroll : {
                    items: 1,
                    duration: 400,
                    fx: "scroll"
                },
                auto: false,
                next: "#right" + _i
            });

And here's the result :

As you can see there's an awful margin-right set to one of the elements that breaks the whole thing. I can't figure what is causing this =/
Obviously, it works like a charm when I remove that margin :

I suppose this margin is here because otherwise we would see partial images in the carousel. But I want it to be that way.
Halp ?
Version of caroufredsel : Latest

A: I had the same problem. It was whitespace the problem for me. Thanks for pointing me to the right direction.
I use comments to eliminate whitespaces and keep my code clean:

A: So I found the problem.
The lib wasn't the problem at all. Some empty nodes were inserted in the DOM along with the other good ones and they were treated as if they had the same width as the images (good nodes then).
It resulted in the carousel's width being too large and then having a messed up behavior.
Everything is well now :)


text:
Q: What is the difference and how to choose between distributed queue and distributed computing platform? there are many files need to process with two computers real-timely,I want to distribute them to the two computers and these tasks need to be completed as soon as possibile(means real-time processing),I am thinking about the below plan:
(1) distributed queue like Gearman
(2)distributed computing platform like hadoop/spark/storm/s4 and so on
I have two questions
(1)what is the advantage and disadvantage between (1) and (2)?
(2) How to choose in (2),hadoop?spark?storm?s4?or other?
thanks!
Maybe I have not described the question clearly. In most case,there are 1000-3000 files with the same format , these files are independent,you do not need to care their order,the size of one file maybe tens to hundreds of KB and in the future, the number of files and size of single file will rise. I have wrote a program , it can process the file and pick up the data and then store the data in mongodb. Now there are only two computers, I just want a solution that can process these files with the program quickly(as soon as possibile) and is easy to extend and maintain
distributed queue is easy to use in my case bur maybe hard to extend and maintain , hadoop/spark is to "big" in the two computers but easy to extend and maintain, which is better, i am confused.

A: It depends a lot on the nature of your "processing". Some dimensions that apply here are:

*

*Are records independent from each other or you need some form of aggregation? i.e: do you need some pieces of data to go together? Say, all transactions from a single user account.

*Is you processing CPU bound? Memory bound? FileSystem bound?

*What will be persisted? How will you persist it?

*Whenever you see new data, do you need to recompute any of the old?

*Can you discard data?

*Is the data somewhat ordered?

*What is the expected load?

A good solution will depend on answers to these (and possibly others I'm forgetting). For instance:

*

*If computation is simple but storage and retrieval is the main concern, you should maybe look into a distributed DB rather than either of your choices.

*It could be that you are best served by just logging things into a distributed filesystem like HDFS and then run batch computations with Spark (should be generally better than plain hadoop).

*Maybe not, and you can use Spark Streaming to process as you receive the data.

*If order and consistency are important, you might be better served by a publish/subscribe architecture, especially if your load could be more than what your two servers can handle, but there are peak and slow hours where your workers can catch up.

etc. So the answer to "how you choose?" is "by carefully looking at the constraints of your particular problem, estimate the load demands to your system and picking the solution that better matches those". All of these solutions and frameworks dominate the others, that's why they are all alive and kicking. The choice is all in the tradeoffs you are willing/able to make.
Hope it helps.

A: First of all, dannyhow is right - this is not what real-time processing is about. There is a great book http://www.manning.com/marz/ which says a lot about lambda archtecture.
The two ways you mentioned serves completly different purposes and are connected to the definition of word "task". For example, Spark will take a whole job you got for him and divide it into "tasks", but the outcome of one task is useless for you, you still need to wait for whole job to finish. You can create small jobs working on the same dataset and use spark's caching to speed it up. But then you won't get much advantage from distribution (if they have to be run one after another).
Are the files big? Are there connected somehow to each other? If yes, I'd go with Spark. If no, distributed queue.


text:
Q: ruby on rails - can I send other parameter on edit path why when I call
<%= link_to 'Edit', edit_quest_path(quest), event: quest.req_event.count , prereq: prereq %>

the event and prereq parameter is not sent to edit page, am I doing it wrong?

A: please modify your code as below
<%= link_to 'Edit', edit_quest_path(quest,event: quest.req_event.count , prereq: prereq) %>


text:
Q: How to pass data to PHP from dynamic form created by jQuery How to submit below form(which is dynamically creating by jQuery) to PHP?
Content: The goal is to enter multiple row values to database. But the problem is, as for now, only one row value in entering to the database. How to enter all the input fields data to database?

Add Row button: Create a new row.
Submit button: Submit the form.

$(".add-row").click(function(){
  $html =
      `

        <input type="number" class="id" placeholder="Enter ID" />
        <input type="text" class="name" placeholder="Enter Name" />

`;
  $(this).closest("table").find("tr").last().prev().after($html);
});

$(".submit-form").submit(function(event){
  event.preventDefault();
  // I am stuck here,
  // I figured out something needs to be done here, but can't figured out what to do!!!
});

    <form method="POST" action="">

      <input type="number" class="id" placeholder="Enter ID" />
      <input type="text" class="name" placeholder="Enter Name" />

      <button type="button" class="add-row">Add Row</button>
      <button type="submit" class="submit-form" name="submitNewData">Submit</button>

    </form>

In my PHP section I am trying to get the form value using POST method, But its only returning only one value. Now how to get all input fields value in PHP:
<?php
// To keep it minimal, simple & understandable, the sanitization part and other things is not given here
if(isset($_POST["submitNewData"])){
    for($i=0; $i<sizeof($_POST["id"]); $i++){
      echo $_POST["id"][$i] . " " . $_POST["name"][$i] . "
";
    }
}
?>

Any guidance/suggestion will really help me!

A: As per the comments previously made, assign a name to both elements using the array notation ( name='id[]' etc ) in both the existing HTML & also the HTML string within the Add Row code.
FYI: The form must either wholly contain the entire table or itself be wholly contained within a single table-cell - straddling table child elements as above is invalid markup and can lead to unpredictable results ( modern browsers are more forgiving than they once were )

        <title>jQuery - Dynamic fields with PHP Processing</title>

        <?php
            if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
                $_POST['id'],
                $_POST['name']
            )){

                foreach( $_POST['id'] as $i => $id ){
                    $name=$_POST['name'][ $i ];
                    printf('
Array Index:%d - ID:%d - Name:%s
', $i, $id, $name );
                }
            }
        ?>
        <form method="POST">

                  <input type="number" class="id" name='id[]' placeholder="Enter ID" />
                  <input type="text" class="name" name='name[]' placeholder="Enter Name" />

                      <button type="button" class="add-row">Add Row</button>
                      <button type="submit" class="submit-form">Submit</button>

        </form>

example:

Yields:

In the above you have I figured out something needs to be done here... only if you intend to do some sort of validation but it is not clear what you wished to actually do there. The submit button will fire off the request perfectly well as is seen here.


text:
Q: What is the use of .byte assembler directive in gnu assembly? While going through some C code having inline assembly I came across the .byte (with a Dot at the beginning) directive.
On checking the assembly reference on web I found that it is used to reserve a byte in memory.
But in the code there was no label before the statement. So I was wondering what is use of an unlabeled .byte directive or any other data storage directive for that matter.
For e.g. if i code .byte 0x0a, how can i use it ?

A: Minimal runnable example
.byte spits out bytes wherever you are. Whether there is a label or not pointing to the byte, does not matter.
If you happen to be in the text segment, then that byte might get run like code.
Carl mentioned it, but here is a complete example to let it sink in further: a Linux x86_64 implementation of true with a nop thrown in:
.global _start
_start:
    mov $60, %rax
    nop
    mov $0, %rdi
    syscall

produces the exact same executable as:
.global _start
_start:
    mov $60, %rax
    .byte 0x90
    mov $0, %rdi
    syscall

since nop is encoded as the byte 0x90.
One use case: new instructions
One use case is when new instructions are added to a CPU ISA, but only very edge versions of the assembler would support it.
So project maintainers may choose to inline the bytes directly to make it compilable on older assemblers.
See for example this Spectre workaround on the Linux kernel with the analogous .inst directive: https://github.com/torvalds/linux/blob/94710cac0ef4ee177a63b5227664b38c95bbf703/arch/arm/include/asm/barrier.h#L23
#define CSDB    ".inst  0xe320f014"

A new instruction was added for Spectre, and the kernel decided to hardcode it for the time being.

A: Here's an example with inline assembly:
#include <stdio.h>
void main() {
   int dst;
   // .byte 0xb8 0x01 0x00 0x00 0x00 = mov $1, %%eax
   asm (".byte 0xb8, 0x01, 0x00, 0x00, 0x00\n\t"
    "mov %%eax, %0"
    : "=r" (dst)
    : : "eax"  // tell the compiler we clobber eax
   );
   printf ("dst value : %d\n", dst);
return;
}

(See compiler asm output and also disassembly of the final binary on the Godbolt compiler explorer.)
You can replace .byte 0xb8, 0x01, 0x00, 0x00, 0x00 with mov $1, %%eax
the run result will be the same. This indicated that it can be a byte which can represent some instruction eg- move or others.

A: There are a few possibilities...  here are a couple I can think of off the top of my head:

*

*You could access it relative to a label that comes after the .byte directive.  Example:
  .byte 0x0a
label:
  mov (label - 1), %eax

*Based on the final linked layout of the program, maybe the .byte directives will get executed as code.  Normally you'd have a label in this case too, though...

*Some assemblers don't support generating x86 instruction prefixes for operand size, etc.  In code written for those assemblers, you'll often see something like:
  .byte 0x66
  mov $12, %eax

To make the assembler emit the code you want to have.

A: The .byte is a directive that allows you to declare a constant byte only known through inspection without any context.
From the GNU Assembler Guide:
.byte  74, 0112, 092, 0x4A, 0X4a, 'J, '\J # All the same value.


text:
Q: Database design to track student attendance I was having a doubt regarding the design of a database table to track students' attendance. Currently, my table students have atleast 4000 students.
Creating a database for attendance to track their attendance will have almost 4000*30days*12months => ~ 1,400,000 rows (neglecting vacations/ sundays).
The attendance table will have:
id (INT)
student_id (INT)
course_id (INT)
data (DATETIME)
present/absent (TINYINT, as I'll store 1/0)
comments

I'm using PHP/MySql. With a table becoming so large, is there any other way?

A: To expand more on @Twinkles alternative, I'm concerned about why you're storing present and absent students in your attendance data. Is it because you want to be able to run a report that shows all kids and whether they were absent on a given day? There's a better way to do it.
Most systems I've seen store either the that the student is present (Positive attendance) or the student is absent (Negative attendance, although rarely referred to by that name). The decision on which to use came down to the structure and reporting requirements of the school (and whoever they report to).
If you're school is concerned when the student is absent for reasons like having to track Truant students, you should use a standard (negative) attendance structure. Most K-12 schools in the US  do it this way.
If you're school only awards credit for courses after a verified number of hours have been completed (e.g. Johnny doesn't pass the course until he's completed his coursework and attended 12 sessions of the class), then a positive attendance structure could be used.
Assuming your data looked like this: (Ignoring the course_id in your example for simplicity)
Attendance:
id | student_id | date       |
------------------------------
1  | 2          | 2013-10-24 |

Students:
student_id | student_name   |
-----------------------------
1          | Johnny Johnson |
2          | Bobby Tables   |
3          | Suzie Smith    |

To get a report of all the kids at your school and their attendance status for the day, you could run a query like:
SELECT s.student_id, s.student_name
,  CASE WHEN a.id IS NOT NULL THEN 'Absent' ELSE 'Present' END as attendance_status
FROM Students s
LEFT JOIN Attendance a on s.student_id=a.student_id AND a.date = '2013-10-24'

Which would return:
Result :
student_id | student_name   | attendance_status |
-------------------------------------------------
1          | Johnny Johnson | Present           |
2          | Bobby Tables   | Absent            |
3          | Suzie Smith    | Present           |

A: You will very probably define an index over ID, student_ID and presence. Since these three values are represented by 9 byte, the whole index will be less than 20MB in size and will fit completely in your memory. I wouldn't worry about it.
Alternative: you could consider only storing a row for every student that missed the lecture.

A: It sounds like a good case for archiving or decreasing granularity. I suspect the exact data becomes less relevant over time. My personal preference would be to have three levels of granularity: daily, weekly and yearly. After data is over a week old you summarise it to weekly. After it's over a year old, summarise it to yearly. I would've said monthly too, but the week to month mapping isn't precise.


text:
Q: Why are these images in a gallery being 'shifted' or 'bumped'? I am trying to implement a variation to how images are displayed for those viewing this website who prefer a tiled viewed over my image existing slider.
The gallery is labeled as follows:

      <?php for ( $x=0; $x<40; $x++)
      {?>

          <img id=img_<?php echo$x;?> data-zoom-image="picsLarge/home-<?php echo $x+1;?>.jpg" class=imgGal src="pics/home-<?php echo $x+1;?>.jpg">

<?php
      }?>

And here is the CSS (not showing bootstrap classes which have not been altered)
#tileGallery
{
  width:90%;
  height:80%;
  margin-left:auto;
  margin-right:auto;
}
.imgGal
{
  max-width: 100%;
  max-height: 100%;
  height: auto;
}

The images are displayed in a grid as I expect them to be, however some are 'bumped' or 'shifted' over, and an empty space is held where I would expect and image to be. (example follows in 3 example images of webpage):
Example images/screenshots of issue: http://johnkellyphotos.com/exampleForSO/
As you can see from the three images above, the mid size web browser displays correctly, whereas the large and small shift the images as if their was an empty one in their spot. To be clear, it is not failing to display the image in the blank space, simply no element exist there.
Here is what I have tried:

*

*Ensuring all images are the exact same size before uploading to server

*Setting overflow to hidden incase some image was somehow larger and 'bumping' the next image

*modifying the padding and margins to most logical values, ranging from 0px/0%, to other smaller values

*displaying images as background images rather than image tags, which appears to fix this particular problem, however leads to a whole new world of other problems that creates a LOT more work in redoing most of the javascript, and ultimately not likely to be worth it if this has a simpler solution

*Adding another div tag between each image to create padding between images

*Adding another div with no overflow surrounding each image that is hard coded to a particular width, and hidden overflow. (This also works but creates a nightmare in making the page dynamic because I have to specify the width exactly.

I would ideally like this to work even if the images are not the exact same size when uploaded, such that they display neatly, centered, and do not 'bump' each other out of position. I was having trouble describing my issue to a search engine and accordingly found it difficult to find anything particularly helpful or specific to my problem.
If any part of this question is unclear, let me know so I can fix it.
Thanks!

A: When using percentages in CSS like you are, many times the widths and heights are outputted in decimals, which are rounded differently by individual browsers. I've encountered problems like this many times where that rounding is inconstant and results in some containers being 1px larger than the neighbor containers which will result in the 'shifted' images.
Lets take grid:

A B C  D E F  G H I

As long as all the elements share the exact same height they will be a perfect grid. however, if A get rounded to 1px taller than the other elements your grid will turn into:

A B C      D E  F G H  I

This is because A is 1px taller than B and C, which makes it encroach 1px into the next "row" that the floats are creating. And now D and E are acting like A is to the left of them and they are starting 1 position further to the right.
This can happen in many different ways that result's in different images getting "pushed" in different areas of the grid.
My suggestion to fix this is to use Javascript to set the heights of the containers. So that they are all the exact same height. Don't rely on CSS percentages giving constant sizes.


text:
Q: If $a\in R-\{0\}$ and $a$ is not a unit and $R$ Principal ideal domain and $a$ cannot be factorized with ireduc. elem then $a$ reducible Bosch Linear Algebra p. 179
This is a part of the proof where where we want to Show that in every principle ideal Domain every element which is not a unit can be factorized with primeelements.
I just want to understand this part which is the beginning of a contradiction proof.

According to our definitions
In a integral Domain with an element $p\neq 0$ such that $p$ is also
  not a unit we  call
$p$ irreducible if from a a equation $p=ab$ follows that either $a$ or
  $b$ is an unit. Otherwise we call $p$ reducible. Hence we have
  established a dichotomy for Elements which are in $R$ but not $0$
  and also not a unit.
We call $p$ a primelement if we know $p|ab\Rightarrow p|a \vee p|b$
  which is also equivalent to $ab\in(p)\Rightarrow a\in(p)\vee b\in(p)$
We already know that every primeelement is also irreducible and in a
  principal ídeal Domain also the Converse.

With that said we want to prrof from our assumptions above that $a$ is reducible. We want to Show that there exists $q,w$ such that $a=qw$ and $q$ or $w$ are not Units.
I have started a contradiction proof. Assuming that $a$ is irreducible
If we look at a product $a=qr$ then $q$ or $r$ must be an unit. If both are Units we get a contadiction because then $a$ would also be a unit. So let $q$ be the unit and $r$ not a unit. We can evoke a contradiction if we could Show that $r$ is a unit nevertheless. But I don't know how.
Edit: I think I got it now
If we write $a$ as a producit of two element so that $a=qw$ for example. Then we can say with our assumption that not $q$ and $w$ can be irreducible. Therefore let $q$ not be reducible without loss. Bacause $q$ is not irreducible $q$ is either reducible or it is a unit or it is a Zero. If it is Zero then $a$ would be Zero too, contradiction. If it is reducible there one can write $q=et$ without loss let $e$ then be a unit then we can write $a=e(tw)$ and $tw$ is not $0$ because otherwise we would get a new contradiction therefore $a$ is irreducible, if $q$ is a unit $a$ also would be irreducible. Therefore in every case $a$ is reducible.

A: Well, let $a$ be reducible. Write $a=a_1b_1$. Then $a_1$ and $b_1$ cannot be units.
Write $a_1=a_2b_2$ similarly. This gives you a sequence of elements $a,a_1,a_2,\ldots$ such that $a_1\mid a$, $a_2\mid a_1$, and so on, or an ascending chain of ideals
$$(a) \subset (a_1)\subset (a_2)\subset \ldots.$$
This series becomes eventually constant in a Noetherian ring such as an integral domain where every finitely generated ideal is principal.
This is what is required in the 2nd part of your proof.


text:
Q: Extension of elliptic complex to an exact sequence This questions concerns elliptic complexes and is closely related to Green's operator of elliptic differential operator.
Let $T_f:\Gamma(E)\rightarrow\Gamma(F)$ be an elliptic partial differential operator of degree $r$ with coefficients $f \in \Gamma(L(J^r E, F))$, where $J^r E$ is the $r$-th jet bundle of $E$.
Given coefficients $f_0$, let $Z^\pm$ be finite-dimensional vector spaces, $T^+: Z^+ \to \Gamma(F)$ and $T^-: \Gamma(E) \to Z^-$ be continuous linear maps such that
$$\begin{pmatrix}T_{f_0} & T^+ \\ T^- & 0\end{pmatrix}: \Gamma(E) \times Z^+ \to \Gamma(F) \times Z^- $$ is invertible (for example, we may choose $Z^- = \ker T_{f_0}$ and $Z^+ = \mathrm{coker} \, T_{f_0}$ with $T^\pm$ being the canonical projection/injection).
In Theorem II.3.3.3 (p. 157f) of Hamilton's work on the Nash-Moser inverse function theorem it is claimed (and attributed to "standard Fredholm theory") that there exists an open neighborhood $U$ of $f_0$ in $\Gamma(L(J^r E, F))$ such that
$$\begin{pmatrix}T_{f} & T^+ \\ T^- & 0\end{pmatrix}$$ is invertible for all $f \in U$.
Side question:

Do you know a reference for the existence of such an open neighborhood $U$?

Real question:

What is the proper generalization of this picture using extended invertible maps to elliptic complexes $\Gamma(E) \overset{T_f}{\to} \Gamma(F) \overset{S_g}{\to} \Gamma(G)$?

The obvious guess is that one goes over to an extended sequence
$$\Gamma(E) \times Z^+ \to \Gamma(F) \times H \to \Gamma(G) \times Z^-,$$
which is exact.
Is this worked-out somewhere?
(I feel like this is a basic statement in elliptic theory but I couldn't find a reference for both questions.)