text:
Q: No index provider 'spatial' found I tried to create a class called Neo4jPoint with an attribute
@Indexed(indexType=IndexType.POINT, indexName="geolocation"
String wkt;
When I run my junit test case, it encountered the following:
java.lang.IllegalArgumentException: No index provider 'spatial' found. Maybe the intended provider (or one more of its dependencies) aren't on the classpath or it failed to load.
    at org.neo4j.kernel.IndexManagerImpl.getIndexProvider(IndexManagerImpl.java:88)
    at org.neo4j.kernel.IndexManagerImpl.getOrCreateNodeIndex(IndexManagerImpl.java:303)
    at org.neo4j.kernel.IndexManagerImpl.forNodes(IndexManagerImpl.java:289)
    at org.neo4j.kernel.IndexManagerImpl.forNodes(IndexManagerImpl.java:283)
    at org.springframework.data.neo4j.support.DelegatingGraphDatabase.createIndex(DelegatingGraphDatabase.java:144)
    at org.springframework.data.neo4j.support.index.IndexProviderImpl.createIndex(IndexProviderImpl.java:93)
    at org.springframework.data.neo4j.support.index.IndexProviderImpl.getIndex(IndexProviderImpl.java:70)
    at org.springframework.data.neo4j.support.index.IndexProviderImpl.getIndex(IndexProviderImpl.java:110)
    at org.springframework.data.neo4j.support.Neo4jTemplate.getIndex(Neo4jTemplate.java:650)
    at org.springframework.data.neo4j.support.mapping.IndexCreationMappingEventListener$1.doWithPersistentProperty(IndexCreationMappingEventListener.java:51)
    at org.springframework.data.neo4j.support.mapping.IndexCreationMappingEventListener$1.doWithPersistentProperty(IndexCreationMappingEventListener.java:47)
    at org.springframework.data.mapping.model.BasicPersistentEntity.doWithProperties(BasicPersistentEntity.java:240)
    at org.springframework.data.neo4j.support.mapping.IndexCreationMappingEventListener.ensureEntityIndexes(IndexCreationMappingEventListener.java:47)
    at org.springframework.data.neo4j.support.mapping.IndexCreationMappingEventListener.onApplicationEvent(IndexCreationMappingEventListener.java:41)
    at org.springframework.data.neo4j.support.mapping.IndexCreationMappingEventListener.onApplicationEvent(IndexCreationMappingEventListener.java:31)
    at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:97)
    at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:334)
    at org.springframework.data.mapping.context.AbstractMappingContext.addPersistentEntity(AbstractMappingContext.java:294)
    at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:60)
    at org.springframework.data.neo4j.support.mapping.Neo4jMappingContext.addPersistentEntity(Neo4jMappingContext.java:43)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:190)
    at org.springframework.data.mapping.context.AbstractMappingContext.getPersistentEntity(AbstractMappingContext.java:159)
    at org.springframework.data.neo4j.support.Neo4jTemplate.getPersistentEntity(Neo4jTemplate.java:601)
    at org.springframework.data.neo4j.support.Neo4jTemplate.getMappingPolicy(Neo4jTemplate.java:486)
    at org.springframework.data.neo4j.support.Neo4jTemplate.getMappingPolicy(Neo4jTemplate.java:656)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:293)
    at org.springframework.data.neo4j.support.Neo4jTemplate.save(Neo4jTemplate.java:287)
    at org.springframework.data.neo4j.repository.AbstractGraphRepository.save(AbstractGraphRepository.java:110)
    at com.isc.enabler.topology.impl.NodeRepositoryImpl.create(NodeRepositoryImpl.java:94)
    at com.isc.enabler.topology.impl.Neo4jLocationTest.testCreateLocation(Neo4jLocationTest.java:53)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:180)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:41)
    at org.junit.runners.ParentRunner$1.evaluate(ParentRunner.java:173)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:28)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:31)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:220)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

I am using spring-data-neo4j 2.2.2.RELEASE
What am I missing here?  I tried to follow "Good Relationships by Michael Hunger" but got lost there at spatial portion...
Many thanks in advance
David

A: You must provide the neo4j-spatial dependency as it is not included with SDN or Neo4j.
SDN Documentation, Neo4j Spatial at Github, Including Neo4j Spatial with Maven


text:
Q: Is it possible to do usual atomic INSERT operation but update Indexes asynchronously? indexes make read fast but write slower. But why can't you have single writes and have db add indexes asynchronously with time, also cache in the INSERT until it's indexed?
Is there any database like that?

A: Converting my comments to an answer:

indexes make read fast but write slower

That's an oversimplification and it's also misleading.
Indexes make data lookups faster because the DBMS doesn't need to do a table-scan to find rows matching a predicate (the WHERE part of a query). Indexes don't make "reads" any faster (that's entirely dependent on the characteristics of your disk IO) and when used improperly they can sometimes even make queries slower (for reasons I won't get into).
I want to stress that the additional cost of writing to a single index, or even multiple indexes, when executing a DML statement (INSERT/UPDATE/DELETE/MERGE/etc) is negligible, really! (In actuality: foreign-key constraints are a much bigger culprit - and I note you can practically eliminate the cost of foreign-key constraint checking by adding additional indexes!). Indexes are primarily implemented using B-trees (a B-tree is essentially like a binary-tree, except rather than each node having only 2 children it can have many children because each tree-node comes with unused space for all those child node pointers, so inserting into the middle of a B-tree won't require data to be moved-around on-disk unlike with other kinds of trees, like a heap-tree).
Consider this QA where a Postgres user (like yourself) reports inserting 10,000 rows into a table. Without an index it took 78ms, with an index it took 84ms, that's only a 7.5% increase, which at that scale (6ms!) is so small it may as well be a rounding error or caused by IO scheduling. That should be proof enough it shouldn't be something you should worry about without actual hard data showing it's a problem for you and your application.
I assume you have this negative impression about indexes after reading an article like this one, which certainly gives the impression that "indexes are bad" - but while the points mentioned in that article are not wrong, there's a LOT of problems with that article so you shouldn't take it dogmatically. (I'll list my concerns with that article in the footer).

But why can't you have single writes and have db add indexes asynchronously with time

By this I assume you mean you'd like a DMBS to do a single-row INSERT by simply appending a new record to the end of a table and then immediately returning and then at an arbitrary point later the DBMS' housekeeping system would update the indexes afterwards.
The problem with that is that it breaks the A, C, and I parts of the the A.C.I.D. model.
Indexes are used for more than just avoiding table-scans: they're also used to store copies of table data for the benefit of queries that would use the index and which also need (for example) a small subset of the table's data, this significantly reduces disk reads. For this reason, RDBMS (and ISO SQL) allow indexes to include non-indexed data using the INCLUDES clause.
Consider this scenario:
CREATE INDEX IX_Owners ON cars ( ownerId ) INCLUDE ( colour );
CREATE INDEX IX_Names  ON people ( name ) INCLUDE ( personId, hairColour );

GO;

SELECT
    people.name,
    people.hairColour,
    cars.colour
FROM
    cars
    INNER JOIN people ON people.personId = cars.ownerId
WHERE
    people.name LIKE 'Steve%'

The above query will not need to read either the cars or people tables on-disk. The DBMS will be able to fully answer the query using data only in the index - which is great because indexes tend to exist in a small number of pages on-disk which tend to be in proximal-locality which is good for performance because it means it will use sequential IO which scales much better than random IO.
The RDBMS will perform a string-prefix index-scan of the people.IX_Names index to get all of the personId (and hairColour) values, then it will look-up those personId values in the cars.IX_Owners index and be able to get the car.colour from the copy of the data inside the IX_Owners index without needing to read the tables directly.

Now, assuming that another database client has just completed inserted a load of records into the cars and/or people table with a COMMIT TRANSACTION just for good measure, and the RDMBS uses your idea of only updating indexes later whenever it feels like it, then if that same database client re-runs the query from above it would return stale data (i.e. wrong data) because the query uses the index, but the index is old.

In addition to using index tree nodes to store copies of table data to avoid non-proximal disk IO, many RDBMS also use index-trees to store entire copies - even multiple copies of table data, to enable other scenarios, such as columnar data storage and indexed-VIEWs - both of these features absolutely require that indexes are updated atomically with table data.

Is there any database like that?

Yes, they exist - but they're not widely used (or they're niche) because for the vast majority of applications it's entirely undesirable behaviour for the reasons described above.
There are distributed databases that are designed around eventual consistency, but clients (and entire application code) needs to be designed with that in-mind, and it's a huge PITA to have to redesign a data-centric application to support eventual-consistency which is why you only really see them being used in truly massive systems (like Facebook, Google, etc) where availability (uptime) is more important than users seeing stale-data for a few minutes.

Footnote:
Regarding this article: https://use-the-index-luke.com/sql/dml/insert

The number of indexes on a table is the most dominant factor for insert performance. The more indexes a table has, the slower the execution becomes. The insert statement is the only operation that cannot directly benefit from indexing because it has no where clause.

I disagree. I'd argue that foreign-key constraints (and triggers) are far more likely to have a larger detrimental effect on DML operations.

Adding a new row to a table involves several steps. First, the database must find a place to store the row. For a regular heap table—which has no particular row order—the database can take any table block that has enough free space. This is a very simple and quick process, mostly executed in main memory. All the database has to do afterwards is to add the new entry to the respective data block.

I agree with this.

If there are indexes on the table, the database must make sure the new entry is also found via these indexes. For this reason it has to add the new entry to each and every index on that table. The number of indexes is therefore a multiplier for the cost of an insert statement.

This is true, but I don't know if I agree that it's a "multiplier" of the cost of an insert.
For example, consider a table with hundreds of nvarchar(1000) columns and several int columns - and there's separate indexes for each int column (with no INCLUDE columns). If you're inserting 100x megabyte-sized rows all-at-once (using an INSERT INTO ... SELECT FROM statement) the cost of updating those int indexes is very likely to require much less IO than the table data.

Moreover, adding an entry to an index is much more expensive than inserting one into a heap structure because the database has to keep the index order and tree balance. That means the new entry cannot be written to any block—it belongs to a specific leaf node. Although the database uses the index tree itself to find the correct leaf node, it still has to read a few index blocks for the tree traversal.

I strongly disagree with this, especially the first sentence: "adding an entry to an index is much more expensive than inserting one into a heap structure".
Indexes in RDBMS today are invariably based on B-trees, not binary-trees or heap-trees. B-trees are essentially like binary-trees except each node has built-in space for dozens of child node pointers and B-trees are only rebalanced when a node fills its internal child pointer list, so a B-tree node insert will be considerably cheaper than the article is saying because each node will have plenty of empty space for a new insertion without needing to re-balance itself or any other relatively expensive operation (besides, DBMS can and do index maintenance separately and independently of any DML statement).
The article is correct about how the DBMS will need to traverse the B-tree to find the node to insert into, but index nodes are efficently arranged on-disk, such as keeping related nodes in the same disk page which minimizes index IO reads (assuming they aren't already loaded into memory first). If an index tree is too big to store in-memory the RDBMS can always keep a "meta-indexes" in-memory so it could potentially instantly find the correct B-tree index without needing to traverse the B-tree from the root.

Once the correct leaf node has been identified, the database confirms that there is enough free space left in this node. If not, the database splits the leaf node and distributes the entries between the old and a new node. This process also affects the reference in the corresponding branch node as that must be duplicated as well. Needless to say, the branch node can run out of space as well so it might have to be split too. In the worst case, the database has to split all nodes up to the root node. This is the only case in which the tree gains an additional layer and grows in depth.

In practice this isn't a problem, because the RDBMS's index maintenance will ensure there's sufficient free space in each index node.

The index maintenance is, after all, the most expensive part of the insert operation. That is also visible in Figure 8.1, "Insert Performance by Number of Indexes": the execution time is hardly visible if the table does not have any indexes. Nevertheless, adding a single index is enough to increase the execute time by a factor of a hundred. Each additional index slows the execution down further.

I feel the article is being dishonest by suggesting (implying? stating?) that index-maintenance happens with every DML. This is not true. This may have been the case with some early dBase-era databases, but this is certainly not the case with modern RDBMS like Postgres, MS SQL Server, Oracle and others.

Considering insert statements only, it would be best to avoid indexes entirely—this yields by far the best insert performance.

Again, this claim in the article is not wrong, but it's basically saying if you want a clean and tidy house you should get rid of all of your possessions. Indexes are a fact of life.

However tables without indexes are rather unrealistic in real world applications. You usually want to retrieve the stored data again so that you need indexes to improve query speed. Even write-only log tables often have a primary key and a respective index.

Indeed.

Nevertheless, the performance without indexes is so good that it can make sense to temporarily drop all indexes while loading large amounts of data—provided the indexes are not needed by any other SQL statements in the meantime. This can unleash a dramatic speed-up which is visible in the chart and is, in fact, a common practice in data warehouses.

Again, with modern RDBMS this isn't necessary. If you do a batch insert then a RDBMS won't update indexes until after the table-data has finished being modified, as a batch index update is cheaper than many individual updates. Similarly I expect that multiple DML statements and queries inside an explicit BEGIN TRANSACTION may cause an index-update deferral provided no subsequent query in the transaction relies on an updated index.
But my biggest issue with that article is that the author is making these bold claims about detrimental IO performance without providing any citations or even benchmarks they've run themselves. It's even more galling that they posted a bar-chart with arbitrary numbers on, again, without any citation or raw benchmark data and instructions for how to reproduce their results. Always demand citations and evidence from anything you read making claims: because the only claims anyone should accept without evidence are logical axioms - and a quantitative claim about database index IO cost is not a logical axiom :)

A: For PostgreSQL GIN indexes, there is the fastupdate feature.  This stores new index entries into a unordered unconsolidated area waiting for some other process to file them away into the main index structure.  But this doesn't directly match up with what you want.  It is mostly designed so that the index updates are done in bulk (which can be more IO efficient), rather than in the background.  Once the unconsolidated area gets large enough, then a foreground process might take on the task of filing them away, and it can be hard to tune the settings in a way to get this to always be done by a background process instead of a foreground process.  And it only applies to GIN indexes. (With the use of the btree_gin extension, you can create GIN indexes on regular scalar columns rather than the array-like columns it usually works with.)  While waiting for the entries to be consolidated, every query will have to sequential scan the unconsolidated buffer area, so delaying the updates for the sake of INSERT can come at a high cost for SELECTs.
There are more general techniques to do something like this, such as fractal tree indexes.  But these are not implemented in PostgreSQL, and wherever they are implemented they seem to be proprietary.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Android: How do I change the rating an indicator rating bar? I have an indicator rating bar:
<RatingBar
    android:id="@+id/ratingBar"
    style="?android:attr/ratingBarStyleIndicator"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:rating="2.5"
    android:numStars="5"/>

You can see that the xml tells the rating bar to reflect 2.5 stars currently.
At a click of a button, I want it to reflect 5 stars instead, so I wrote this code:
indicatorRatingBar = (RatingBar) findViewById(R.id.ratingBar);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        indicatorRatingBar.setIsIndicator(false);
        indicatorRatingBar.setRating(5);
        indicatorRatingBar.setIsIndicator(true);
    }
});

The rating bar does not update at all. I don't know if it is because it is an indicator rating bar?
How can I get this to work properly with the rating bar set at the indicator style?

A: I actually found the answer through trial and error. I just needed to call invalidate on the view as it has changed and it doesn't invalidate itself automatically.
indicatorRatingBar = (RatingBar) findViewById(R.id.ratingBar);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        indicatorRatingBar.setRating(5);
        indicatorRatingBar.invalidate();
        indicatorRatingBar.setIsIndicator(true);
    }
});

A: Change it to
indicatorRatingBar.setRating(5.0f);


text:
Q: Are Android geofences surviving a reboot? is the system persisting them or do I have to add them again them after reboot? I have not found anything about that in the documentation at https://developer.android.com/training/location/geofencing.html

A: I haven't found any documentation confirming this, but my own experiments have shown that they are not persisted across reboots.
My setup was as follows:

*

*Run application

*Application sets up various geofences on first launch only as NEVER_EXPIRE

*Exit application

*Use phone in regions marked by fences

*Confirm fences trigger pending intents which are sent to IntentService

*Leave region

*Reboot phone

*Re-enter region

*Pending intent does not get sent to IntentService

If anyone has more information on this from someone at Google please comment!

A: Geofences will not persist on reboot.
You have to listen for BOOT_COMPLETED action and add geofences again.
Note: If your app installed on external storage(SD card), you will never receive Boot Complete action. So you have to specify android:installLocation="internalOnly" in the manifest tag.
This is because, android device will broadcast BOOT_COMPLETED action before setting up the external storage.

A: Which data do you want to persist? Is it the geofence region in your device or the geofence region stored by Google Play Service Location API ?
I believe the device need to register a region (defined by its latitude, longitude and radius) to Google Play Service (via LocationClient). You also need to provide expiration time, transition type you want to be notified, and the Intent from which you will be notified.
This region will be stored (remotely) not in your App. When it pass its expiration time, Google Play Service will automatically remove it. You can also set it as NEVER_EXPIRE.
If the region is not expired yet, Google Play Service will notify your App (via intent that you send when calling addGeofences).
The source of the region (lat, long, radius) is up to your implementation.


text:
Q: Architecture for WinForms applications? I have started a WinForms project a few weeks ago and as I did not really know what features I wanted, I just added them along the way. This now caused a horrible mess where my MainForm is a big ball of mud and where for example some important state changes are triggered by UI elements to the point I have to call the OnChange Event of a Control in order to change some state in the database.
In short: I've just started a new project where I want to take a better approach. I just don't know which would be the "good" one. In ASP.net MVC, I found the MVVM Pattern really useful, but on the Desktop, MVVM seems to be only intended for WPF, not for WinForms.
The other approach is a three-tier-architecture: I have my Database-Class which currently talks directly to the UI. I now create a new Static Class ("ApplicationState") that talks to the database and fires events to tell the UI "Hey, Something changed!". The UI would manipulate the State which will then handle the database persistence and again raise Events if the UI needs updating. The point here is that the ApplicationState class never modifies the UI directly, but that the UI subscribes to Events. That looks like a clean/"MVC-y" way of doing it, but maybe I am overlooking something here?
Basically my ultimate goal would be to have the UI completely independent from the database layer just to make sure I don't wire in business logic into the UI again.

A: What I would always go for (first) is to have a layered application

*

*Presentation Layer (JUST UI and databinding logic)

*Interface Layer to the Business Layer (defining the contracts for accessing the BL)

*Business Layer implementation (the actual logic, data validation etc...)

*Interface Layer to the Data Access Layer (defining the contracts for accessing the DAL)

*Data Access Layer implementation

This organizes your application extremely well. Then I'd look for some MVC kind approach. I did not develop so much with WinForms, more with Asp.net and some Java Desktop clients (where I used MVC). WinForms works more with the .Net databinding approach (DataSource, DataMember,...). You should go for that approach instead of trying to force something other. I found that it doesn't match that well.
What's always useful is to lay out our UI logic into different controls (like UserControls in Asp.net). This facilitates reuse.

A: NDepend documentation comes with some pretty cool and advanced online blog posts, articles and white books concerning architecture of .NET code.
Advices on partitioning code through .NET assemblies
Control Components Dependencies to gain Clean Architecture
Re-factoring, Re-Structuring and the cost of Levelizing
Evolutionary Design and Acyclic componentization
Layering, the Level metric and the Discourse of Method
Fighting Fabricated Complexity
Also, if you want to continuously check that your UI code is independent from your database code, you can write easily some Code Query Language rules that will be checked live at development time in Visual Studio:
Keep your code structure clean

A: Don't throw in the towel on MVVM - it's valid for WinForms as well.  Basically, if you use data-binding, you have to make a decision about what your objects will bind to. Often, especially for more complex UI, you dont want to bind directly to your domain objects, you want to build specialized classes (sometimes wrappers) that your UI can bind to which provide everything the view needs (the essence of MVVM) and the technique works just as well with Winforms.
A good series on WinForms Model-View-Presenter approach can be found at
The Build Your Own CAB Series Table of Contents

A: Just start writing unit-tests for everything you can think of. As some pieces will turnout difficult to unit-test because of tight coupling to the WinForms, separate them out. Clean. Wash. Repeat.

A: Nido framework is good. However it is just for your back-end architecture. It will give you a solid, flexible, and simpler back-end with t4template. It prove to be having a very good architectural pattern. Furthermore it can plug not just with WinForm but with any other (MVC ASP.NET etc) front-end too..
Then again RocketFramework is also good
Link1: http://rocketframework.codeplex.com
Link2: http://nidoframework.codeplex.com

A: Our rule of thumb is to lean towards MVC for most websites due to the stateless nature of the web.  Unless you're trying to provide a very rich web experience and bring in silverlight, then you should go with MVVM.  XAML goes hand to hand with MVVM and can be your smart client choice as well (or a nice MVCP pattern).
True MVC is almost impossible to uphold in any other circumstance due to the fact that controllers are suppose to handle all input.  Most non web architecture has controls that will provide this for you.  In fact, most say that ASP.NET MVC is a hybrid MVC anyways but it's very good in my experience.

A: Okay,
 I found some nice answers above but as per my 4+ years of experience in winform, I can say that you can use dotnet remoting for this purpose. In simple words, you need to create one solution for your business logic and client side works and another solution for connection with the database which you can called as a server. Both solution should contain some common projects and then you can easily works on your application without worry about your database.
 I would suggest you to read about dotnet remoting.
Hope, this answer is helpful.


text:
Q: Why there is exit code 1 - executing R script from PHP I am trying to execute the following simple R script via PHP but I am always getting exit code 1 if I put library() function call.
library('optparse')
quit()

The PHP script 'test.php' is given as:
<?php
$calc = exec("Rscript test.r", $R_output, $R_exitcode);
print $calc_routine;

The script produces exit code 0 when I remove library() function call, so it's sure that R script is located correctly.

A: There is an environment variable called R_LIBS_USER that tells R where to look for libraries. By default, it is set to a subdirectory in your home directory. Of course when called from a web server, you will be not be running it – the home directory will be different.
First you'll need to determine what your library directory is. From R, call .libPaths() to get it.
Then, you can either tell PHP about the updated value:
<?php
setenv("R_LIBS_USER", "/path/to/your/libraries");
$calc = exec("Rscript test.r", $R_output, $R_exitcode);

Or, in your R code, use .libPaths with a parameter to set the library path to the new value:
.libPaths('/path/to/your/libraries')
library('optparse')
quit()


text:
Q: How to exclude the TR that contains the TD with a specific class I have a function in which I take the first TR of my table and then I take all the TD of this TR.
Now I need to modify this function: when I take the first TR I need to check that if all the TD of my TR have the class 'HD1' I need to take the second TR of the table.
I put my function below. Thanks in advance.
 function getColumnsIdx(id) {
   var header = $("table#" + id + " thead tr:eq(1)");
   var header_fields = $("td", header);
   var header_idx = new Object();
   header_fields.each(function(idx, val) {
     var $$ = $(val);
     var key = $$.text();
     header_idx[key] = idx;
   });
 return header_idx;
}

A: You can look for the first td without that class, and then take its parent:
var header = $("table#" + id + " thead tr td:not(.HD1):eq(0)").parent();

This could, however, result in getting the third/fourth/etc row. If you must always return the second row, even if those cells also all have the HD1 class:
var header = $("table#" + id + " thead tr:eq(0)");
var header_fields = $("td", header);

if (header_fields.length && header_fields.length == header_fields.filter(".HD1").length) {
  header = header.next();
  header_fields = $("td", header);
}

Note: :eq() uses a zero-based index, so use eq(0) to select the first element.

A: You can check if the first row contains only class="HD1" elements by comparing the length of that selector to the length of the  elements in general.
If they're the same length  (all of the  are HD1) - use the second row. Otherwise, use the first.
With HD1:

let $row = $("thead tr:first > .HD1").length === $("thead tr:first > td").length
  ? $("table tr").eq(1)
  : $("table tr").first();

$row.css("color", "red");

    1
    2
    3

    1
    2
    3

Without HD1:

let $row = $("thead tr:first > .HD1").length === $("thead tr:first > td").length
  ? $("table tr").eq(1)
  : $("table tr").first();

$row.css("color", "red");

    1
    2
    3

    1
    2
    3


text:
Q: particular solution of partial differential equation $\frac{\partial^2z}{\partial x^2}=10x^3y+12x^2y^2$ $$\frac{\partial^2z}{\partial x^2}=10x^3y+12x^2y^2$$
I need to find the particular solution $z(x,y)$ subject to the boundary conditions $$z=y \space and \space \frac{\partial z}{\partial x}=y^2 \space when \space x=1$$
I integrated with respect to x and found: $10y\frac{x^4}{4}+4x^3y^2+f(y)$ then i integrated again this with respect to x and found:$2x^5y+x^4y^2+f(y)x+g(y)$
How do i continue from here to find the particular solution?

A: From integrating twice, we find that
$$z(x,y)=\frac12yx^5+x^4y^2+f(y)x+g(y)$$
Next, we apply the conditions at $x=1$, $z(1,y)=y$ and $z_x(1,y)=y^2$.  Then, we find that
$$\frac12y+y^2+f(y)+g(y)=y \tag 1$$
and
$$\frac52y+4y^2+f(y)=y^2\tag 2$$
From $(2)$ we can determine $f(y)$ and using this form for $f(y)$ and substituting it into $(1)$ we can determine $g$.
Can you finish this now?

A: Check your work, you integrated twice with respect to $x$ and should have:
$$z=\frac12x^5y+x^4y^2+xf(y)+g(y)$$
You need a particular solution such that:
$$z|_{x=1}=\frac12y+y^2+f(y)+g(y)=y$$
$$\frac{\partial z}{\partial y}|_{x=1}=\frac52y+4y^2+f(y)=y^2$$
Solving the second equation gives $f$, then the first gives $g$. They are:
$$f(y)=-3y^2-\frac52y$$
$$g(y)=2y^2+2y$$


text:
Q: didSelectRowAtIndexPath is not work the cell is very simple, just a textLabel. i want to tap the cell and  then print some words. this is a test . but the didSelectRowAtIndexPath is not work. Please tell me why, thank you !
import UIKit
import SnapKit

class ListTableViewController : UITableViewController{
    var itemData: ListTableModel!
    var header: UIView!
    override init(style: UITableViewStyle){
        super.init(style: style)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        itemData = ListTableModel()
        self.tableView.dataSource = self
        self.tableView.delegate = self

    }

    ....

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("mCell", forIndexPath: indexPath)
        cell.textLabel?.userInteractionEnabled = false
        let listCell = cell as! ListTableViewCell
        if let item = itemData.getItemData(indexPath.row) {
            listCell.textLabel!.text = item.valueForKey("title") as? String
        }

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        print("indexPathS")
    }

}

A: Please check if self.tableView.allowsSelection = NO is not written anywhere. And in the storyboard, check if single selection is checked under Selection tab.

A: func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        tableView.deselectRowAtIndexPath(indexPath, animated: true)
        let text:NSString = myArray .objectAtIndex(indexPath.row) as! NSString
        delegate?.myMethod(text as String)
        self.navigationController?.popToRootViewControllerAnimated(true)

    }

you can try this.


text:
Q: Docker : Dynamically created file copy to local machine I am new to docker, I'm dynamically creating a file which is in docker container and want to copy that local machine at the same time, please let me know how it is possible through volumes.
For now, I have to use the below command again and again to check the file data :
docker cp source destination

How it can be done through volumes, the file format will be in .csv or .xlsx? I mean what should I write the command in docker files so that it can copy the file

A: What you need is volume. You have to add your current directory as a volume to the docker container when you first create the container so that they are the same folder. By doing this, you'll be able to sync the files in that folder automatically. But I'm assuming you're using docker for development environment.
This is how I run my container.
docker run -d -it --name {container_name} --volume $PWD:{directory_in_container} --entrypoint /bin/bash {image_name}
In addition to your run command, you have to add --volume $PWD:{directory_in_container} to your run script.
If you have a problem again, just add more detail to your question.
Things you can add might be your Dockerfile, and how you first run your container.


text:
Q: calculateAge (or year) from LINQ Query DateTime field using C# for comparision (Age From) please see calculateAge to convert the Birthdate to current age in years in LINQ Query (it works for other keys, ex: EyeColor, but age conversion failing), I would like to compare with the value that was stored in Array. I tried storing the value in DateTime temp variable above the link, right below "case "AgeTo":" but I can not take the value x.profile.BirthDate as it's allowed only within LINQ Query. It appears that LINQ query is not giving error during build, however, it's failing to con
Error:

LINQ to Entities does not recognize the method 'Int32
  calculateAge(System.DateTime)' method, and this method cannot be
  translated into a store expression.

Any help how to handle?
Code and calculateAge method:
if (searchList.Count > 0)
{
    foreach (KeyValuePair<String, String> kvp in searchList)
    {
        switch (kvp.Key)
        {
            case "AgeFrom":
                photosquery = photosquery.Where(x => calculateAge(Convert.ToDateTime(x.profile.BirthDate)) >= Convert.ToInt32(kvp.Value));
                break;
            case "AgeTo":
                photosquery = photosquery.Where(x => calculateAge(Convert.ToDateTime(x.profile.BirthDate)) <= Convert.ToInt32(kvp.Value));
                break;
            case "EyeColor":
                photosquery = photosquery.Where(x => x.physical.EyesColor.Contains(kvp.Value));
                break;
        }
    }
}

//My code for calculateAge:

public static int calculateAge(DateTime birthDay)
{
    int years = DateTime.Now.Year - birthDay.Year;

    if ((birthDay.Month > DateTime.Now.Month) || (birthDay.Month == DateTime.Now.Month && birthDay.Day > DateTime.Now.Day))
        years--;

    return years;
}

A: The reason you're getting this error is that your Where-clause is being invoked on your Entity queryable, and it doesn't know how to translate the C# code into the equivalent for your database language.
If you were able to rewrite the internals of that function into something that didn't have .NET-based variable storage or referenced only CLR functions that are available in the database you could use it inline, as if you didn't have the function call:
var now = DateTime.Now;
...
case "AgeFrom":
    photosquery = photosquery.Where(x => DbFunctions.DiffYears(x.profile.BirthDate,now) >= Convert.ToInt32(kvp.Value));
    break;

If you want to use the code you have though, you'll need to retrieve all of the data before filtering, which is not generally recommended. You could still achieve this by calling .ToList() before your .Where(..) clause.

A: There's an easier solution.  Rather than comparing the age, compare the dates themselves.
case "AgeFrom":
    var fromAge = Convert.ToInt32(kvp.Value);
    var maxDate = DateTime.Today.AddYears(-fromAge);
    photosquery = photosquery.Where(x => x.profile.BirthDate <= maxDate);
    break;
case "AgeTo":
    var toAge = Convert.ToInt32(kvp.Value);
    var minDate = DateTime.Today.AddYears(-toAge-1).AddDays(1);
    photosquery = photosquery.Where(x => x.profile.BirthDate >= minDate);
    break;

This has the added benefit of making the query sargable, so it can make use of an index, assuming you've created one on the BirthDate field.

A: You are working with IQueryable, so you can't mix it with arbitrary C# code before materialization.
Now you have two options:

*

*Load all your data into app memory with ToList or ToArray and apply your filtering method

*Rewrite your query to use some sql functions (DATEPART for this case)

For second way you can write this query (before switch):
var newQuery = photosquery.Select(x => new
{
    AllQuery = x,
    yearsDiff = (x.profile.BirthDate.Month > now.Month) ||
                (x.profile.BirthDate.Month == now.Month
                   && x.profile.BirthDate.Day > now.Day)
        ? now.Year - x.profile.BirthDate.Year - 1
        : now.Year - x.profile.BirthDate.Year
});

Then when you enter your switch you can write:
case "AgeFrom":
  photosquery = newQuery
      .Where(x => x.yearsDiff >= Convert.ToInt32(kvp.Value))
      .Select(x => x.AllQuery );
  break;


text:
Q: Model property bindings with [FromBody] attribute I want to apply some preprocessing to raw data before it assigned to model properties. Namely to replace comma with dot to allow converting both this strings "324.32" and "324,32" into double. So I wrote this model binder
public class MoneyModelBinder: IModelBinder
    {
        private readonly Type _modelType;
        public MoneyModelBinder(Type modelType)
        {
            _modelType = modelType;
        }

        public Task BindModelAsync(ModelBindingContext bindingContext)
        {
            if (bindingContext == null)
            {
                throw new ArgumentNullException(nameof(bindingContext));
            }

            string modelName = bindingContext.ModelName;

            ValueProviderResult providerResult = bindingContext.ValueProvider.GetValue(modelName);

            if (providerResult == ValueProviderResult.None)
            {
                return TaskCache.CompletedTask;
            }

            bindingContext.ModelState.SetModelValue(modelName, providerResult);

            string value = providerResult.FirstValue;

            if (string.IsNullOrEmpty(value))
            {
                return TaskCache.CompletedTask;
            }

            value = value.Replace(",", ".");

            object result;
            if(_modelType == typeof(double))
            {
                result = Convert.ToDouble(value, CultureInfo.InvariantCulture);
            }
            else if(_modelType == typeof(decimal))
            {
                result = Convert.ToDecimal(value, CultureInfo.InvariantCulture);
            }
            else if(_modelType == typeof(float))
            {
                result = Convert.ToSingle(value, CultureInfo.InvariantCulture);
            }
            else
            {
                throw new NotSupportedException($"binder doesn't implement this type {_modelType}");
            }

            bindingContext.Result = ModelBindingResult.Success(result);
            return TaskCache.CompletedTask;
        }

    }

then appropriate provider
 public class MoneyModelBinderProvider : IModelBinderProvider
    {
        public IModelBinder GetBinder(ModelBinderProviderContext context)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if(context.Metadata?.ModelType == null)
            {
                return null;
            }

            if (context.Metadata.ModelType.In(typeof(double), typeof(decimal), typeof(float)))
            {
                return new MoneyModelBinder(context.Metadata.ModelType);
            }
            return null;
        }
    }

and registering it inside Startup.cs
services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new MoneyModelBinderProvider());

        });

but I noticed some strange behavior or maybe I missed something. If I use this kind of action
 public class Model
    {
        public string Str { get; set; }
        public double Number { get; set; }
    }

    [HttpPost]
    public IActionResult Post(Model model)
    {

        return Ok("ok");
    }

and supply parameters inside query string everything works fine: first provider is called for model itself then for every property of the model. But if I use [FromBody] attribute and supply parameters by JSON, provider is called for model but never called for properties of this model. But why? How can I use binders with FromBody?

A: I've found solution. As it described here [FromBody] behaves differently in comparing to other value providers - it converts complex objects all at once via JsonFormatters. So in addition model binders we should write separate logic just for FromBody. And of course we can catch some points during json processing:
public class MoneyJsonConverter : JsonConverter
{
    public override bool CanWrite => false;

    public override bool CanConvert(Type objectType)
    {
        return objectType == typeof(double);
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        string value = (reader.Value ?? "").Replace(" ", "").Replace(",", ".");

        TypeConverter converter = TypeDescriptor.GetConverter(modelType);
        object result = converter.ConvertFromInvariantString(value);

        return result;;
    }
}

and using
        services.AddMvc(options =>
        {
            options.ModelBinderProviders.Insert(0, new MoneyModelBinderProvider());

        }).AddJsonOptions(options =>
        {
            options.SerializerSettings.Converters.Add(new MoneyJsonConverter());
        });


text:
Q: How to keep the textbox inside of a cell from gridview, in a postback My problem is the following, when you load the page for the first time you see the textbox inside the cell with the red background, but when there is a postback the textbox inside the cell is lost.
load method fill my gridview.
the idea is when the column color is red, i need to create a textbox and put the background of the textbox red;
 protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack)
            {
                Load();
            }

        }

 protected void GvCriticidad_RowDataBound(object sender, GridViewRowEventArgs e)
 {
     if (e.Row.RowType == DataControlRowType.DataRow)
     {
      if (e.Row.Cells[2].Text == "RED") {
          System.Web.UI.WebControls.TextBox txt = new System.Web.UI.WebControls.TextBox();
          txt.Enabled = false;
          txt.Width = 35;
          txt.Height = 30;
          txt.BackColor = ColorTranslator.FromHtml("#FD0707");
          e.Row.Cells[2].Text = "";
          e.Row.Cells[2].Controls.Add(txt);

        }

     }

 }

A: What are you doing on postback? Are you calling for the grid to load again? Based on what you shared the textbox won't show because a postback has occurred there for not calling the Load() method. Does removing the !PostBack check and just calling load every time resolve your issue?
 protected void Page_Load(object sender, EventArgs e)
    {
       Load();

    }


text:
Q: The POST method in DJANGO returns "None" when a form is submitted I have built a small web application that will get the data from a HTML table and dump it into sqlite database. When I use the POST method to capture a particular cell value, it returns none. Could someone please help me how to get the data from the table I created below in table.html ? Initially I am just trying to print the value of the element "name", later on I will add it to DB. I want the output as ["name1","name2"]
models.py
from django.db import models

class people(models.Model):
    Company = models.TextField()
    Contact = models.TextField()
    Country = models.TextField()

    def __str__(self):
        return self.Contact

urls.py
from django.contrib import admin
from django.urls import path, include
from . import views

urlpatterns = [
    path('', views.getvalue, name='myapp'),
]

views.py
from django.shortcuts import render

def home(request):
    return render(request, 'myapp/table.html')

def getvalue(request):

    if request.method == "POST":
        value = request.POST.get("cellvalue")
        print("The values is", value, request.method)
        return render(request, 'myapp/table.html')

table.html

<form role="form" action="getvalue", method="post">{% csrf_token %}
  <input type="submit" value="Update DB" />

      name1
      name2

</form>

A: well i am not really a django guy but are you sure your template is posting any value?
def getvalue(request):
    value = request.POST.get("R1")
    print("The R1 values is", value)
    return render(request, 'myapp/table.html')

on the first call there wont be any post variable at all so if you like to handle this you might be better of with a FormView.
Update on some stuff (might not be the best way because I am no django pro)
so i would go for a FormView that is providing some functionality out of the box. I only got an exmaple for an AuthenticationForm but it might start you off here
so simple view could look like that
class UserLoginView(FormView):
    form_class = AuthenticationForm #UserLoginForm
    template_name = 'yourApp/registration/login.html'
    success_url = reverse_lazy('users_list')

and the template for the form could be something like this

{% load staticfiles %}

<link rel="stylesheet" type="text/css" href="{% static 'yourApp/css/style.css' %}">

Login

<form method="post" >
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit"/>
</form>

so the magic is done by django here since we only tell the template to post stuff with post and the form magic is provided because django knows we use a authentication form. So to do a lot more usefull stuff you might need to read up a little and build out your template accordingly. That said you need to tell your form where to send the post data!!
so does this line really POST data to your getvalue methode???
<form role="form" action="getvalue", method="post">

if you dont know why not do a little print debugging in your method?
def getvalue(request):
    print(dir(request))
    if request.method == "POST":
        value = request.POST.get("cellvalue")
        print("The values is", value, request.method)
        return render(request, 'myapp/table.html')

you should see a lot of stuff in your console now and figure out what finegrained stuff you really want to know.
Update on your Code
with this kind of form
<form role="form" action="getvalue", method="post">{% csrf_token %}

    <input type="submit" value="Update DB"/>

      <input class = splinput type="label" name = "cellvalue" value=""/>
      <input class = splinput type="label" name = "cellvalue" value=""/>
      <input class = splinput type="label" name = "cellvalue" value=""/>

</form>

you need to make it clear for the backend wht to do  with what.so your line

becomes something like
      <input class = splinput type="text" name = "give_me_some_unique_name" value="and_pass_a_value"/>

to find out what input types are there you might want to go here
https://www.w3schools.com/html/html_form_input_types.asp
and read up on it
after that your view should get something you can handle the request.POST object. Here your input name should be the key and value of course value.

A: I modified the HTML file slightly and I got the expected results. It appears like I needed to insert a input within every "td element" and then query its value. Please find the code below:

<form role="form" action="getvalue", method="post">{% csrf_token %}

    <input type="submit" value="Update DB"/>

      <input class = splinput type="text" name = "cellvalue" value=""/>
      <input class = splinput type="text" name = "cellvalue" value=""/>
      <input class = splinput type="text" name = "cellvalue" value=""/>

</form>


text:
Q: Error on magento installation I need to set a magento website on local computer. While loading the website on local computer the page is not loading. This is the apache log.
[Tue Dec 26 23:25:23.551700 2017] [negotiation:error] [pid 8462]
[client 127.0.0.1:38922] AH00687: Negotiation: discovered file(s) matching request: $
[Tue Dec 26 23:25:23.871522 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP Fatal error:  Call to a member function getCode() on boolean in /v$
[Tue Dec 26 23:25:23.871549 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP Stack trace:
[Tue Dec 26 23:25:23.871561 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   1. {main}() /var/www/stage.elb2b.online/index.php:0
[Tue Dec 26 23:25:23.871570 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   2. Mage::run() /var/www/stage.elb2b.online/index.php:71
[Tue Dec 26 23:25:23.871578 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   3. Mage_Core_Model_App->run() /var/www/stage.elb2b.online/app/Ma$
[Tue Dec 26 23:25:23.871587 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   4. Mage_Core_Controller_Varien_Front->dispatch() /var/www/stage.$
[Tue Dec 26 23:25:23.871596 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   5. Mage_Core_Controller_Varien_Router_Standard->match() /var/www$
[Tue Dec 26 23:25:23.871604 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   6. Mage_Core_Controller_Varien_Action->dispatch() /var/www/stage$
[Tue Dec 26 23:25:23.871612 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   7. Mage_Install_IndexController->preDispatch() /var/www/stage.el$
[Tue Dec 26 23:25:23.871621 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   8. Mage_Core_Controller_Varien_Action->preDispatch() /var/www/st$
[Tue Dec 26 23:25:23.871628 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP   9. Mage::dispatchEvent() /var/www/stage.elb2b.online/app/code/co$
[Tue Dec 26 23:25:23.871637 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  10. Mage_Core_Model_App->dispatchEvent() /var/www/stage.elb2b.onl$
[Tue Dec 26 23:25:23.871644 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  11. Mage_Core_Model_App->_callObserverMethod() /var/www/stage.elb$
[Tue Dec 26 23:25:23.871653 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  12. MageWorx_CurrencySwitcher_Model_Observer->currencyAutoswitch($
[Tue Dec 26 23:25:23.871660 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  13. MageWorx_GeoIP_Model_Geoip->getCurrentLocation() /var/www/sta$
[Tue Dec 26 23:25:23.871668 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  14. Mage::getSingleton() /var/www/stage.elb2b.online/app/code/loc$
[Tue Dec 26 23:25:23.871675 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  15. Mage::getModel() /var/www/stage.elb2b.online/app/Mage.php:477
[Tue Dec 26 23:25:23.871683 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  16. Mage_Core_Model_Config->getModelInstance() /var/www/stage.elb$
[Tue Dec 26 23:25:23.871691 2017] [:error] [pid 8462] [client 127.0.0.1:38922] PHP  17. Mage_Customer_Model_Session->__construct() /var/www/stage.elb$

Can you please suggest how can I solve the problem. Any suggestion would be helpful.

A: Try to add this to your Apache Httpd.conf
AddType application/x-httpd-php .php
If this don't help show me print of your php.info


text:
Q: HDMI audio disabled after resuming from sleep Whenever I resume my Ubuntu 17.04 from sleep the HDMI audio output is disabled, and audio has defaulted to the SP-DIF output. I always have to run pavucontrol or go into sound settings to re-select HDMI as the audio output.
As this is a Home Theatre PC running Kodi this is a pain in the neck, as it can't be done using the IR remote.
Is there any way that I can resolve this, either by disabling the SP-DIF output altogether or automatically selecting the HDMI audio device whenever resuming from sleep?

A: There is a complicated way of accomplishing this with udev rules, systemd service and suspend/resume hooks.
An easier way is to check this:
$ cat /etc/pulse/default.pa | grep switch-on-port-available
load-module module-switch-on-port-available

If the second line doesn't begin with a # (commented out) then edit the file and insert a # in the beginning.
Now all output will be controlled to what you manually set it to and stay there until you change it.

A: For the benefit of anyone who hits this problem....Following advice given on another forum I upgraded my kernel from 4.10 to 4.15 and it seems to have fixed the problem.


text:
Q: PhantomJS includeJs() + Nested evaluate() Not Working Consider the following code...
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'Lisas headless browser';
page.open('http://www.httpuseragent.org', function(status) {
    if (status !== 'success')
    {
        console.log('Unable to access network or site is down');
    }else{
        page.includeJs(
            // Include the https version, you can change this to http if you like.
            'https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js',
            function() {
                (page.evaluate(function() {
                    // jQuery is loaded, now manipulate the DOM
                    console.log(document.getElementById('myagent').textContent);
                }))
            }
        );
    }
    phantom.exit();
});

I'm trying to get some code going that inserts jquery and then allows me to continue performing actions but it doesn't evaluate includeJs()

A: EDIT: As mentioned by Vaviloff in the comment below, you need to subscribe to 'page.onConsoleMessage' events in order to use console.log() inside the page.evaluate() callback. I've updated the code block below to reflect this.
The following code will capture the user agent text from the page using jQuery and also capture evidence of the page content having been manipulated.
var page = require('webpage').create();
console.log('The default user agent is ' + page.settings.userAgent);
page.settings.userAgent = 'Lisas headless browser';
// simple 'page.onConsoleMessage' event handler
page.onConsoleMessage = function (msg) {
  console.log('page.onConsoleMessage');
  console.log(msg);
};
page.open('http://www.httpuseragent.org', function(status) {
  if (status === 'success') {
    // capture the rendered page to 'before.jpg'
    page.render('before.jpg');
    // load the jQuery library
    page.includeJs(
      'http://code.jquery.com/jquery-1.8.2.min.js',
      function() {
        // jQuery is loaded, now manipulate the DOM
        var agent = page.evaluate(function() {
          // This code is executed within the loaded page
          // get the user agent string
          var text = $('#myagent').text();
          // log the text to the console
          console.log('Inside page.evaluate ::', text);
          // time for some mischief
          $('#myagent').html('PhantomJS Strikes Again!');
          // return the text string
          return text;
        });
        // capture the evidence
        page.render('after.jpg');
        // print the user agent text
        console.log(agent);
        // exit now
        phantom.exit(0);
      });
  } else {
    console.log('Unable to access network or site is down');
    phantom.exit(1);
  }
});

Resulting console output:
The default user agent is Mozilla/5.0 (Macintosh; Intel Mac OS X) AppleWebKit/538.1 (KHTML, like Gecko) PhantomJS/2.1.1 Safari/538.1
page.onConsoleMessage
Inside page.evaluate :: Your Http User Agent string is: Lisas headless browser
Your Http User Agent string is: Lisas headless browser


text:
Q: Change a string in a line in file via a script and sed I have a script that restores db dump. As a parameter a database name is passed to this script. In a dump there is a following line:
ALTER DATABASE `previosDbName` CHARACTER ... ;

I have to change previosDbName to a value, passed as a parameter. I try to use sed, but it does not work.
Here is a script:
echo $3

export updateValue="ALTER DATABASE \`$3\`"

echo $updateValue

sed -i 's/ALTER DATABASE `\(.*\)`/${updateValue}/' $4

Here how I run it:
./test.sh dbP dbN medi_6_0 full_path_to_test.sql

The output of the script tells us, that updateValue is a correct one:
medi_6_0
ALTER DATABASE `medi_6_0`

But the result string:
${updateValue} CHARACTER ...;

Instead of:
ALTER DATABASE `medi_6_0` CHARACTER ...;

I've also tried to use double quotes, but it did not help:
sed -i 's/ALTER DATABASE `\(.*\)`/"${updateValue}"/' $4

Update: Solution offered by @Sundeep helped:
sed -i 's/ALTER DATABASE `\(.*\)`/'"${updateValue}"'/' $4

None of solutions described in:
How to use variables in a command in sed?
Helped. As most of solutions (did not check all of them), offered in this topic.

A: You can use:
sed -iE "s/(ALTER DATABASE \`).*(\`)/\1$3\2/" file.sql

*

*Use double quotes so that "$3" can be expanded by shell

*Escape the reverse quotes, otherwise it tells shells to execute the text between ` and ` as a command.

A: To allow variable interpolation enclose sed expression with double quotes.
Also, backtick  ` sign has a special meaning. Everything between backticks is evaluated. So it should be escaped with a backslash \
...
export updateValue="$3"
sed "s/\(ALTER DATABASE\) \`.*\`/\1 \`$updateValue\`/" $4
...

The output:
ALTER DATABASE `medi_6_0` CHARACTER ... ;

A: bash variables  can only expand inside double quotes  and backtick needs to be escaped, i.e.:
sed -i "s/\(ALTER DATABASE\) \`.*\`/\1 \`$3\`/" $4
# ALTER DATABASE `medi_6_0` CHARACTER ... ;

Options:
-i     Edit files in-place (otherwise sends to stdout)


text:
Q: Can I run UnitTests on all devices and UITests only on iOS 9.x devices in Xcode Server? So I spent some time on implementing the first UITests in Xcode 7 to automatically test the main workflows in our app. And everything went fine locally.
However, when I pushed the UITests to the C.I. (Xcode Server) the build broke with the following log message:

xcodebuild: error: Failed to build workspace mycoolapp with scheme
  mycoolapp.
Reason: UI Testing is not supported on "iPad 2" because it
  is running iOS Simulator 8.1 and UI Testing requires iOS Simulator 9.0
  or later.
4.684 (4.687) seconds Test Suite 'mycoolappUITests.xctest' failed at 2015-10-14 11:21:45.242.
  Executed 2 tests, with 2 failures (0 unexpected) in 12.217 (12.229) seconds

So what I understand is that UITests are only supported by iOS 9.x devices (which is reasonable).
What I don't understand is that I can't seem to configure the Xcode Bot to only run UITests on certain devices and UnitTests on all devices.
Am I right about this or is there a configuration option I'm missing? Did anybody run into the same problem?

A: I reckon you should be able to create a new scheme to run your UI Tests and uncheck unit tests from the Test action in Edit Scheme.

Later you can configure your new bot settings be specifying the UI Test scheme, selecting the "Perform test action" and select the iOS9 devices connected to your server.
You can continue to run unit tests with existing bot on all iOS devices and simulators.


text:
Q: How to generate a random number between 1 and 75 repeating every 10 seconds in Swift I have the following code in Swift trying to get a simple random number generator as a simulator for a game.
var randomNumber = 0

override func viewDidLoad() {
    super.viewDidLoad()

    randomNumber = Int(arc4random_uniform(74) + 1)

    label.text = "\(randomNumber)"

}

I'm new to programming Swift but I know to use timer() and import Foundation to use the timer function but I'm not sure how to implement and make it so a new number appears in the label every 10 seconds. Thanks for any help.

A: Use a Timer with an interval of 10 seconds to pull a new number from an array of numbers.  Remove the number from the array so that you don't call the same number twice.  When the stop button is pressed, or you are out of numbers call invalidate on the timer to stop it.
class BingoCaller: UIViewController {
    @IBOutlet weak var label: UILabel!

    var numbers = Array(1...75)
    let letters = ["B", "I", "N", "G", "O"]
    var timer: Timer?

    override func viewDidLoad() {
        timer = Timer.scheduledTimer(withTimeInterval: 10, repeats: true) { timer in
            let index = Int(arc4random_uniform(UInt32(self.numbers.count)))
            let number = self.numbers.remove(at: index)
            self.label.text = "\(self.letters[(number - 1) / 15])-\(number)"
            if self.numbers.isEmpty {
                timer.invalidate()
            }
        }
    }

    @IBAction func stop(_ button: UIButton) {
        timer?.invalidate()
    }
}

Suggestions for next steps:

*

*Add the numbers that have been pulled to a second array.  Use that array to populate a tableView so that Gran is able to review the numbers when someone calls "Bingo!".

*Use AVSpeechSynthesizer to have the iPhone actually speak the numbers.

*Add a reset button to start a new game.  Initialize the numbers to Array(1...75), the calledNumbers to [] and start again.  It's a good idea to move the Timer loop to its own function so that it can be called from a start button.

A: You can define a helper array, that would let you check if that number was already returned:
var array = [Int]()
var timer: Timer?

override func viewDidLoad() {
    super.viewDidLoad()

    timer = Timer.scheduledTimer(timeInterval: 10, target: self, selector: #selector(ViewController.timerFunction), userInfo: nil, repeats: true)
}

func timerFunction(){
    var n = arc4random_uniform(75) + 1
    while array.contains(Int(n)){
        n = arc4random_uniform(75) + 1
    }
    array.append(Int(n))
    label.text = String(n)
    if array.count == 75{
        timer?.invalidate()
    }
}

This way you are sure that the timer is invalidated when all the numbers have already been used and also avoid index-removal errors.


text:
Q: Chernoff inequalities for the sum of Exponential RVs These two well-known Chernoff bounds for the sum of RVs $X=\sum_{k=1}^{n}X_k$ in mulitplicative form,
$\mathbf{P}(X \leq (1- \delta)\mathbf{E}X) \leq e^{-\frac{\delta^2 \mathbf{E}X}{2}}\\
\mathbf{P}(X \geq (1+ \delta)\mathbf{E}X) \leq \big(\frac{e^{\delta}}{(1+\delta)^{(1+\delta)}} \big)^{\mu}
$
apply in the case when $X_k$ take values 0 and 1. I'm wondering if and how these results can extend in a more general case, e.g. when $X_k$ are exponentially distributed iid.

A: As explained by the OP in a comment, Markov inequality yields
$$
P(X\gt(1+\delta)n/\mu)\leqslant \exp(-nI(t/\mu,\delta)),
$$
for every $t\gt0$, where
$$
I(s,\delta)=s(1+\delta)+\log(1-s).
$$
The derivative is $\partial_sI(s,\delta)=1+\delta-1/(1-s)$ hence the optimal choice is $s_\delta=\delta/(1+\delta)$, which yields $I(s_\delta,\delta)=\delta-\log(1+\delta)$, and finally,
$$
P(X\gt(1+\delta)n/\mu)\leqslant\left(\frac{1+\delta}{\mathrm e^\delta}\right)^n.
$$
To sum up, Markov (exponential) inequality yields a family of upper bounds, indexed by $t$ (or by $s$), and one chooses the value of $s$ (or of $t$) which minimizes this upper bound.


text:
Q: Hide a table row in Telerik's RadRichTextBox I'm currently doing some work with Telerik's controls (RadRichTextBox specifically).
We've got a requirement to be able to toggle row visibility on tables in the document.
Setting TableRow.Height to 0 has no effect on the actual visual state of the row if there are contents in any of the cells.
I gather this is likely down to the content having their own height and as such the layout pass is deciding to keep the row at the same height.
I can't find any sort of visibility property (naturally), so I'm at a bit of a loss as to how I go about solving this one.
An approach my team has come up with (which none of us like) is to basically keep track of "last known" formatting information via a serialised tag object against the row / cell, when collapsing a row do so for everything and persist the old data and just re hydrate to reverse - this isn't ideal as it means walking every cell for a paragraph and then walk those for spans.

A: It doesn't have a Visibility property because it is not a FrameworkElement. Most of the controls that you are manipulating inside FlowDocument children are called FrameworkContentElement.
Setting TableRow.Height to 0 is not a good idea and it'll just mess up the look and feel of the UI when you use serialization and deserialization against the document.
In my opinion what I would do is create attach properties for TableRows and when user toggles to hide the TableRows you clear all the TableCells of the TableRow and when they put it back you'll just have to re-add it back. Better than walking to every cell and paragraph.


text:
Q: wrong file identifier/HTTP URL specified I'm trying to send a PDF from a Telegram BOT.When I select a file from my server , it shows this message:
Client error: `POST https://api.telegram.org/botXXXX/sendDocument` resulted in a `400 Bad Request` response:\n {"ok":false,"error_code":400,"description":"Bad Request: wrong file identifier/HTTP URL specified"}\

But when I choose from other servers, it works fine!
my file is this directory :
http://109.169.XX.XX:7070/pdfs/sample.pdf

Should the server port be 80?
code :
$data=[
        'chat_id' =>'YYYYY' ,
        'caption' =>'test' ,
        'document'=>"http://109.169.xx.xx:7070/pdfs/sample.pdf",
        ];

$url = 'https://api.telegram.org/bot' . $token . '/sendDocument';

$client= new \GuzzleHttp\Client([]);
$result  = client->post( $url,['form_params'=>$data]);

A: My problem has been resolved
I had to transfer my code from Port 7070 to port 80
For example, my PDF file address is :
http://109.169.XX.XX/pdfs/sample.pdf

I suggest if you encounter this problem, Be sure your code to run on port 80, and as far as possible use the domain instead of IP


text:
Q: Why is my morse code to english java programming not showing any errors but not printing anything? I'm making a java program that converts morse code to english. I've searched for help, and found that maybe I need to do something with string.split(), but I have no experience with it, and don't know where to put it. Here's my code:
String r = JOptionPane.showInputDialog(null, "Please enter the text you would like to be translated into morse code. Use spaces between letters, and \"|\" for a space. " "\n To print \"Hi there\", you would want to type \'.... .. | - .... . .-. . \'\n\n The morse code will print out at the bottom of your screen.");

char [] regenglish = {'a', 'b', 'c', 'd', 'e', 'f', 'g',
    'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3',
    '4', '5', '6', '7', '8', '9', '!', '?', '.', ',', '/', ':', ';',
    '-', '"', '\'', '(', ')', ' '};

String[] regmorse = { ".- ", "-... ", "-.-. ", "-.. ",
    ". ", "..-. ", "--. ", ".... ", ".. ", ".--- ", "-.- ", ".-.. ", "-- ", "-.",
    "--- ", ".--. ", "--.- ", ".-. ", "... ", "- ", "..- ", "...- ", ".-- ",
    "-..- ", "-.-- ", "--.. ", "----- ", ".---- ", "..--- ",
    "...-- ", "....- ", "..... ", "-.... ", "--... ", "---.. ",
    "----. ", "-.-.-- ", "..--.. ", ".-.-.- ", "--..-- ", "-..-. ", "-- -... ",
    "-.-.- ", "-....- ", ".----. ", "-.--. ", "-.--.- ",
        "| "};

String[] morseChars = r.split(" ");

char[] chars = Arrays.toString(morseChars).toCharArray();
boolean endsWithWordSeparator = Arrays.toString(chars).endsWith("| ");
String st = "";
for (int j = 0; j < chars.length; j++)
{
    for (int i = 0; i < regmorse.length; i++)
    {
        if (regmorse[i].equals(Character.toString(chars[j])))

        {
            st = st + regenglish[i];
        }
    }
}
System.out.println(st);

I guess I'm just confused on why this isn't printing anything, and what role
     string.split() plays, if any.

A: if (regmorse[i].equals(Character.toString(chars[j])))
You're attempting to compare a character against a multi-character string, so this condition will never be satisfied. For instance, you're checking if "-... " is equivalent to ".".
You need to either compare regmorse character-by-character or package the characters of chars together before comparing them against regmorse.


text:
Q: Django 1.6 You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware I am totally new to Django and using Django 1.6 ,
I have User Registration form I am using Django Messaging module.
But when I submit form I get an error :
You cannot add messages without installing django.contrib.messages.middleware.MessageMiddleware
I have django.contrib.messages in INSTALLED_APPS and django.contrib.messages.middleware.MessageMiddleware in MIDDLEWARE_CLASSES.
I have looked at solution provided in this Thread but it didn't worked for me.
Here is the code:
settings.py
INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'south',
    'usersapp',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
)

Views.py:
class RegisterView(FormView):
    template_name = 'register_form.html'
    form_class = RegisterForm

    def form_valid(self, request):
        f = RegisterForm(self.request.POST)
        f.save()

        messages.info(request, "User added.")
        return redirect('/usersapp')

If anyone having this problem and have solution. Please post.

A: I was getting the same problem, and this is what solution I found:
I had a decorator for a method on a CBV; this decorator would check the permissions and issue a message and redirect if the were not valid. The way to resolve was to use the method_decorator decorator to call the decorator function, so:
class MyView(FormView):
...
@custom_permission_required('my.permission')
    def dispatch(self, *args, **kwargs):

became:
from django.utils.decorators import method_decorator
...
class MyView(FormView):
...
@method_decorator(custom_permission_required('my.permission'))
    def dispatch(self, *args, **kwargs):


text:
Q: Pgfplots axis x line = bottom changes plot content I'd like to disable the top border of the plot.
To do so, I used axis x line = bottom.
However, this changed the plots content (the left most and right most bar are now hidden).
How can I achieve this without changing the plot content?
Here is a minimal example:
\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{xcolor}
\usepackage{pgfplots}
\usepgfplotslibrary{dateplot}
\usepackage{filecontents}
\pgfplotsset{
axis x line = bottom,
every x tick label/.append style={rotate=45,anchor=east,yshift=-0.3cm},
}

\begin{filecontents}{minimal.csv}
Datum;A;B;X;Y
2017-05-01;2.92;4.08;135861;14767
2017-06-01;2.92;4.08;135861;14767
2017-07-01;2.85;4.85;137600;96389
2017-08-01;2.78;5.42;137032;16351
2017-09-01;2.75;5.40;108018;56753
2017-10-01;2.66;4.97;156561;40026
\end{filecontents}

\begin{document}

\begin{figure}[ht]
\centering
\begin{tikzpicture}
\begin{axis}[
  date coordinates in=x,
  ybar,
  xtick=data,
]
\addplot table [x = Datum, y = X, col sep=semicolon] {minimal.csv};
\addplot table [x = Datum, y = Y, col sep=semicolon] {minimal.csv};
\end{axis}
\end{tikzpicture}
\end{figure}

\end{document}

A: You could use the starred version: axis x line*=bottom. From pgfplots manual:

The starred versions . . . line* only affect the axis lines, without
  correcting the positions of axis labels, tick lines or other keys
  which are (possibly) affected by a changed axis line.

\documentclass{article}
\usepackage[ngerman]{babel}
\usepackage{pgfplots}% loads tikz, xcolor, graphicx
\pgfplotsset{compat=1.15}% <- added, current version is 1.15
\usepgfplotslibrary{dateplot}
\usepackage{filecontents}
\pgfplotsset{
axis x line* = bottom,% <- changed
every x tick label/.append style={rotate=45,anchor=east,yshift=-0.3cm},
}

\begin{filecontents}{minimal.csv}
Datum;A;B;X;Y
2017-05-01;2.92;4.08;135861;14767
2017-06-01;2.92;4.08;135861;14767
2017-07-01;2.85;4.85;137600;96389
2017-08-01;2.78;5.42;137032;16351
2017-09-01;2.75;5.40;108018;56753
2017-10-01;2.66;4.97;156561;40026
\end{filecontents}

\begin{document}
\begin{figure}[ht]
\centering
\begin{tikzpicture}
\begin{axis}[
  date coordinates in=x,
  ybar,
  xtick=data,
]
\addplot table [x = Datum, y = X, col sep=semicolon] {minimal.csv};
\addplot table [x = Datum, y = Y, col sep=semicolon] {minimal.csv};
\end{axis}
\end{tikzpicture}
\end{figure}
\end{document}

Note that it is recommended to add a compat after loading pgfplots. Current version is 1.15.


text:
Q: My JSONObjectWithData is null I have a problem with my JSON who send me a null value.
I think it's not a problem with my webservice in PhP because my colleague who is a expert in PhP doesn't see any error
Just below my Obj-C code
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);

        dispatch_async(downloadQueue, ^{
            NSData *result = self.envoyerLaDemande;
            dispatch_async(dispatch_get_main_queue(), ^{

                id strResult=nil;

                strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];

                NSLog(@"strResult: %@", strResult);

                NSString* boolOk=[strResult objectForKey:@"result"];
                NSLog(@"BoolOk: %@", boolOk);

And there is the PHP script
$data = array();

if(condition == 1)
{
$data["result"] = "ok";
}
else
{
$data["result"] = "error";
}
$data["result"] = "coucou";
}
echo json_encode($data);

And the methode envoyerLaDemande
-(NSData*)envoyerLaDemande{

NSURL *url = [NSURL URLWithString:@"http://mywebsite.com.com/App/V2/mailTo.php"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];

NSString* requestFields;

requestFields = [NSString stringWithFormat:@"agence=%@&", nomAgence];

request.HTTPBody = requestData;
request.HTTPMethod = @"POST";

NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
} else {
}
return responseData;

}

A: The problem is that you're doing two dispacth_async.
In the first one, you're telling the OS "Perform this code in the background", this will start loading the request in the background. However, immediately following that code you're telling the OS to perform a piece of code on the main thread. This piece of code accesses the result variable which hasn't been set yet because it's still being loaded in the background.
If you insist on using these dispatches, simply removing the dispatch back to the main queue should work. However, consider looking into NSURLConnectionDataDelegate or at the very least use the method sendAsynchronousRequest:queue:completionHandler on your NSURLConnection.
This code should work in your current scenario.
dispatch_queue_t downloadQueue = dispatch_queue_create("downloader", NULL);

dispatch_async(downloadQueue, ^{
    NSData *result = self.envoyerLaDemande;
    id strResult=nil;
    strResult = [NSJSONSerialization JSONObjectWithData:result options:0 error:nil];
    NSLog(@"strResult: %@", strResult);
    NSString* boolOk=[strResult objectForKey:@"result"];
    NSLog(@"BoolOk: %@", boolOk);
}

EDIT:
Instead of simply ignoring the error and response objects, use them to diagnose the problem:
NSHTTPURLResponse *response = nil;
NSError *error = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error == nil && response.statusCode == 200) {
    return responseData;
} else {
    NSLog(@"Error. Status code: %d Error message: %@", response.statusCode, error.localizedDescription);
    return nil;
}


text:
Q: Change ball in pong style arcade game to image with javascript I am new to Javascript and wrote a basic pong arcade game. I am trying to use an image as the ball in the game. I tried to replace the code below with something along the lines of:
var img = new Image();
img.src = "http://yourimage.jpg";

but it did not work. Any suggestions or hints? Would it be easier to create an HTML object. Snippet at the top and full code below. Thanks.
//snippet
function colorCircle(centerX,centerY, radius, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.beginPath();
    canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
    canvasContext.fill();

    // ball
    colorCircle(ballX, ballY, 10, 'green')
}

Full Game:
<html>

<canvas id="gameCanvas" width="800" height="600"></canvas>

<script>
// set my vars
var canvas;
var canvasContext;
var ballX = 50;
var ballY = 50;
var ballSpeedX = 10;
var ballSpeedY = 5;

var player1Score = 0;
var player2Score = 0;
const WINNING_SCORE = 3;
var showingWinScreen = false;

var paddle1Y = 250;
var paddle2Y = 250;

// consts cannot be changed when game is played.
const PADDLE_HEIGHT = 100;
const PADDLE_THICKNESS= 10;

function calculateMousePos(evt) {
    var rect = canvas.getBoundingClientRect();
    var root = document.documentElement;
    var mouseX = evt.clientX - rect.left - root.scrollLeft;
    var mouseY = evt.clientY - rect.top - root.scrollTop;
    return {

        x:mouseX,
        y:mouseY
    }

}

function handleMouseClick(evt) {
    if(showingWinScreen) {
        player1Score = 0;
        player2Score = 0;
        showingWinScreen = false;
    }

}

window.onload = function() {
    canvas = document.getElementById('gameCanvas');
    canvasContext = canvas.getContext('2d');

    var framesPerSecond = 30;
    setInterval(function() {
        moveEverything();
        drawEverything();
    }, 1000/framesPerSecond );

    canvas.addEventListener('mousedown', handleMouseClick);

    // rewatch section 2 lecture 7
    canvas.addEventListener('mousemove',
        function(evt) {
            var mousePos = calculateMousePos(evt);
            paddle1Y = mousePos.y-(PADDLE_HEIGHT/2);

        });
}

function ballReset() {
    if(player1Score >= WINNING_SCORE ||
        player2Score >= WINNING_SCORE) {
        showingWinScreen = true;

    }
    ballSpeedX = -ballSpeedX;
    ballX = canvas.width/2;
    ballY = canvas.height/2;
}

function computerMovement() {
    var paddle2YCenter = paddle2Y + (PADDLE_HEIGHT/2);
    if(paddle2YCenter < ballY-35) {
        paddle2Y += 6;
    } else if(paddle2YCenter > ballY+35) {
        paddle2Y -= 6;
    }
}

function moveEverything() {
    if(showingWinScreen){
        return;
    }
    computerMovement();
    ballX += ballSpeedX;
    ballY += ballSpeedY;

    if(ballX < 0) {
        if(ballY > paddle1Y &&
            ballY < paddle1Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX
        var deltaY = ballY-(paddle1Y+PADDLE_HEIGHT/2);
            ballSpeedY = deltaY * .35;
        } else {
            player2Score += 1; //must be BEFORE ball reset
            ballReset();
            //++ adds one and

        }

    }
    if(ballX > canvas.width) {
        if(ballY > paddle2Y &&
            ballY < paddle2Y+PADDLE_HEIGHT) {
            ballSpeedX = -ballSpeedX

            var deltaY = ballY-(paddle2Y+PADDLE_HEIGHT/2);
            ballSpeedY = deltaY * .35;
        } else {
            player1Score ++;
            ballReset();
            //--removes one

        }
    }
        if(ballY < 0) {
        ballSpeedY = -ballSpeedY;
    }
    if(ballY > canvas.height) {
        ballSpeedY = -ballSpeedY;
    }

}

function drawNet() {
    for(var i=0;i<canvas.height; i+=40) {
        colorRect(canvas.width/2-1, i, 2, 20, 'red');

    }

}

function drawEverything() {

    // next line blanks out the screen with black
    colorRect(0,0,canvas.width,canvas.height,"black");

    if(showingWinScreen){
        canvasContext.fillStyle = "orange";
        if(player1Score >= WINNING_SCORE) {
            canvasContext.fillText("Left Player Wins!", 350, 200);

        } else if( player2Score >= WINNING_SCORE) {
            canvasContext.fillText("Right Player Wins!", 350, 200);

        }

        canvasContext.fillText("Click to Continue!", 350, 500);
        return;
    }

    drawNet();

    //left player paddle
    colorRect(0,paddle1Y,PADDLE_THICKNESS,PADDLE_HEIGHT, 'white');

    //right player paddle
    colorRect(canvas.width-PADDLE_THICKNESS,paddle2Y,PADDLE_THICKNESS,PADDLE_HEIGHT, 'white');

    // ball
    colorCircle(ballX, ballY, 10, 'green')

    canvasContext.fillText(player1Score, 100, 100);
    canvasContext.fillText(player2Score, canvas.width - 100, 100);

    }

function colorCircle(centerX,centerY, radius, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.beginPath();
    canvasContext.arc(centerX, centerY, radius, 0, Math.PI*2, true);
    canvasContext.fill();

}

function colorRect(leftX,topY, width,height, drawColor){
    canvasContext.fillStyle = drawColor;
    canvasContext.fillRect(leftX,topY, width,height);

}

A: You never actually draw the image. You only specify an image object with a src.
To actually draw the image, try using this after you declare your image object to draw the image at the correct location:
canvasContext.drawImage(img,ballX, ballY);

A: You need to use CanvasRenderingContext2D.drawImage()
Define a function drawBall()
function drawBall(centerX, centerY, radius) {
    // get the ball diameter
    var diameter = radius * 2;

    canvasContext.drawImage(
        img,
        // the region of clipping from the img
        0, 0, img.width, img.height,
        // the region of drawing the ball on the canvas
        centerX - radius, centerY - radius, diameter, diameter
    );
}

Replace following code in function drawEverything()
// ball
colorCircle(ballX, ballY, 10, 'green');

to
// ball
drawBall(ballX, ballY, 10);

For more infomations about CanvasRenderingContext2D.drawImge(), go to MDN CanvasRenderingContext2D.drawImage()


text:
Q: Deletion of compressed file in c# application I'd like to delete a zip file in my code c#
try
 {
   System.IO.File.Delete(@"C:/Projets/Prj.zip");
  }
  catch { }

but i have this error The format of the given path is not supported.
why this exception appears ? How can i fix this error?

A: You used forward slashes rather than backslahes, resulting in:
try
{
    System.IO.File.Delete(@"C:\Projets\Prj.zip");
}
catch { }

It seems some odd character has slipped in somewhere making it invalid. If I copy/paste the line above, it gives me the same exception. However, if I remove the string and type it in by hand, it will give me a FileNotFound (obviously).
Try cop/pasting this line:
System.IO.File.Delete(@"C:\Projets\Prj.zip");

After further investigation, the culprit appears to be a invsible character between the " and the C. Specifically, the unicode character for "left to right embedding" is present. If I convert the string to unicode, you can clearly see it:
System.IO.File.Delete(@"C:\Projets\Prj.zip");

A: File paths in Windows use backslashes, not forward slashes:
System.IO.File.Delete(@"C:\Projets\Prj.zip");

A: Use Path library, to access platform independent path manipulation. Example is given below:
var root = "C:" + Path.DirectorySeparatorChar;

var path = Path.Combine( root, "Projects", "Prj.zip" );

File.Delete(path); //will try to delete C:\Projects\Prj.zip

A: Try
 string file = @"C:\Projets\Prj.zip";
  if( System.IO.File.Exists(file))
    System.IO.File.Delete(file);


text:
Q: How to get Youtube Live Stream by Channel Id in Youtube API V3 in android? I am able to get the list of live stream: https://developers.google.com/youtube/v3/live/docs/liveStreams/list#examples
But how to get the live stream status and live stream link or id for particular channel using youtube v3 api in android?

A: This will return live stream ID
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={CHANNEL_ID}&eventType=live&type=video&key={YOUR_API_KEY}

You can also pass Query to YouTube so YouTube give you all live stream events
https://www.googleapis.com/youtube/v3/search?part=snippet&q={YOUR_SEARCH_QuERY}&eventType=live&type=video&key={YOUR_YOUTUBE_API}

This how i get live stream videos in my app
    private void initVolley(String[] urls) {

        for (String url : urls) {

            if (url.startsWith("https://www.googleapis.com/youtube/v3/")) {
                jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {

                        try {
                            JSONArray jsonArray = response.getJSONArray("items");
                            if (jsonArray.length() > 0) {
                                for (int getItem = 0; getItem < jsonArray.length(); getItem++) {

                                    JSONObject jsonObject = jsonArray.getJSONObject(getItem).getJSONObject("id");
                                    String videoID = jsonObject.getString("videoId");

                                    Log.d(TAG, "void id " + videoID);

                                    mUrlList.add(new video(jsonArray.getJSONObject(getItem).getJSONObject("snippet").getString("title"), jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("medium").getString("url"), " ", "https://www.youtube.com/watch?v=" + videoID, true));

                                    if (mAdapter != null)
                                        mAdapter.notifyDataSetChanged();
                                    Log.d(TAG, videoID + jsonArray.length() + jsonArray.getJSONObject(getItem).getJSONObject("snippet").getJSONObject("thumbnails").getJSONObject("default").getString("url"));

                                }

                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(jsonObjectRequest);
            }
        }
}

And if you have YouTube links maybe you store  your in database then this will return you some usefull info with out API key
https://www.youtube.com/oembed?url=https://www.youtube.com/watch?v=lUOhCtXPN40&format=json

and below code for this
     JsonObjectRequest obreq = new JsonObjectRequest(Request.Method.GET, JsonURL, null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                // mVideo = new video(response.getString("title"), response.getString("thumbnail_url"), response.getString("author_name"));
                                //  mVideoDataSet.add(mVideo);

                                mVideo = new video(url);
                                mVideo.setVideoTitle(response.getString("title"));
                                mVideo.setVideoThimailUrl(response.getString("thumbnail_url"));
                                mVideo.setVideoChannalName(response.getString("author_name"));
                                mVideo.setLiveNow(false);
                                mVideoDataSet.add( mVideo);
                                Log.d(TAG, "inside the volly" + mVideo.getVideoTitle());
                               // Log.d(TAG, mVideoDataSet.get(i).getVideoStreemUrl());

                                if (mAdapter != null) {
                                    mAdapter.notifyDataSetChanged();
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);

                                } else {
                                    Log.d(TAG, "setingAdupter");
//                                    if(mSwipeRefreshLayout.isRefreshing())
//                                        mSwipeRefreshLayout.setRefreshing(false);
                                   mAdapter = new CustomAdapter(mVideoDataSet);
                                    mRecyclerView.setAdapter(mAdapter);

                                }
                                i++;
                                if (i != mUrlList.size())
                                    initVolly();

                            } catch (JSONException e) {

                                e.printStackTrace();
                            }
                        }
                    },
                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                           // if(error)
                          i++;
                            initVolly();
                            Log.e("Volley", "Error");
                        }
                    }
            );
            // Adds the JSON object request "obreq" to the request queue
requestQueue.add(obreq);

and last if you want to see source code here is link

A: I have faced the same problem and managed to figure out a solution for the same. YouTube actually provides an API for this purpose. You can use the search API to get the currently active Live Video ID, if you have the channel ID.
Use the following API:
https://www.googleapis.com/youtube/v3/search?part=snippet&channelId={YOUR_CHANNEL_ID}&eventType=live&type=video&key={YOUR_API_KEY}

The key factor here is you have to set the eventType to live and type to video.
For getting the channel ID, you can use the following request, if you have the channel's username.
https://www.googleapis.com/youtube/v3/channels?part=contentDetails&forUsername={CHANNEL_USER_NAME}&key={YOUR_API_KEY}


text:
Q: asp.net identity: after authentication, add custom user claims to a token provided by AAD After a webapp is successfully authenticated by Azure Active Directory, I need to add custom claims to the token.
Essentially I want to do this in one of my controllers:
if (ExistsUserInDb(User.Identity.Name))
{
   User.Identity.AddClaim("superUser", "true");
}

So that I can keep on reusing the same token when that user does some superPrivilege action on other controllers.
Is this possible?
I've tried these links but they didn't work for me:
How to extend available properties of User.Identity
How to add claims in ASP.NET Identity

A:
asp.net identity: after authentication, add custom user claims to a token provided by AAD

Based on my understanding, your MVC application is configured to use ASP.NET Identity for user authentication and you also use the
Microsoft.Owin.Security.ActiveDirectory package for supporting AAD JWT bearer token authentication as follows:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        TokenValidationParameters = new TokenValidationParameters()
        {
            ValidAudience = "{AAD-client-ID}"
        },
        Tenant = "{tenantID}"
    });

At this point, the above middle-ware would decode the token and create a ClaimsIdentity for wrapping the claims from the incoming JWT token. Per my understanding, you could not modify the incoming token under your controller, but you could handle this under the middle-ware settings as follows:
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
    new WindowsAzureActiveDirectoryBearerAuthenticationOptions
    {
        TokenValidationParameters = new TokenValidationParameters()
        {
            ValidAudience = "{AAD-client-ID}"
        },
        Tenant = "{tenantID}",
        Provider = new OAuthBearerAuthenticationProvider()
        {
            OnValidateIdentity = (context) =>
            {
                //check context.Ticket.Identity.Name
                //add your additional claims here
                context.Ticket.Identity.AddClaim(new Claim("test02", "test02"));
                return Task.FromResult(0);
            }
        }
    });

Moreover, I would use Microsoft.Owin.Security.OpenIdConnect middleware to use OpenIdConnect for AAD authentication as follows:
app.UseOpenIdConnectAuthentication(
    new OpenIdConnectAuthenticationOptions
    {
        ClientId = clientId,
        Authority = Authority,
        PostLogoutRedirectUri = postLogoutRedirectUri,
        Notifications = new OpenIdConnectAuthenticationNotifications()
        {
            SecurityTokenValidated = async (x) =>
            {
                var identity = x.AuthenticationTicket.Identity;

                //check the name, add additional claims
                identity.AddClaim(new Claim("test", "test"));

                await Task.FromResult(0);
            }
        }
    });

Or you could try to add the claims in your controller as follows:
var identity= User.Identity as ClaimsIdentity;
identity.AddClaim(new Claim("test1", "test1"));
HttpContext.GetOwinContext().Authentication.SignIn(identity);

Details, you could follow Integrate Azure AD into a web application using OpenID Connect.