text:
Q: Selenium- Docker Infrastructure - Unable to establish an Selenium Grid with Edge Image I am trying to set up an Selenium Grid to run test in Edge Browser. I am trying to set this up in my local Mac OS machine and if all is good,  I will set it up in the Build machine.
The issue I am facing is the Selenium Node ( Edge Image ) not able to communicate with the Selenium hub
The edge image is the latest ( https://hub.docker.com/r/selenium/node-edge ) as well as the selenium hub ( https://hub.docker.com/r/selenium/hub )
The remaining nodes are getting connected and I am able to see that in the console.

I logged into the docker container of selenium hub and did a ping to the Edge Node and I am able to see that it is pinging. The port 4444 is open and all is good.

I also did the other way round as in logged into the Edge Node and Pinged selenium hub and all is well. The port 5555 is also open for connections

But the unfortunate thing is, the connection is not getting established between the Node Edge image and Selenium hub.
Quite clueless here as this is an off the shelf solution. Did any one face an issue like this ??
edge_1          | 18:20:41.252 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:20:51.226 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:01.229 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:11.231 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:21.199 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:31.201 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:41.203 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:21:51.171 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:22:01.173 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:22:11.180 INFO [NodeServer$1.lambda$start$1] - Sending registration event...
edge_1          | 18:22:21.081 INFO [NodeServer$1.lambda$start$1] - Sending registration event...

To my knowledge, the above message indicates that the Node is trying to reach out to hub but for some reason, not able to ...
Is there a place where I can get more details about this error ? Any help and direction would be great.
The link below seems to be helpful
https://github.com/SeleniumHQ/selenium/issues/9488
But, I am able to clearly see the machines are able to connect with each other and hence its not a firewall issue/port issue/ network issue
@Alexey - Yes. I am using docker-compose up
version: '3.0'

services:
    selenium-hub:
        image: selenium/hub:latest
        ports:
            - '4442:4442'
            - '4443:4443'
            - '4444:4444'

chrome:
    image: selenium/node-chrome:latest
    volumes:
        - /dev/shm:/dev/shm
    environment:
        - HUB_HOST=selenium-hub
        - HUB_PORT=4444
    depends_on:
        - selenium-hub
    ports:
        - "6900:5900"

firefox:
    image: selenium/node-firefox:latest
    volumes:
        - /dev/shm:/dev/shm
    environment:
        - HUB_HOST=selenium-hub
        - HUB_PORT=4444
    depends_on:
        - selenium-hub
    ports:
        - "6902:5900"

edge:
    image: selenium/node-edge:93.0-20210804

    volumes:
        - /dev/shm:/dev/shm
    environment:
        - HUB_HOST=selenium-hub
        - HUB_PORT=4444
        - SE_EVENT_BUS_HOST=selenium-hub
        - SE_EVENT_BUS_PUBLISH_PORT=4442
        - SE_EVENT_BUS_SUBSCRIBE_PORT=4443
    depends_on:
        - selenium-hub
    ports:
        - "6901:5900"

e2e:
    build: .
    image: wdio
    environment:
        - username=${username:-user}
        - password=${password:-password}
        - headless=${headless:-true}
    volumes:
        - ./results:/wdio/results
    depends_on:
        - chrome
        - firefox
        - edge
    entrypoint: npm run test:local -- --suite all

The docker file is
FROM node:12.16.2-buster-slim

WORKDIR /wdio

COPY package*.json ./
RUN npm install --silent

COPY . .

A: @All - I tried all things what ever I can in my knowledge. Nothing worked. Except one thing
Start all the nodes ( FF, Edge, Chrome ) ...wait for say 1 min and then start the selenium-hub container..
Pretty strange...but this is the only solution which I have so far...though not a clean solution.. I can survive with this for the moment...
This might be helpful for some one who faced the same issue...


text:
Q: How to represent highest and lowest values with >  I have a raster and when I plot it, I got the legend as a rectangle.I am asked to plot the legend as the one in this graph (two arrows on bottom and top).

The colours in the triangles to represent all values above 15 and below -10. If the triangles are difficult to put on the legend.Is it possible to just put at
symbols > < before 15 AND 10!.
    on the top > 15   and on the bottom < -10
library(raster)
r <- raster(nrows=10, ncols=10); r <- setValues(r, 1:ncell(r))
plot(r)

A: One way to convey the same message is, as you say, indicating that the bottom and top colours represent "less than -10" and "greater than 15". This is equivalent to saying the ends of the ramp are negative infinity and positive infinity, respectively.
Here's how you might do that with rasterVis::levelplot:
# First, some fake data
r <- raster(matrix(runif(100, -20, 30), 10))

library(rasterVis)
levelplot(r, margin=FALSE, at=c(-Inf, seq(-10, 15, 2.5), Inf),
          colorkey=list(at=seq(-12.5, 17.5, 2.5),
                        labels=c(expression(-infinity),
                                 seq(-10, 15, 2.5),
                                 expression(infinity)))
)

Above, the at argument to levelplot controls the breaks at which colours in the plot will change. We set it such that values between -Inf and -10 are one colour, and then colours change every 2.5 units, until 15, after which colour is constant up to Inf. The at element of the colorkey list controls the colour breaks for the colour legend. Negative and positive infinity will be represented by -12.5 and 17.5. The labels element of colorkey determines the labels that will be plotted at those locations. We can use an expression to include an infinity symbol.
If you want to use a diverging ramp, you could calculate an appropriate ramp manually according to the length of the negative vs. positive sides of the ramp. For example, in the example above, we need 7 positive colours and 5 negative colours, so we can create a ramp of 14 colours, and exclude the first 2:
library(RColorBrewer)
colr <- colorRampPalette(rev(brewer.pal(11, 'RdBu')))(14)[3:14]

Then pass this ramp to col.regions:
levelplot(r, margin=FALSE, at=c(-Inf, seq(-10, 15, 2.5), Inf),
      colorkey=list(at=seq(-12.5, 17.5, 2.5),
                    labels=c(expression(-infinity),
                             seq(-10, 15, 2.5),
                             expression(infinity))),
      col.regions=colr
)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Correct usage of unique() indexes on Titan : PermanentLockingException Update based on later experiments :
Initially I assumed that the PermanentLockingException was due to my usage of unique indices with locking. I removed this unique() property from my index graph configuration and I still run into the same PermanentLockingException.
To clarify, I have two separate indices and I'm trying to update the two of them concurrently. I'm not trying to update the same index from two threads and running into this issue.
This indicates to me that regardless of the index type, some kind of a global lock is obtained by Titan for every index-based transaction ? This means that at any given time Titan can update only one index tree ?
Is this correct ?
Thanks
I'm using Titan 1.0.0 with Cassandra backend. I created two composite indexes on Titan :
index1 =   mgmt.buildIndex(indexName, Vertex.class).
addKey(indexPropertyKey1).addKey(indexPropertyKey2).unique()
.buildCompositeIndex();

index2 =    mgmt.buildIndex(indexName, Vertex.class).
addKey(indexPropertyKey1).addKey(indexPropertyKey3).unique()
.buildCompositeIndex();

My intent behind doing this is to ensure that there is exactly only 1 entry in the backend with Key1+Key2 composite combination. I dont want any duplicates. I want to enforce the same thing with index2.
My understanding was that these are two different index constructs so they should not run into any conflict between each other. But I notice that when I'm trying to do a concurrent access/update on index1 and index2, I get a locking.PermanentLockingException from Titan. If access them serially I don't run into any trouble.
Some questions I have :

*

*Is my usage of unique() correct ?

*I'm not explicitly setting ConsistencyModifier.LOCK, so I'm assuming this is getting set by default to true by some other layer ? Does it matter one way or the other ?

*These are two different indexes. So their access should be mutually exclusive. Am I missing something here ?

*They do share one of the property keys, key1, does that matter ?

*How can I allow concurrent access of these two different indices ? Can I allow this explicitly ? What does it cost ?
Thanks
Here is the error in-case someone is interested :
2016-09-01T12:17:19.29-0700 [App/0]      OUT [Z: C:] 2016-09-01 19:17:19 ERROR [pool-30-thread-1] c.t.t.g.d.StandardTitanGraph [StandardTitanGraph.java:695] Could not commit transaction [8] due to storage exception in system-commit
2016-09-01T12:17:19.29-0700 [App/0]      OUT com.thinkaurelius.titan.core.TitanException: Could not execute operation due to backend exception
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.diskstorage.util.BackendOperation.execute(BackendOperation.java:44)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.diskstorage.keycolumnvalue.cache.CacheTransaction.persist(CacheTransaction.java:87)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.diskstorage.keycolumnvalue.cache.CacheTransaction.flushInternal(CacheTransaction.java:141)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.diskstorage.keycolumnvalue.cache.CacheTransaction.commit(CacheTransaction.java:198)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.diskstorage.BackendTransaction.commit(BackendTransaction.java:135)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.graphdb.database.StandardTitanGraph.commit(StandardTitanGraph.java:692)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx.commit(StandardTitanTx.java:1352)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.thinkaurelius.titan.graphdb.tinkerpop.TitanBlueprintsGraph$GraphTransaction.doCommit(TitanBlueprintsGraph.java:263)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at org.apache.tinkerpop.gremlin.structure.util.AbstractTransaction.commit(AbstractTransaction.java:94)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.ge.predix.acs.privilege.management.dao.GraphGenericRepository.save(GraphGenericRepository.java:113)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.ge.predix.acs.privilege.management.dao.ResourceMigrationManager.doResourceMigration(ResourceMigrationManager.java:52)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at com.ge.predix.acs.privilege.management.dao.ResourceMigrationManager.run(ResourceMigrationManager.java:34)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
2016-09-01T12:17:19.29-0700 [App/0]      OUT    at java.lang.Thread.run(Thread.java:745)
2016-09-01T12:17:19.29-0700 [App/0]      OUT Caused by: com.thinkaurelius.titan.diskstorage.locking.PermanentLockingException: Expected value mismatch for KeyColumn [k=0x 16-165-160-114-116- 30- 97-116-116-114-105- 98-117-116-101-243, c=0x  0]: expected=[] vs actual=[120-133] (store=graphindex)


text:
Q: How to i replace regex patterns using preg_replace function? I have url like below
/test/(?<name>\w+)/(?<id>\d+)/

I want to replace it using preg_replace() function like this
/test/name/(?<id>\d+)/

I tried this but it does not work as i expected.
$subject = '/test/(?<name>\w+)/(?<id>\d+)/';

preg_replace('#\(.*\<name\>.*\)#', 'name', $subject);

A: You could take all the characters until the next ")" using [^)]+.
$subject = '/test/(?<name>\w+)/(?<id>\d+)/';
$subject = preg_replace('#\(.*\<name\>[^)]+\)#', 'name', $subject);
echo $subject;

Outputs :
/test/name/(?<id>\d+)/


text:
Q: A cursor with the name ... already exists - SQL Server 2008 I have a trigger that is used to perform some auditing tasks when changes are made to a table. Within this trigger there is a WHILE loop, and in the loop there is a cursor that is declared, used, closed and then deallocated before the next iteration of the loop.
When I call a stored procedure that changes the table and in turn causes the trigger to run, and I do this from within the Management Studio, all works as expected.
However, when this stored procedure is called from within my Java web application, I get an error: "A cursor with the name ...  already exists".
Is there a reason why this stored procedure would work when I execute it manually, and not work when run from the web application?

A: You can also try this
IF CURSOR_STATUS('global', 'Cursorname') >= -1
BEGIN
    CLOSE Cursorname
    DEALLOCATE Cursorname
END

A: Sounds a little like it is being called by multiple threads and therefore already exists when the second thread tries to use the name. You might try naming your cursor dynamically with a GUID in the name etc.  I would not recommend this approach.
I suggest you remove the cursor from your trigger code if at all possible in favour of a set based approach. Overhead of using a cursor within the trigger must be pretty high.

A: It sounds like you might be using GLOBAL cursors, which could cause problems like this.
If you must use cursors:
If you can, use LOCAL cursors in all your code.
e.g. declare cursor using the "LOCAL" keyword, like this:
DECLARE yourcursor CURSOR LOCAL ...


text:
Q: Same Component in both asp.net, asp.net MVC and Classic ASP I have a big website/application coded in Classic ASP, ASP.NET and ASP.NET MVC.
I have a menu on top with a lot of HTML CSS JS, and some conifiguration (visible or not ...)
and lot of dynamic links.
So the problem is when i have to update the menu i have to update 3 files, one Include in Classic ASP, one ASCX user control in asp.net and one Partial view in asp.NET MVC
I hate code duplication, so is it possible to use only one component ?
I heared about Com but i have no idea where to start.
Thanks for help
Edit : I am thinking know to use a .net Object, that can generate a string containing all the html that i need and then put it in the views MVC and in the asp.net pages
But how to use it in Classic ASP?

A: There's nothing stopping you using a webapi controller to expose this functionality; the webapi controller would return json or xml menu structure to the client browser this in turn would be rendered using by injection of the json over into the browser DOM and styled using CSS.
Classic ASP and MVC ASP.NET would use the same javascript and css.

A: Guess, you can make an action method in asp.net MVC to render the dynamic menu and do AJAX load from the javascript in every part of the site?
UPDATE:
You can make an HTTP GET request in classic ASP to the aforementioned ASP.NET MVC handler, and cache results if its not very dynamic. Anyway it should be pretty fast if its within the same server. I suppose, request will look like in this answer

A: I'm also working in a legacy application that is very much similar to your case, how bad the life is :(
I'll go for XML/XSLT in your case.
I'll create an XML file that contains all the menu details and use XSLT to generate HTML from XML. I can easily use the XML and XSLT in all the three technologies. So every time you need a change you have to change either the XML or XSLT file.
You can even create a simple .NET component that uses the XML/XSLT approach which could be easily used in ASP.NET Web Forms, ASP.NET MVC (in custom view engine?) and in classic asp as well (you have to register).


text:
Q: Адаптивная иконка под локализацию приложения Можно ли как то  сделать чтобы иконка менялась в зависимости от локализации приложения.(На русском языке одна ,на английском другая !)

A: Да, можно. Для любых ресурсов можно
Правой кнопочкой по папке res в структуре проекта -> New -> Android Resource Directory
Выбираете drawable(или любую другую). Слева список "параметров" папки. Выбираете Locale, справа указываете, например, en. Теперь когда у юзера телефон использует англоязычную локаль, возьмутся ресурсы с папки drawable-en, если их там нет - из основной папки drawable


text:
Q: Textual geolocation I need to geolocate a series of entries in a single-country development projects database. I have a brief synopsis for each project within which I would like to identify municipalities (or even larger political entities) to allow me to geolocate each project later on with the GoogleMaps API.
I am trying to extract the geographic information without using natural language processing. I am not keen to use NLP because the project are located in small villages, whose name I can obtain from other sources.
I was considering splitting the text on spaces, and trying to find matches using a Python vocabulary in which the value is the name of the village and the key is the name of the village split at spaces.
Example:
"Project X has been built in The Hague, The Netherlands".
Would give me: "The Hague"

A: I would suggest to use NLP :-) or at least some algorithms related to NLP.
Here you can find list of cities/towns having more than 500 citizens with information about GPS coordinates, region(s), country and continent http://www.geonames.org/ or http://download.geonames.org/export/dump/readme.txt
I would use these data to build very light-weight Name Entity Recognition using https://pypi.org/project/pyahocorasick/ algorithms.
And after that you can have a nice and neat "tree"/hierarchy of village - small region - bigger region - country - continent (maybe even with GPS coordinates if I am not wrong).

A: Try https://geocode.xyz/textscan
https://geocode.xyz/?scantext=Project%20X%20has%20been%20built%20in%20The%20Hague,%20The%20Netherlands&geoit=XML
<geodata>
<match>
<location>The Hague,NL</location>
<latt>52.06805</latt>
<longt>4.29647</longt>
<confidence>0.2</confidence>
<MentionIndices>32</MentionIndices>
<matchtype>locality</matchtype>
</match>
</geodata>


text:
Q: Can I get the ID/name of database that a stored procedure is called from? I have a stored procedure (logging procedures) that all other stored procedures execute to log their use.
Now I would like to add what database the stored procedures that is being log is in.
I would like to get the ID or name of the database the executes the logging procedures in the logging procedures.
Is this possible?

A: You can use DB_NAME() to retrieve current database name. You should pass it as parameter to your logging procedure.
USE Database1

SELECT
    CurrentDatabase = DB_NAME()
-- CurrentDatabase = Database1

USE Database999

SELECT
    CurrentDatabase = DB_NAME()
-- CurrentDatabase = Database999

DECLARE @CurrentDatabase VARCHAR(100) = DB_NAME()

EXEC LogDatabase.dbo.LoggingProcedure
    @DatabaseName = @CurrentDatabase
    -- OtherParameters

A: I think there is no other way without modifying the procs to do this, the best approach is using DB_NAME on the client procs


text:
Q: No action triggered after placing an order I am making my custom payment method module for Magento 1.9.1.1 and I want to do some action when user proceeds to checkout, before the order is placed, and after the order is placed. I implemented action for proceed to checkout event, and then I wanted to add an observer for event when order is placed. In my config.xml file I have this:
<events>
  <controller_action_predispatch_checkout_onepage_index>
    <observers>
      <mycheckout>
        <class>Custom_Paymentmethod_Model_Observer</class>
        <method>checkoutStarted</method>
        <type>singleton</type>
      </mycheckout>
    </observers>
   </controller_action_predispatch_checkout_onepage_index>
   <sales_order_save_after>
     <observers>
       <mycheckout>
         <class>Custom_Paymentmethod_Model_Observer</class>
         <method>initiateCheckout</method>
         <type>singleton</type>
       </mycheckout>
      </observers>
    </sales_order_save_after>
</events>

And in my Observer.php file I got:
class Custom_Paymentmethod_Model_Observer
{
    public function checkoutStarted(Varien_Event_Observer $observer)
    {
        //This action works fine
    }

    public function initiateCheckout(Varien_Event_Observer $observer)
    {
        //Nothing from here is triggered
    }
}

What am I missing here, and what is the issue?
And what event should I use before the order is placed?

A: I believe you are wrongly using the event. I don't think there is an event called sales_order_save_after.
Use this event instead: sales_order_place_after and also change the observer name mycheckout to something else, anything, just need to be unique than what you have used earlier.
Each observer should be wrapped with a unique identifier.
So your code becomes this in config.xml:
<sales_order_place_after>
 <observers>
   <mycheckout_place_after>
     <class>Custom_Paymentmethod_Model_Observer</class>
     <method>initiateCheckout</method>
     <type>singleton</type>
   </mycheckout_place_after>
  </observers>
</sales_order_place_after>

Full list of events in magento here.
[UPDATE]

And what event should I use before the order is placed?

Events for order:
sales_order_place_after => this will fire after order is placed
sales_order_place_before => this will fire before order is placed
etc...

In fact, you could tell when they will be fired from their naming. This is good stuff from Magento team.


text:
Q: Лишний padding в Safari День добрый, есть "скрипочка", во всех браузерах кроме "сафари" отображается правильно, в "сафари" добавляется поддинг не понятно откуда, в результате чего, html код отображается неправильно! Как можно решить данную проблему?!

A: Добавьте вашим элементам принудительно box-sizing: content-box

A: Врапперу поставьте свойство white-space: nowrap;

A: float плохое свойство, на мой взгляд. с ним больше мук и страданий, чем пользы
display:flex очень хорошо его заменяет.

* {
    padding:0;
    margin:0;
    outline:none;
}
body {
    background:silver;
    font-family:'Cuprum', sans-serif;
    font-size:62.5%;
}

/* shedule  */
 ul.shedule {
    padding:5px;
 background:#fff;
    font-size:120%;

    border:1px solid #eee;

    width:219px;
    color:white;
    zoom:1;
}
ul.shedule li {
   display: flex;
    margin-bottom:2px;
}
.shedule .day {
    text-transform:uppercase;

    border-right:2px solid #fff;
    width:122px;
    padding:10px;
    background:#a6ce2c;
}
.shedule .time {

    text-align:center;
    width:75px;
    padding:10px 0;
    background:#333;
}

Понедельник

7:00 - 23:00

Вторник

7:00 - 23:00

Среда

7:00 - 23:00

Четверг

7:00 - 23:00

Пятница

7:00 - 23:00

Суббота

7:30 - 23:00

Воскресенье

ВЫХОДНОЙ


text:
Q: Kinect v1.8 SDK with Unity3D Am developing a football game in Unity3D . in which I need only the foot orientation of the users from which I can detect the angle of the kick.
Am now tracking the whole skeleton data , but I can't able to get the foot orientation angles precisely.
Is there anyway that I can track only the foot of the user without going for the method of Tracking whole skeleton.

A: I have developed some games with unity and kinect. what I did is,
I could access the transform.position of each joints represent the skeleton. then by using relative positions of several joints, I detected the body gestures.
Hope this helps
let me know if you need any assistance


text:
Q: Plotting Data with Basemap I am trying to plot the following dataset using a Basemap instance:
[-0.126929 -0.127279 -0.127851 ..., -0.14199  -0.142828 -0.14335 ]
The problem is I can't have the right number of points displayed on the map. (which is the length of my data list above = 1315 points).
If I define my dataset to be like:

data = np.diag(data)

[[-0.126929  0.        0.       ...,  0.        0.        0.      ]
 [ 0.       -0.127279  0.       ...,  0.        0.        0.      ]
 [ 0.        0.       -0.127851 ...,  0.        0.        0.      ]
 ...,
 [ 0.        0.        0.       ..., -0.14199   0.        0.      ]
 [ 0.        0.        0.       ...,  0.       -0.142828  0.      ]
 [ 0.        0.        0.       ...,  0.        0.       -0.14335 ]]
I have this figure

If I define my dataset to be like:

data = np.ma.masked_where(data==0., data)

[[-0.12692899999999696 -- -- ..., -- -- --]
 [-- -0.12727900000000147 -- ..., -- -- --]
 [-- -- -0.12785099999999971 ..., -- -- --]
 ...,
 [-- -- -- ..., -0.14198999999999984 -- --]
 [-- -- -- ..., -- -0.1428280000000015 --]
 [-- -- -- ..., -- -- -0.1433499999999981]]
I have this figure

fig = plt.figure()

m = Basemap(projection='mill',      \
            llcrnrlon= lonmin-0.02, \
            urcrnrlon= lonmax+0.02, \
            llcrnrlat= latmin-0.02, \
            urcrnrlat= latmax+0.02, \
            resolution='f')

cmap = plt.cm.get_cmap('bwr_r')

x, y = m(*np.meshgrid(lon,lat))
y = y.T
cs = m.contourf(x,y,data,cmap=cmap)

m.drawcoastlines(linewidth=1.,color='grey')
m.drawcountries(linewidth=1.5,color='white')
m.drawmapboundary(color='k',linewidth=2.0)
m.fillcontinents(color='white')

cb = m.colorbar(cs,location='bottom',size='5%',pad='8%')
cb.set_label('[m]',fontsize=12)
plt.show()


text:
Q: Using De Moivre to show $\cos5\theta = P(\cos\theta)$ Where $P$ is a polynomial of the 5th degree. I would understand how to show something like this if $P$ was given, but I'm not exactly sure how to approach this particular problem. I tried starting with $\cos5\theta = (\cos\theta + i\sin\theta)^5 - i\sin5\theta$ but I didn't have any luck.

A: $$\cos 5\theta+i\sin5\theta=e^{i5\theta}=(cos\theta+i\sin\theta)^5=\cos^5\theta+5\cos^4\theta\cdot i\sin\theta-10\cos^3\theta\sin^2\theta-10\cos^2\theta\cdot i\sin\theta+5\cos\theta\sin^4\theta+i\sin^5\theta$$
Now equate real part of left side to that of right side and then use $\sin^2\theta=1-\cos^2\theta$, you will find the polynomial.

A: $\cos 5\theta = Re [(\cos \theta + i \sin \theta)^5]$
or if your prefer
$\cos 5\theta = \frac 12 (\cos \theta + i \sin \theta)^5 + \frac 12 (\cos (-\theta) + i \sin (-\theta))^5$
either way you get:
$\cos 5\theta = \cos^5 \theta - 10 \cos^3\theta \sin^2 \theta + 5 cos \theta \sin^4\theta$
$\sin^2 \theta = (1-\cos^2\theta)$
$\cos 5\theta = \cos^5 \theta - 10 \cos^3\theta (1-\cos^2 \theta) + 5 \cos \theta (1-\cos^2\theta)^2$
multiply that out and you have a polynomial $p(\cos\theta)$

A: In my opinion, solving this in the general case is substantially nicer than actually expanding everything out:
$$\cos(n\theta) = \mathrm{Re}\left(e^{in\theta}\right)$$
$$\cos(n\theta) = \mathrm{Re}\left((e^{i\theta})^n\right)$$
$$\cos(n\theta) = \mathrm{Re}\left(\sum_{k=0}^n {n\choose k}(\cos\theta)^{n-k}(i\sin\theta)^{k} \right)$$
Note that the only times this is real is when $k$ is even:
$$\cos(n\theta) = \sum_{p=0}^{\left \lfloor\frac{n}{2}\right \rfloor } {n\choose 2p}(\cos\theta)^{n-2p}(\sin^2\theta)^{p}(-1)^p $$
$$\cos(n\theta) = \sum_{p=0}^{\left \lfloor\frac{n}{2}\right \rfloor } (-1)^p{n\choose 2p}(\cos\theta)^{n-2p}(1-\cos^2\theta)^{p} $$
which is a polynomial in $\cos\theta$.


text:
Q: C# Resize image from webclient I have a program that sets the image from a link , to a picture box.
For example:
pictureBox1.Load("http://www.e357.net/wordpress/beingernest/wp-content/uploads/2010/07/questionmark-150x150.jpg");
But since the pictureBox size is 100x100, the image gets cut down.
How can i resize the image, without changing the pictureBox size?
Im using WinForms.
Thanks.

A: You can just change your pictureBox1.SizeMode to achieve that behavior.
In your case
pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;

and
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;

should work.


text:
Q: ASP.NET Authentification fails with IE 10 today I've encountered with strange issue.
My site was running on application pool under .NET 4 and today we noticed that it can't authenticate users under IE 10 (with other browsers everything is ok). Here's the exception that was thrown:

Server Error in '/' Application.
Unable to cast object of type
  'System.Security.Principal.GenericIdentity' to type
  'System.Web.Security.FormsIdentity'.  Description: An unhandled
  exception occurred during the execution of the current web request.
  Please review the stack trace for more information about the error and
  where it originated in the code.
Exception Details: System.InvalidCastException: Unable to cast object
  of type 'System.Security.Principal.GenericIdentity' to type
  'System.Web.Security.FormsIdentity'.

But after upgrading .NET 4 to version 4.5 error has gone away. The strange thing is that we didn't change the version of .NET on application pool, it is still .NET 4.
By the way I'm using custom principal and I'm attaching userData to AuthenticationTicket.
Here's my code from the Global.asax:
protected void Application_PostAuthenticateRequest(object sender, EventArgs e)
    {
        HttpCookie authCooke = Request.Cookies[FormsAuthentication.FormsCookieName];
        if (authCooke != null)
        {
            FormsAuthenticationTicket authTicket = FormsAuthentication.Decrypt(authCooke.Value);
            if (authTicket != null)
            {
                var identity = new GenericIdentity(authTicket.Name, "Forms");
                var principal = new CustomPrincipal(identity);

                string userData = ((FormsIdentity)(Context.User.Identity)).Ticket.UserData;
                var serializer = new JavaScriptSerializer();
                principal.User = (User)serializer.Deserialize(userData, typeof(User));

                Context.User = principal;
                Thread.CurrentPrincipal = principal;
            }
        }
    }

Could anybody explain to me what I am doing wrong and how updating version of .NET without changing it on application pool could affect the site?

A: Similar problem on my site. Authentication fails only with IE10 but works fine in Firefox and IE8, IE9.
To solve the problem I added the parameter cookieless="UseCookies" in web.config
<authentication mode="Forms" >
  <forms loginUrl="~/Account/LogOn" timeout="2880" cookieless="UseCookies" />
</authentication>

A: Could it be due to your mis-spelling in your code (HttpCookie authCooke).  Should it be "authCookie"?


text:
Q: Bind residuals to input dataset with missing values I am looking for a method to bind lm residuals to an input dataset. The method must add NA for missing residuals and the residuals should correspond to the proper row.
Sample data:
N <- 100
Nrep <- 5
X <- runif(N, 0, 10)
Y <- 6 + 2*X + rnorm(N, 0, 1)
X[ sample(which(Y < 15), Nrep) ] <- NA
df <- data.frame(X,Y)

residuals(lm(Y ~ X,data=df,na.action=na.omit))

Residuals should be bound to df.

A: Using merge, or join.
N <- 100
Nrep <- 5
X <- runif(N, 0, 10)
Y <- 6 + 2*X + rnorm(N, 0, 1)
X[ sample(which(Y < 15), Nrep) ] <- NA
df <- data.frame(X,Y)

df$id <- rownames(df)

res <- residuals(lm(Y ~ X,data=df,na.action=na.omit))
tmp <- data.frame(res=res)
tmp$id <- names(res)

merge(df,tmp,by="id",sort=FALSE,all.x=TRUE)

If you need to maintain the order. Use join() from the plyr package:
library(plyr)
join(df,tmp)

A: Simply change the na.action to na.exclude:
residuals(lm(Y ~ X, data = df, na.action = na.exclude))

na.omit and na.exclude both do casewise deletion with respect to both predictors and criterions. They only differ in that extractor functions like residuals() or fitted() will pad their output with NAs for the omitted cases with na.exclude, thus having an output of the same length as the input variables.
(this is the best solution found here)

A: This maybe could be solution, but, first, you do not need c() in data.frame
df <- data.frame(X,Y)
df$Res[!is.na(X)]<-residuals(lm(Y ~ X,data=df,na.action=na.omit))

A: "[<-"(df, !is.na(df$X), "res", residuals(lm(Y ~ X,data=df,na.action=na.omit)))

will do the trick.

A: N <- 100
Nrep <- 5
X <- runif(N, 0, 10)
Y <- 6 + 2*X + rnorm(N, 0, 1)
X[ sample(which(Y < 15), Nrep) ] <- NA
df <- data.frame(X,Y)

R.all=as.numeric(rep(NA,length(X)))  # numeric vector with missing values
res=residuals(lm(Y ~ X,data=df,na.action=na.omit))
i=as.numeric(names(res)) # vector locations of non-missing residuals
R.all[i]=res;R.all     # assign residuals to their correct positions.


text:
Q: GWT: sharing POJOs with MySQL I have a client who wants to use GWT with MySQL. What's the best way to share POJOs between the GWT front-end and the SQL back-end? Is Gilead up to the task? Is there something better?

A: You can check RequestFactory . Here is the discussion about them ; Gilead vs RequestFactory


text:
Q: Pass an ID To Twitter Bootstrap Model I am trying to pass an id to a twitter bootstrap model for a delete confirmation (basic CRUD page) and for the life of me I can't get this working.  Looked at several examples still unable to get to work.  I need to get the data-id to pass to the model and append the href link so that for example they confirm it takes them to the appropiate page (eg: delete.php?id=5)  Any ideas would be greatly appreciated.  Heres my code:
The link:

The Model:

<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Are You Sure?

Are you sure you want to delete this product?  This action can not be reversed.

Remember if you want to just hide the product from your store you can mark it as inactive.

<button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
Delete Product

The JavaScript:

A: in your code

change it to
<a data-href="delete.php?id=<?php=productId?>" data-toggle="modal" class="open-dialog btn btn-mini btn-danger" data-id="'.$row["id"].'">

so, it will be automatically pass to your javascript... and you won't need to pass it in script...
change your script to this
$(document).on("click", ".open-dialog", function () {
 var productId = $(this).data('id');
 console.log(productId);
});

A: Look like your code has misprint.
$("#clink").attr("href", "delete.php?idd=" + productId);
                                  -----^

Should be
$("#clink").attr("href", "delete.php?id=" + productId);

At least http://jsfiddle.net/egX3W/ shows that you href changes as you want.


text:
Q: Formula labels in TensorBoard Is it possible to write the scalar labels in TensorBoard as mathematical expressions? (e.g. with Tex, Latex etc.).
Something like
tf.summary.scalar('$f^2$', ...)

I want to make the output labels look nice on TensorBoard.


text:
Q: proguard in android - should i obfuscate gson POJOs I am assuming i cannot obfuscate gson POJOs.  if i do then gson cannot do the object mapping and deserialize json to POJO, correct ? Is there any way to obfuscate POJOs then ? Also please let me know if my thoughts are correct that obfuscating POJOs should not be done and if so what would be the proguard command to keep all pojos.

A: 5 months too late but I ran into this issue and this was the first Google result.
My solution was just to keep all POJOs unobfuscated, the easiest way being to keep all classes that are in a "model" folder
-keep class com.example.myapp.**.model.** {*; }

This will keep all POJOs that are in any model package in your app.


text:
Q: Replacing Specific Row with the data from another table that matches specific condition I wrote a query in Access that produces the following result.
qryCalculateXY
EquipmentID, ZoneNumber, RowNumber, ColumnNumber, XCoordinate, YCoordinate, ComponentID
1, 0, 1, 1, 500, 600, 1
1, 0, 1, 20, 500, 1200, 1
.
.
.
.

This query quickly calculates 1000+ XY co-ordinates of PrimaryComponent based on adding very few rows (maximum 30) in the table. And I am very happy with this so far.
However, there are very few locations (maximum 20) where, I may have ComponentID changed. For that I've created a table as below that lists out all exceptions.
tblException
EquipmentID, ZoneNumber, RowNumber, ColumnNumber, ComponentID
1, 0, 1, 20, 2

I want to generate another query which would list out all rows from qryCalculateXY as it is where it does not find corresponding values of EquipmentID, ZoneNumber, RowNumber, ColumnNumber from table tblException. And replace the value of ComponentID from tblException where values of these four columns match in the table tblException.
The resulting query should look like this -
qryCalculateXYFinal
EquipmentID, ZoneNumber, RowNumber, ColumnNumber, XCoordinate, YCoordinate, ComponentID
1, 0, 1, 1, 500, 600, 1
1, 0, 1, 20, 500, 1200, 2
.
.
.
.

This would save lots of time from my side not to convert query into a table and then change specific values.
How can I achieve this?
Thanks,
Nimish
I tried the left joint but to no avail.

A: assuming:
'table xy
----------------------------------------------------------------------------------------------------------------------------------------------------
|    EquipmentID     |     ZoneNumber     |     RowNumber      |    ColumnNumber    |    XCoordinate     |    YCoordinate     |    ComponentID     |
----------------------------------------------------------------------------------------------------------------------------------------------------
|                  1 |                  0 |                  1 |                  1 |                500 |                600 |                  1 |
----------------------------------------------------------------------------------------------------------------------------------------------------
|                  1 |                  0 |                  1 |                 20 |                500 |               1200 |                  1 |
----------------------------------------------------------------------------------------------------------------------------------------------------

' saved query qryCalculateXY:

SELECT tableXY.*
FROM tableXY;

QryCalculateXYFinal:

'qryCalculateXYFinal

SELECT qryCalculateXY.EquipmentID, qryCalculateXY.ZoneNumber, qryCalculateXY.RowNumber, qryCalculateXY.ColumnNumber, qryCalculateXY.XCoordinate, qryCalculateXY.YCoordinate, DLookUp("ComponentID","tblException","EquipmentID = " & [EquipmentID] & " AND ZoneNumber = " & [ZoneNumber] & " AND RowNumber = " & [RowNumber] & " AND ColumnNumber = " & [ColumnNumber]) AS ExceptionComponentID, IIf([ExceptionComponentID],[ExceptionComponentID],[qryCalculateXY].[ComponentID]) AS ComponentID, GetReplacementComponentID([ComponentID],[EquipmentID],[ZoneNumber],[RowNumber],[ColumnNumber]) AS C2
FROM qryCalculateXY;

'ExceptionComponentID

ExceptionComponentID: DLookUp("ComponentID","tblException","EquipmentID = " & [EquipmentID] & " AND ZoneNumber = " & [ZoneNumber] & " AND RowNumber = " & [RowNumber] & " AND ColumnNumber = " & [ColumnNumber])

'The fixed ComponentID

ComponentID: IIf([ExceptionComponentID],[ExceptionComponentID],[qryCalculateXY].[ComponentID])

'C2

C2: GetReplacementComponentID([ComponentID],[EquipmentID],[ZoneNumber],[RowNumber],[ColumnNumber])

'GetReplacementComponentID in code module

Public Function GetReplacementComponentID(ComponentID As Long, EquipmentID As Long, Zonenumber As Long, RowNumber As Long, ColumnNumber As Long)
Dim returnvalue As Long
returnvalue = Nz(DLookup("ComponentID", "tblException", "(EquipmentID = " & EquipmentID & ") AND (ZoneNumber = " & Zonenumber & ") AND (RowNumber = " & RowNumber & ") AND (ColumnNumber = " & ColumnNumber & ")"), ComponentID)

 GetReplacementComponentID = returnvalue
End Function

as shown above you can look up the appropriate ComponentID in the query.  ExceptionComponentID is just there to make reading easier you can replace it with its expression everywhere it occurs or better yet abstract even more of the Calculations to a public function like in c2.  You can cut, paste, import the tables and sql into your version of Access.  You can also replace the vba functions with a subquery which is not shown.

A: Use Nz in a simple query with a left join:
Select
    qryCalculateXY.EquipmentID,
    qryCalculateXY.ZoneNumber,
    qryCalculateXY.RowNumber,
    qryCalculateXY.ColumnNumber,
    qryCalculateXY.XCoordinate,
    qryCalculateXY.YCoordinate,
    Val(Nz([tblException].[ComponentID],[qryCalculateXY].[ComponentID])) As ComponentID
From
    qryCalculateXY
Left Join
    tblException On
        (qryCalculateXY.ColumnNumber = tblException.ColumnNumber
        (qryCalculateXY.RowNumber = tblException.RowNumber) AND
        (qryCalculateXY.ZoneNumber = tblException.ZoneNumber) AN
        (qryCalculateXY.EquipmentID = tblException.EquipmentID);

Output:


text:
Q: Ошибка при установке kivy При установке kivy через pip - появляется такая ошибка.
error: command 'clang' failed with exit status 1

A: Итак: решение найдено.
ось - macOS High Sierra
всему виной оказалась ошибка описанная здесь https://github.com/kivy/kivy/issues/5468 - решение проблемы внутри.


text:
Q: Prove that every rational solution of $x^n=c$ is integer
Prove that every rational solution of $x^n=c$ is integer
$c,n\in \mathbb N$

My start:
Let $x=u/q\quad \text{ such that } \gcd(u,q)=1$
$$\left( \frac u q \right)^n=c $$
I realy don't understand what should I prove here, since $c\in \mathbb N$ so $q$ must be equale to $\pm 1$, I can't find a formal way to show that.

A: You have $u^n=cq^n$, thus $q$ divides $u^n$,thus a prime $p$ which divides $q$ divides $u$. This implies $p=1$ since $u$ and $q$ are relatively prime, henceforth $q=1$.

A: If $c=1$, then $u^n=cq^n$ implies $u^n=q^n$ and so $u=\pm q$ and $q=\pm\gcd(u,q)=1$.
If $c>1$, let $p$ be a prime divisor of $c$. Then $u^n=cq^n$ implies that the exponent of $p$ in $c$ is a multiple of $n$ and so $c$ is an $n$-th power, $c=d^n$. Then $u=\pm dq$ and $q=\pm\gcd(u,q)=1$.

A: Suppose there exists a rational solution $x$ which is not an integer such that $x^n=c$, let $x=\frac{p}{q}$, where $p\in Z$ with $p\neq 0$, and $q\in N$ with $q\geq 2$. Then we may let $\gcd(p,q)=1$ and then
$$c=\left(\frac{p}{q}\right)^n=\frac{p^n}{q^n}\quad\mbox{or}\quad
  p^n=q^nc,$$
whcih follows that $q^n$ divides $p^n$, thus $2\leq q^n=\gcd(p^n,q^n)=[\gcd(p,q)]^n=1^n=1$. This gives a contradiction.


text:
Q: How do I get around int value resetting after changing method I set an int value in my method GetDays, I then want to use this value inside GetRiskAssement() but it changes to default 0 as soon as I return back to this method.
I want to set intDays and for it to stay the same until I run the GetDays method again.
public class RiskA
{
    int accountId;
    static int intDays;
    bool stop;
    List<int> DateVehicleList = new List<int>();

    public List<DisplayableRiskAssement> DisplayableRiskAssement { get; private set; }

    public RiskAssement()
    {
        accountId = 461;
        DisplayableRiskAssement = GetRiskAssement();
    }

    List<DisplayableRiskAssement> GetRiskAssement()
    {
       //Additional code here than runs through a load of records
        if(riskAssement.InUK == false)
        {
            GetVehiclesNotInUK(riskAssement.VehicleID);
            riskAssement.IntDaysSinceUK = intDays;
        }
        return riskAssesments;
    }

    protected void GetVehiclesNotInUK(int VehicleID)
    {
        //Code here that creates DateVehicleList
        GetDays(DateVehicleList, intDays);
    }

    private static int GetDays(List<int> DateVehicleList, int intDays)
    {
        using (aEntities db = new aEntities())
        {
            foreach (var item in DateVehicleList)
            {
                var qryDate = (from a in db.ev
                               where a.evID == item
                               select a.sysdatetime).Single();

                string strDate = qryDate.ToString();
                DateTime oldDate = DateTime.Parse(strDate);

                TimeSpan t = DateTime.Now - oldDate;
                double doubleDays = t.TotalDays;
                intDays = Convert.ToInt32(doubleDays);
            }
        }
        DateVehicleList.Clear();
        return intDays;
    }
}

A: Your method GetDays should operate on class variables, not on parameters that you are passing.
If you expect the method to use class variables, just remove parameters from this method:
private static int GetDays(){...}

A: In C#, arguments can be passed to parameters either by value or by reference. For your GetDays method you have passed DateVehicleList by reference and intDays by value. Your previous intDays value from class object will not be updated unless you assign the returned value in it.
protected void GetVehiclesNotInUK(int VehicleID)
{
    //Code here that creates DateVehicleList
    intDays = GetDays(DateVehicleList, intDays);
}

not it will work as of you intended, cheers!

A: int is of Primitive type so by default it is 0. So when your object is initialized, your constructor calls GetRiskAssement() method and that method used intDay that's not still set in your GetDays() method that's why it returns 0 to you.
You can use intDay as your class attribute and make getter and setter of it, and your getDays() method works on your class attributes rather than parameters.
private static int intDay;
public static int getIntDay()
{
    return intDay;
}
public static void setIntDay(int intDay)
{
    this.intDay = intDay;
}

and your function should looks like.
private static int GetDays()
{
    //your code goes here
}

hope this helps you.


text:
Q: Why does the assigned data do not change to the assigned value in the template immediately? I have a smarty project:
The php file is like this:
<?php

require($_SERVER['DOCUMENT_ROOT'] . '/smartyHeader.php');

$smarty->assign('foo', 'Foo');

if( isset($_GET['username'])) {

    $username = $_GET['username'];
    $smarty->assign('bar', $username);
}

$smarty->display('php/test.tpl');

In its corresponding template:
<form method="get" action="{$smarty.server.PHP_SELF}">
    <input type="text" name="username"/>
    <input type="submit">
</form>

{if isset($bar)}
    bar {$bar}
{/if}

You see I use a form to submit the username.
However, it seems that $smarty->assign('bar', $username); is not executed in the php file. The username field is filled before form submission.

EDIT-01
my snapshot:

I am not sure whether the send username is assigned in the php file to bar, but the 12ewf is my set last time. this time username 123 submit, the template do not change immediately.
the Array is my print_r $_GET test in :
if( isset($_GET['username'])) {

    print_r($_GET);
    ...

EDIT-02
See this:
if( isset($_GET['username'])) {

    print_r($_GET);

    echo $_GET['username'];

    $username = $_GET['username'];

    $smarty->assign('bar', $username);

}

the result in the browser:

After several seconds when I refresh the page the value will change to the sent value, whether this is caused by the cache?


text:
Q: Default Credentials in Google App Engine: Invalid Credentials error I followed the tutorial on https://developers.google.com/identity/protocols/application-default-credentials to use the default credentials in my application on the google app engine. However, when running the app locally, I get a 401 error (invalid Credentials)

com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
  OK {   "code" : 401,   "errors" : [ {
      "domain" : "global",
      "location" : "Authorization",
      "locationType" : "header",
      "message" : "Invalid Credentials",
      "reason" : "authError"   } ],   "message" : "Invalid Credentials" }

This is the code I use, included the parts of tutorial:
List<String> scopes = Lists.newArrayList("https://www.googleapis.com/auth/youtube.force-ssl");
        try{
            // Authorize the request.
            GoogleCredential credential = GoogleCredential.getApplicationDefault();
            if (credential.createScopedRequired()) {
                credential = credential.createScoped(scopes);
            }
            // This object is used to make YouTube Data API requests.
            youtube = new YouTube.Builder(Auth.HTTP_TRANSPORT, Auth.JSON_FACTORY, credential)
                    .setApplicationName("youtube-cmdline-captions-sample").build();
        } catch (IOException e) {
            e.printStackTrace();
        }

I have the Google Cloud SDK installed, I used the shell to give permission to get access to my google account

A: There are several steps that you need to follow in order to use the application default credentials... You can follow the steps below, or have a look at this link.

*

*First things first : install google cloud storage SDK

*Make sure you can run commands from the SDK. If you do not have python installed you need to install python 2.7 or above, and also pyopenssl...

*You need to authenticate with from within the SDK by running the
gcloud auth activate-service-account [Service account email] --key-fil
e [.p12 file] . When you run this you should get a message telling you that you have activated your service account

*You need to set environment variables from the SDK by setting
GOOGLE_APPLICATION_CREDENTIALS to the JSON path of the secret
CLOUDSDK_PYTHON_SITEPACKAGES to 1, and also setting the project

Commands to configure system variables...

set GOOGLE_APPLICATION_CREDENTIALS "secret.json path"
set CLOUDSDK_PYTHON_SITEPACKAGES 1
gcloud config set project "your project name"

After you authenticate, and authorize yourself, you can then start using the applications default credentials, given that you have setup your environment properly.


text:
Q: How to properly run jumbo react Jumbo React - React Redux Material BootStrap Admin Template? I am running linux and I am trying to run the demo version of the template by cd to the the source directory and then running yarn start which is the according to the documentation.
I am getting the following errors please help!
ERROR in ./src/containers/App.js
Module not found: Error: Can't resolve 'material-ui-pickers/utils/MuiPickersUtilsProvider' in '/home/dd/Desktop/source/src/containers'
 @ ./src/containers/App.js 39:31-91
 @ ./src/MainApp.js
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:3000 webpack/hot/dev-server babel-polyfill webpack/hot/only-dev-server react-hot-loader/patch ./index.js

ERROR in ./src/containers/App.js
Module not found: Error: Can't resolve 'material-ui-pickers/utils/moment-utils' in '/home/dd/Desktop/source/src/containers'
 @ ./src/containers/App.js 35:19-68
 @ ./src/MainApp.js
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:3000 webpack/hot/dev-server babel-polyfill webpack/hot/only-dev-server react-hot-loader/patch ./index.js

ERROR in ./src/util/RTL.js
Module not found: Error: Can't resolve 'react-jss/lib/JssProvider' in '/home/dd/Desktop/source/src/util'
 @ ./src/util/RTL.js 17:19-55
 @ ./src/containers/App.js
 @ ./src/MainApp.js
 @ ./src/index.js
 @ multi (webpack)-dev-server/client?http://localhost:3000 webpack/hot/dev-server babel-polyfill webpack/hot/only-dev-server react-hot-loader/patch ./index.js

A: You should first try yarn install to install the related dependencies and then only run yarn start.


text:
Q: SqlBulkCopy - The given ColumnName does not match up with any column in the source or destination I'm trying to use SqlBulkCopy to copy data into an SQL database table however it is (wrongly) saying that the columns don't match. They do match. If I use a breakpoint to see the names of the columns being mapped, they're correct. The error message shows the name of the column, and it is correct.
This is my method. I have an identical method that does work and the only difference is where it gets the column names from. The strings containing the column names, however, are EXACTLY identical.
    public static bool ManualMapImport(DataTable dataTable, string table)
    {
        if(dataTable != null)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlBulkCopy import = new SqlBulkCopy(connection);
            import.DestinationTableName = "[" + table + "]";
            foreach (string s in Global.SelectedColumns)
            {
            /* The s string variable here is the EXACT same as
               the c.ToString() in the other method below */

                if (ColumnExists(table, s))
                    import.ColumnMappings.Add(s, s);
                else
                    return false;
            }

            connection.Open();
            import.WriteToServer(dataTable); //Error happens on this line
            connection.Close();

            return true;
        }
        else
        {
            return false;
        }
    }

This is the almost identical, working method:
    public static bool AutoMapImport(DataTable dataTable, string table)
    {
        if (dataTable != null)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlBulkCopy import = new SqlBulkCopy(connection);
            import.DestinationTableName = "[" + table + "]";
            foreach (DataColumn c in dataTable.Columns)
            {
                if (ColumnExists(table, c.ToString()))
                    import.ColumnMappings.Add(c.ToString(), c.ToString());
                else
                    return false;
            }

            connection.Open();
            import.WriteToServer(dataTable);
            connection.Close();

            return true;
        }
        else
        {
            return false;
        }
    }

If it helps, the column names are: ACT_Code, ACT_Paid, ACT_Name, ACT_Terminal_Code, ACT_TCustom1, ACT_TCustom2. These are exactly the same in the database itself. I'm aware that SqlBulkCopy mappings are case sensitive, and the column names are indeed correct.
This is the error message:

An unhandled exception of type 'System.InvalidOperationException'
  occurred in System.Data.dll
Additional information: The given ColumnName 'ACT_Code' does not match
  up with any column in data source.

Hopefully I'm just missing something obvious here, but I am well and truly lost.
Many thanks.

EDIT: For anyone happening to have the same problem as me, here's how
  I fixed it.
Instead of having the ManualMapImport() method be a near-clone of
  AutoMapImport(), I had it loop through the columns of the datatable
  and change the names, then called AutoMapImport() with the amended
  datatable, eliminating the need to try and map with plain strings at
  all.

A: According to MSDN (here), the DataColumn.ToString() method returns "The Expression value, if the property is set; otherwise, the ColumnName property.".
I've always found the ToString() method to be wonky anyway (can change based on current state/conditions), so I'd recommend using the ColumnName property instead, as that's what you are actually trying to get out of ToString().

OK, failing that, then I'd have to guess that this is a problem with case-sensitivity in the names of the columns in the source datatable, as SQLBulkCopy is very case-sensitive even if the SQL DB is not.  To address this, I would say that when you check to see if that column exists, then you should return/use the actual string from the datatable's column list itself, rather than using whatever string was passed in.  This should be able to fix up any case or accent differences that your ColumnsExist routine might be ignoring.

A: I had the same problem... The message might seem a bit misleading, as it suggests you didn't perform the correct mapping.
To find the root of the problem I have decided to go step by step in adding table columns and calling the WriteToServer method.
Assuming you have a valid column mapping, you will have to ensure the following between the source DataTable and the destination table:

*

*The column types and lengths (!) do match

*You have provided a valid value for each non-empty (NOT NULL) destination column

If you don't control your identity column values and would like the SQL Server do this job for you, please make sure not to specify the SqlBulkCopyOptions.KeepIdentity option. In this case you don't add the identity column to your source either.
This should be all for your bulk insert to work. Hope it helps.


text:
Q: Enumerables in Powershell versus pipes I am so confused. I can't understand why a foreach in Powershell behaves so differently than C#.
This simple code produces no output:
@{a=1; b=2} | %{ $_.key }

An approximation of this I did in Linqpad using C# gives the output I'd expect:
var ht = new Hashtable();
ht["a"] = 1;
ht["b"] = 2;

foreach (DictionaryEntry kvp in ht)
{
    kvp.Key.Dump();
}

// output

a
b

If I enumerate the Keys member of the hashtable, I can do what I need. But I don't understand why enumerating the hashtable itself doesn't return the key-value pairs. In fact it seems to return the object itself:
>     @{a=1; b=2} | %{ $_.gettype() }

IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Hashtable                                System.Object

What's Powershell doing here?

A: The PowerShell pipeline will "unroll" arrays and collections (one level), but not hash tables.  If you want to enumerate the key-value pairs of a hashtable in PowerShell, call the .getenumerator() method:
$ht = @{a=1;b=2}
$ht.GetEnumerator()

Name                           Value
----                           -----
a                              1
b                              2


text:
Q: What does the ?hash=item URL Param In eBay Sold URLS Mean? Example of one ebay url:
https://www.ebay.com/itm/313606425313?hash=item4904664ae1:g:voUAAOSwP9BhH1Fj&var=612446123827
By the time you're reading this, the link may be dead.
But that's not the point, the point is what is the meaning of the ?hash=item4904664ae1:g:voUAAOSwP9BhH1Fj part of the url?
I understand the 313606425313 is the eBay itemId and if it's a variation size or color that is what &var=612446123827 is for.
Does anybody know what the ?hash=item part means?


text:
Q: Counting hours from a valid date I have a small problem because I do not always understand how to use the lessons of the day, for example, I want the time from the list to have the day time recalculated from that date, but if I have a new time, that conversion counts from the new time. It works fine for me if I only have one time, but if I have two times, foreach the loop calculates me both times for the day.
This is my code:
  public TimeSpan GetHoursForDay(DateTime day) {
         TimeSpan time = TimeSpan.Zero;

         foreach (var times in shouldWorkTime)
                {
                    if (times.Valid_from > day) //here's the real problem for me, do i want the hours to count from that date, for example: for 1.1.2020 it doesn't need to take hours from 1.12.2019
                        continue;
                    if (day.DayOfWeek == DayOfWeek.Monday)
                    {
                        time += times.ShouldWorkMonday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Tuesday)
                    {
                        time += times.ShouldWorkTuesday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Wednesday)
                    {
                        time += times.ShouldWorkWednesday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Thursday)
                    {
                        time += times.ShouldWorkThursday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Friday)
                    {
                        time += times.ShouldWorkFriday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Saturday)
                    {
                        time += times.ShouldWorkSaturday;
                    }
                    if (day.DayOfWeek == DayOfWeek.Sunday)
                    {
                        time += times.ShouldWorkSunday;
                    }
                }
                return time;
            }
    }

These are the values I get in the list:
var shouldWorkTime = new List<ShouldWorkTime>
            {
             new ShouldWorkTime
             {
            Valid_from = new DateTime(2019, 12, 01, 0, 0, 0),
            ShouldWorkMonday = new TimeSpan(8,0,0),
            ShouldWorkTuesday= new TimeSpan(7,0,0),
            ShouldWorkWednesday= new TimeSpan(6,0,0),
            ShouldWorkThursday= new TimeSpan(5,0,0),
            ShouldWorkFriday= new TimeSpan(8,0,0),
            ShouldWorkSaturday = new TimeSpan(0,0,0),
            ShouldWorkSunday = new TimeSpan(0,0,0)
            },
            new ShouldWorkTime
            {
            Valid_from = new DateTime(2020, 01, 01, 0, 0, 0),
            ShouldWorkMonday = new TimeSpan(4,0,0),
            ShouldWorkTuesday= new TimeSpan(3,0,0),
            ShouldWorkWednesday= new TimeSpan(6,0,0),
            ShouldWorkThursday= new TimeSpan(5,0,0),
            ShouldWorkFriday= new TimeSpan(9,0,0),
            ShouldWorkSaturday = new TimeSpan(0,0,0),
            ShouldWorkSunday = new TimeSpan(0,0,0)
                }
            };

for the day value, I always get for the current day from the calendar, so I want to be counted in this case for the days of 1.1.2020 values for the days that fall in the second count, and until then the values that fall in the first count.
so i need to return how many hours for a particular day a worker needs to make, but valid from the last date from (Valid_From).
How can I correct this? thank you all very much for your help
eg:

input 1.1.2020 output = 6,0,0;
input 1.12.2019 output = 0,0,0;

A: Here is a little modification of the Data structure.
Instead of a brunch of property The TimeSpan will be mapped to the DayOfWeek using a Dictionary. This will remove the need for a switch-case or a lot of If.
Using DayOfWeek as dictionary key ensure that only one TimeSpan is defined for a day.
public class WorkingTimeScheldure
{
    public DateTime Start { get; set; }
    public DateTime End { get; set; }
    public Dictionary<DayOfWeek, TimeSpan> Scheldure { get; set; }
}

That way I can ask for the TimeSpan of a day using : Scheldure[test.DayOfWeek]
Note the addition of an End property. It may be usefull to select the right thing.
eg: 30/01/2020 is superior to 01/12/2019 and 01/01/2020..
So in order to take the most recent, I assume the list in ordered on Start date and pick the last one: .Last(x => x.Start <= day).
Online Demo
public class Program
{
    static List<ShouldWork> WorkTimeScheldure;
    public static void Main()
    {
        WorkTimeScheldure = new List<ShouldWork>
        {
            new ShouldWork
            {
                Start = new DateTime(2019, 12, 01, 0, 0, 0),
                Scheldure= new Dictionary<DayOfWeek, TimeSpan>()
                {
                    {(DayOfWeek)0,  new TimeSpan(0,0,0)},
                    {(DayOfWeek)1,  new TimeSpan(8,0,0)},
                    {(DayOfWeek)2,  new TimeSpan(7,0,0)},
                    {(DayOfWeek)3,  new TimeSpan(6,0,0)},
                    {(DayOfWeek)4,  new TimeSpan(5,0,0)},
                    {(DayOfWeek)5,  new TimeSpan(8,0,0)},
                    {(DayOfWeek)6,  new TimeSpan(0,0,0)}
                }
            },
            new ShouldWork
            {
                Start = new DateTime(2020, 01, 01, 0, 0, 0),
                Scheldure = new Dictionary<DayOfWeek, TimeSpan>()
                {
                    {(DayOfWeek)0,  new TimeSpan(0,0,0)},
                    {(DayOfWeek)1,  new TimeSpan(4,0,0)},
                    {(DayOfWeek)2,  new TimeSpan(3,0,0)},
                    {(DayOfWeek)3,  new TimeSpan(6,0,0)},
                    {(DayOfWeek)4,  new TimeSpan(5,0,0)},
                    {(DayOfWeek)5,  new TimeSpan(9,0,0)},
                    {(DayOfWeek)6,  new TimeSpan(0,0,0)}
                }
            }
        };

        var testValues = new[] {

            new DateTime(2019, 12, 01, 0, 0, 0),
            new DateTime(2019, 12, 02, 0, 0, 0),
            new DateTime(2019, 12, 03, 0, 0, 0),
            new DateTime(2019, 12, 04, 0, 0, 0),
            new DateTime(2019, 12, 05, 0, 0, 0),
            new DateTime(2019, 12, 06, 0, 0, 0),
            new DateTime(2019, 12, 07, 0, 0, 0),
            new DateTime(2019, 12, 08, 0, 0, 0),

            new DateTime(2020, 01, 01, 0, 0, 0),
            new DateTime(2020, 01, 02, 0, 0, 0),
            new DateTime(2020, 01, 03, 0, 0, 0),
            new DateTime(2020, 01, 05, 0, 0, 0),
            new DateTime(2020, 01, 05, 0, 0, 0),
            new DateTime(2020, 01, 06, 0, 0, 0),
            new DateTime(2020, 01, 07, 0, 0, 0),
            new DateTime(2020, 01, 08, 0, 0, 0),
        };

        foreach (var test in testValues) {

            // Perhaps there is many possible, so I took the Last.
            var workingTime = WorkTimeScheldure.Last(x => x.Start <= day);
            //Please handle the case where there is no matching scheludre for this date.

            var houtToWork = workingTime.Scheldure[day.DayOfWeek].Hours;

            Console.WriteLine(
                $"{day.ToShortDateString()} , it's a {day.DayOfWeek}" +
                $" I have to work {houtToWork} Hour{(houtToWork>1?"s":"")}!"
            );
        }
    }
}

Result :
12/01/2019 , it's a Sunday I have to work 0 Hour!
12/02/2019 , it's a Monday I have to work 8 Hours!
12/03/2019 , it's a Tuesday I have to work 7 Hours!
12/04/2019 , it's a Wednesday I have to work 6 Hours!
12/05/2019 , it's a Thursday I have to work 5 Hours!
12/06/2019 , it's a Friday I have to work 8 Hours!
12/07/2019 , it's a Saturday I have to work 0 Hour!
12/08/2019 , it's a Sunday I have to work 0 Hour!

01/01/2020 , it's a Wednesday I have to work 6 Hours!
01/02/2020 , it's a Thursday I have to work 5 Hours!
01/03/2020 , it's a Friday I have to work 9 Hours!
01/04/2020 , it's a Saturday I have to work 0 Hour!
01/05/2020 , it's a Sunday I have to work 0 Hour!
01/06/2020 , it's a Monday I have to work 4 Hours!
01/07/2020 , it's a Tuesday I have to work 3 Hours!
01/08/2020 , it's a Wednesday I have to work 6 Hours!

A: The test times.Valid_from > day is false for all element in shouldWorkTime if the value of day is big enough. That why time can be incremented multiple time.
If you want to increment only once and on the first/last acceptable value of Valid_from, you should ensure that shouldWorkTime is sorted in increasing/decreasing order and ensure that the increment is done only once.
In fact you didn't need increment but just return the corresponding TimeSpan:
public TimeSpan GetHoursForDay(DateTime day) {
    // shouldWorkTime should have been sorted once for all at creation.
    // This code use the first acceptable Valid_from
    // By using OrderByDescending we take the last (in date) entry
    var math = shouldWorkTime
                 .Where(v => day >= v.Valid_from) // We take only valid entry
                 .OrderByDescending(v => v.Valid_from) // We sort only on valid entry
                 .FirstOrDefault(); // we take the last (in date) valid entry

    if (match == null)
        return TimeSpan.Zero;

    switch (day.DayOfWeek)
    {
        case DayOfWeek.Monday:
            return match.ShouldWorkMonday;
        case DayOfWeek.Tuesday:
            return match.ShouldWorkTuesday;
        case DayOfWeek.Wednesday:
            return match.ShouldWorkWednesday;
        case DayOfWeek.Thursday:
            return match.ShouldWorkThursday;
        case DayOfWeek.Friday:
            return match.ShouldWorkFriday;
        case DayOfWeek.Saturday:
            return match.ShouldWorkSaturday;
        case DayOfWeek.Sunday:
            return match.ShouldWorkSunday;
    }
}

Edit:
To avoid code duplication, the ShouldWorkTime class may provide a GetWorkTimeForDayOfWeek:
public TimeSpan GetWorkTimeForDayOfWeek(DayOfWeek dayOfWeek) {
  ...
}

And instead of storing seven values in seven fields, you may take a look to collections. I will choose a Dictionary<DayOfWeek, TimeSpan>.


text:
Q: How to write multiple lines in a label I have a XIB file of type View XIB. In it I have a View controller, and in the View controller I have a label.
I have long text that I want to break, but it doesn't - it gets truncated.
I tried this solution - I did it in the attribute window - but it doesn't help.

A: use this
myLabel.lineBreakMode = UILineBreakModeWordWrap;

if you are worried about backwards compatibility use this because the comand i mentioned before was introduced in iOS 6.0
myLabel.numberOfLines = 0;

A: I have been running into a similar problem.  I started out with a label, but wanted multi-lines and a UITextView worked great for this, at first.  Because I am using a third party library (MBProgressHUD) to handle stuff like progress messages and what not, I had thread problems when trying to update a UITextView and show the progress message at the same time.
So I went back to UILabel which actually didn't have thread problems.  I found a property to allow a specific number of lines of my choosing, and had to create the label big enough to display those lines.  The downfall to this approach is that I don't get the context menus like Copy, Paste, etc. but more importantly I'm not running into thread problems.  I can always embed this into a UIScrollView in the future if I so choose.

A: You could check out my category for UILabel on GitHub. https://gist.github.com/1005520
This lets you resize the height of the label to accommodate the content.

A: You could use a TextView and disable the Editable and User Interaction Enabled options in IB.

A: From the Attiribute inspector, choose LineBreaks->Word Wrap option when you have selected the lablel. Also increase the number of lines Label->Lines.

A: Try Following steps to solve issue :

*

*Drag out a UITextView.

*Double-click it to edit text, place cursor    where you want the
paragraph break.

*Option-Enter a couple of times to    create a blank line & paragraph.


text:
Q: Mongodb: update collection imediatly after aggregation I execute an aggregation that's output is 2 new field.
db.Messages.aggregate(
[
    {$match : {
        "Payload": /(([1-2]?[0-9])-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*)-([0-9]*))/}
       },...
{
    $out : "tmp_Messagess"  // create new Collection
}

by using  $out I have inserted 2 new field into new collection called tmp_Messagess. after inserted I have updated old collection with new collection:
var bulkOps = db.tmp_Messagess.find().map(function (doc) {
   return {
        "updateOne": {
            "filter": {"_id" : doc._id},
            "update": { "$set": {"BusinessCode" : doc.BusinessCode , "Domain" : doc.Domain}}
        }
   }
});

db.Messages.bulkWrite(bulkOps, { "ordered": true });

updating in this way, it's to long. because I have to run 2 heavy query. first create new collection after aggregation and next, update old collection with documents inside the new collection.
Is there any way that I can directly update main collection inside my aggregate command or I have to use old way that i mention in this post?

A: I have created two sample collections named test1 and test2 respectively.,
//this is my fist collection
db.test1.insert({"fullName": "Srikar Jammi","uname": "srikarjammi"});
db.test1.insert({"fullName": "Viswa Pradeep","uname": "vpradeep"});

//this is my second collection
db.test2.insert({"fullName": "Srikar Jammi","uname": "srikarjammi",
"age":24, "city": "Hyderabad"});
db.test2.insert({"fullName": "Viswa Pradeep","uname": "vpradeep",
"age":28, "city": "Guntur"});

for now i want to get data from collection(test2: because it has other keys which are not in test1) one by uname(which is a common key in both collections). So, you can do this.,
result = db.test2.find({}).map(function(a){return a});
//output
[
{
    "_id" : ObjectId("5a7c072742f432f35421f931"),
    "fullName" : "Srikar Jammi",
    "uname" : "srikarjammi",
    "age" : 24,
    "city" : "Hyderabad"
},
{
    "_id" : ObjectId("5a7c072b42f432f35421f932"),
    "fullName" : "Viswa Pradeep",
    "uname" : "vpradeep",
    "age" : 28,
    "city" : "Guntur"
}
]

Now the result holds the data of second collection(test2). then finally i have to update the collection with respective keys(age, city) for this.,
finalRes = result.forEach(
function (elem) {
    db.test1.update({
        "uname": elem.uname
    },
    {
            $set: {
                "age": elem.age,
                "city":elem.city
            }
        }
    )
    }
);

Finally (db.test1.find({});
) by this you find the collection one(test1) with updated keys(age, city)
Correct me if i am wrong or any solutions are much appreciated.
Thanks


text:
Q: sikuli - The windows application opened through sikuli is opened as minimized, how to solve? I have a simple sikuli script which will open a windows exe file(in below cmd "run.bat" opens a windows exe application)
App.open(r"SENINFO_V100R002C00SPC700\run.bat")

The problem i am facing is, the exe application is opened sometimes as minimized in taskbar, So next sikuli cmds which are expecting some image are failing.
How to solve this, please help

A: Try App.focus() method instead of App.open()


text:
Q: Can you expect flash/as3 player to eventually garbage collect? So I'm quite aware of flash/as3 garbage collecting causing memory leaks, and all the questions on the net.
Our software runs a swf, that loads in other swfs, videos, and images. It is expected to run a week without being restarted. generally, the player barely makes it a week without crashing from using too much memory. the swf will load in other assets based on the time of day, or if the schedule has changed. I wrote a simple resource manager so that it keeps track of what is used and what isn't, and will unload and set the unused assets to null. it does this unused check every hour, but it still seems that memory still doesn't go down after these assets are unloaded, and the memory leak continues to grow.
What I'm wondering, and can't seem to find, is can you expect flash to for SURE eventually release memory that is unused? or is there a possibility that flash may NEVER release unused memory?

A: It's really hard to find where memory-leaks come from without tools.
During game developpement I use Flash Builder Profiler, allow me to see if all my objects are destroyed when they are supposed to be.
In your case I would take a look at Adobe Scout :
http://gaming.adobe.com/technologies/scout/
Introduction to adobe scout: https://www.youtube.com/watch?v=yUHipsoGB2U
Using those tools during and after game developpement are the way to deal with memory-leaks.

A: Flash should be garbage collecting things that are no longer referenced. Is it possible that there are still references to whatever you're trying to garbage collect? You'll need to use removeEventListener() anytime that you've used addEventListener() to ensure that all of the references get deleted.
So, if you add an event listener to an object:
foo.addEventListener(Event, functionName)

Then you'll need to remove the reference when you're deleting the object:
foo.removeEventListener(Event, functionName)

A: It should be garbage collecting. Are you sure you're not inadvertently holding onto a reference to the unused objects? It's pretty easy to forget to remove an event listener, which will prevent an object from being collected when the GC runs.


text:
Q: Trigger IF Inserting Loop /Oracle I am trying to Insert new row in Table StavkaUgovora (ContractItem) and trigger/procedure should calculate (+/-) jedinicna_cena (price) and kolicina (amount) into the ukupna_cena (total_price) at table Ugovor(contract). I already have update and delete and that works fine, but for inserting statement script go into the loop and multiplicate data without stopping. Where i wrong?
CREATE TABLE StavkaUgovora (
broj_stavke INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
broj_ugovora INT not null,
kolicina NUMBER,
tip_usluge VARCHAR2(255),
jedinicna_cena NUMBER,
CONSTRAINT stavka_ugovora_broj_ugovora
    FOREIGN KEY(broj_ugovora)
    REFERENCES Ugovor(broj_ugovora));

CREATE TABLE Ugovor (
broj_ugovora INT GENERATED BY DEFAULT AS IDENTITY PRIMARY KEY,
broj_ponude INT not null,
datum_sklapanja DATE,
ukupna_cena NUMBER,
CONSTRAINT broj_ponude_ugovor
    FOREIGN KEY(broj_ponude)
    REFERENCES Ponuda(broj_ponude)
);

CREATE OR REPLACE PROCEDURE Zbir (brojUgovoraIN NUMBER, cenaSaberiIN NUMBER, cenaOduzmiIN
NUMBER)
AS suma UGOVOR.broj_ugovora%type;
pragma autonomous_transaction;
BEGIN suma:=0;
EXECUTE IMMEDIATE 'ALTER TRIGGER ZABRANAIZMENEUKUPNECENE DISABLE';
SELECT ukupna_cena INTO suma
FROM UGOVOR
WHERE broj_ugovora=brojUgovoraIN;
UPDATE UGOVOR
SET ukupna_cena=suma + cenaSaberiIN - cenaOduzmiIN
WHERE broj_ugovora=brojUgovoraIN;
EXECUTE IMMEDIATE 'ALTER TRIGGER ZABRANAIZMENEUKUPNECENE ENABLE';
COMMIT;
END;

CREATE OR REPLACE TRIGGER "SIFRAUGOVORA"
BEFORE INSERT OR UPDATE OR DELETE ON STAVKAUGOVORA
FOR EACH ROW
DECLARE
brojUgovora NUMBER;
cenaSaberi NUMBER;
cenaOduzmi NUMBER;
BEGIN
    IF INSERTING
    THEN
        BEGIN
        brojUgovora := :NEW.broj_ugovora;
        cenaSaberi  := :NEW.jedinicna_cena * :NEW.kolicina;
        cenaOduzmi  := 0;
        END;
    ELSIF UPDATING
    THEN
        BEGIN
        brojUgovora := :NEW.broj_ugovora;
        cenaSaberi  := :NEW.jedinicna_cena * :NEW.kolicina;
        cenaOduzmi  := :OLD.jedinicna_cena * :OLD.kolicina;
        END;
    ELSE
        BEGIN
        brojUgovora := :OLD.broj_ugovora;
        cenaSaberi  := 0;
        cenaOduzmi  := :OLD.jedinicna_cena * :OLD.kolicina;
        END;
    END IF;
    BEGIN
        Zbir(brojUgovora, cenaSaberi, cenaOduzmi);
    END;
END;

A: It works for me (after some modifications as you didn't post all tables/triggers involved).
Tables:
SQL> CREATE TABLE ugovor
  2  (
  3     broj_ugovora      INT PRIMARY KEY,
  4     broj_ponude       INT NOT NULL,
  5     datum_sklapanja   DATE,
  6     ukupna_cena       NUMBER
  7  );

Table created.

SQL> CREATE TABLE stavkaugovora
  2  (
  3     broj_stavke      INT PRIMARY KEY,
  4     broj_ugovora     INT NOT NULL,
  5     kolicina         NUMBER,
  6     tip_usluge       VARCHAR2 (255),
  7     jedinicna_cena   NUMBER,
  8     CONSTRAINT stavka_ugovora_broj_ugovora FOREIGN KEY (broj_ugovora)
  9        REFERENCES ugovor (broj_ugovora)
 10  );

Table created.

Procedure:
SQL> CREATE OR REPLACE PROCEDURE zbir (brojugovorain  NUMBER,
  2                                    cenasaberiin   NUMBER,
  3                                    cenaoduzmiin   NUMBER)
  4  AS
  5     suma  ugovor.broj_ugovora%TYPE;
  6     PRAGMA AUTONOMOUS_TRANSACTION;
  7  BEGIN
  8     suma := 0;
  9
 10     --EXECUTE IMMEDIATE 'ALTER TRIGGER ZABRANAIZMENEUKUPNECENE DISABLE';
 11     SELECT ukupna_cena
 12       INTO suma
 13       FROM ugovor
 14      WHERE broj_ugovora = brojugovorain;
 15
 16     UPDATE ugovor
 17        SET ukupna_cena = suma + cenasaberiin - cenaoduzmiin
 18      WHERE broj_ugovora = brojugovorain;
 19
 20     --EXECUTE IMMEDIATE 'ALTER TRIGGER ZABRANAIZMENEUKUPNECENE ENABLE';
 21     COMMIT;
 22  END;
 23  /

Procedure created.

Trigger:
SQL> CREATE OR REPLACE TRIGGER sifraugovora
  2     BEFORE INSERT OR UPDATE OR DELETE
  3     ON stavkaugovora
  4     FOR EACH ROW
  5  DECLARE
  6     brojugovora  NUMBER;
  7     cenasaberi   NUMBER;
  8     cenaoduzmi   NUMBER;
  9  BEGIN
 10     IF INSERTING
 11     THEN
 12        brojugovora := :new.broj_ugovora;
 13        cenasaberi := :new.jedinicna_cena * :new.kolicina;
 14        cenaoduzmi := 0;
 15     ELSIF UPDATING
 16     THEN
 17        brojugovora := :new.broj_ugovora;
 18        cenasaberi := :new.jedinicna_cena * :new.kolicina;
 19        cenaoduzmi := :old.jedinicna_cena * :old.kolicina;
 20     ELSE
 21        brojugovora := :old.broj_ugovora;
 22        cenasaberi := 0;
 23        cenaoduzmi := :old.jedinicna_cena * :old.kolicina;
 24     END IF;
 25
 26     DBMS_OUTPUT.put_line ('ugovor: ' || brojugovora);
 27     zbir (brojugovora, cenasaberi, cenaoduzmi);
 28  END;
 29  /

Trigger created.

Testing: insert UGOVOR first and then COMMIT because the zbir procedure is declared as an autonomous transaction so - if you don't COMMIT - it won't see newly added rows into UGOVOR table.
SQL> SET SERVEROUTPUT ON
SQL>
SQL> INSERT INTO ugovor (broj_ugovora,
  2                      broj_ponude,
  3                      datum_sklapanja,
  4                      ukupna_cena)
  5       VALUES (1,
  6               1,
  7               SYSDATE,
  8               100);

1 row created.

SQL> COMMIT;

Commit complete.

Insert stavkaugovora:
SQL> INSERT INTO stavkaugovora (broj_stavke,
  2                             broj_ugovora,
  3                             kolicina,
  4                             tip_usluge,
  5                             jedinicna_cena)
  6       VALUES (1,
  7               1,
  8               10,
  9               'A',
 10               5);
ugovor: 1

1 row created.

No errors, no "loop". The result:
SQL> SELECT * FROM ugovor;

BROJ_UGOVORA BROJ_PONUDE DATUM_SKLAPANJA     UKUPNA_CENA
------------ ----------- ------------------- -----------
           1           1 26.01.2022 08:21:21         150

SQL> SELECT * FROM stavkaugovora;

BROJ_STAVKE BROJ_UGOVORA   KOLICINA TIP_USLUGE JEDINICNA_CENA
----------- ------------ ---------- ---------- --------------
          1            1         10 A                       5

SQL>

A: Thanks for answer! Everything works fine when put in comment autonomous transaction and manualy disable trigger. I use autonomous transaction to disable trigger ZabranaIzmeneUkupneCene which prohibits direct input values into ukupna_cena on table UGOVOR. I saw in your code autonomous transaction is in comment too.
Do you have advice how to disable trigger 'ZabranaIzmeneUkupneCene' while procedure 'Zbir' is active?
CREATE OR REPLACE TRIGGER ZabranaIzmeneUkupneCene
BEFORE UPDATE OF ukupna_cena ON UGOVOR
FOR EACH ROW
BEGIN
RAISE_APPLICATION_ERROR (-20001, 'Nije moguca promena ukupne cene direktno!');
END;


text:
Q: Using Factor Variables to Facet a Histogram Beside a Scatter Plot in R Is it possible to use a factor variable to facet a histogram below or beside a scatter plot in ggplot2 in R (such that the histograms are of the x- and y-components of the data)?
The reason I ask whether this could be done with a factor variable is because faceting seems to be more general than the available packages that address this issue, where, for example with faceting, facet labels can be turned on or off, and also faceting has a more standard appearance where publication may be a concern. (Faceting also by default preserves the use of the same axes).
So far I haven't been able to get this to work because it seems like all faceted data have to be of the same number of dimensions (e.g., the scatterplot data is 2D, the histogram data are 1D).

A: I am not sure if I fully understand the question since a histogram of factor variables doesn't quite make sense to me. Also, without sample data, I will just have to use mtcars. Something like this might help. I use grid.extra in addition to ggplot2 in order to make the plots have a custom grid arrangement.
library(gridExtra)
library(ggplot2)

s_plot <- ggplot(data = mtcars, aes(x = hp, y = mpg)) + geom_point()

h1 <- ggplot(data = mtcars, aes(x = hp)) + geom_histogram()

h2 <- ggplot(data = mtcars, aes(x = mpg)) + geom_histogram()

grid.arrange(s_plot, h1, h2, layout_matrix = cbind(c(1, 1), c(2, 3)))

Note that in the layout_matrix argument in grid.arrange, I use cbind(c(1,1), c(2, 3)) because I want the first plot to be in a column all by itself and then I want the other two plots to occupy individual rows in the second column of the grid.

A: Consider the use of geom_rug.
ggplot(mtcars, aes(wt, mpg)) +
  geom_point() + geom_rug()

A: Nick and Brian,
Thanks for your help with the code. I asked around and was able to get the set-up I was looking for. Basically it goes like this, as shown below. (Hopefully this might be useful to you and others in the future, as I think this is a common type of graph):
rm(list = ls())
library(ggplot2)
library(gridExtra)

df <- data.frame(
  x = rnorm(100),
  y = rnorm(100)
)

xrange <- range(pretty(df$x))
yrange <- range(pretty(df$y))

p.left <- ggplot(df, aes(y)) +
  geom_histogram() +
  lims(x = yrange) +
  coord_flip() +
  theme_light() +
  theme(
    axis.title.x = element_blank(),
    axis.text.x = element_blank(),
    axis.ticks.x = element_blank(),
    panel.grid.major.x = element_blank(),
    plot.margin = unit(c(1, 0.05, 0.05, 1), "lines")
  )

p.blank <- ggplot() +
  theme_void() +
  theme(plot.margin = unit(rep(0, 4), "lines"))

p.main <- ggplot(df, aes(x, y)) +
  geom_point() +
  lims(x = xrange, y = yrange) +
  theme_light() +
  theme(
    axis.title = element_blank(),
    axis.text = element_blank(),
    axis.ticks = element_blank(),
    plot.margin = unit(c(1, 1, 0.05, 0.05), "lines")
  )

p.bottom <- ggplot(df, aes(x)) +
  geom_histogram() +
  lims(x = xrange) +
  theme_light() +
  theme(
    axis.title.y = element_blank(),
    axis.text.y = element_blank(),
    axis.ticks.y = element_blank(),
    panel.grid.major.y = element_blank(),
    plot.margin = unit(c(0.05, 1, 1, 0.05), "lines")
  )

lm <- matrix(1:4, nrow = 2)

grid.arrange(
  p.left, p.blank, p.main, p.bottom,
  layout_matrix = lm,
  widths = c(1, 5),
  heights = c(5, 1),
  padding = unit(0.1, "line")
)


text:
Q: WS-Federation with OWIN in ASP.NET WebForms I want to use WSFederation with OWIN in WebForms application. Even though I deny unauthorized access in web.config using the <authorization> tag on all my pages, application does not automatically redirect to IDP.
Application automatically redirects to Login page in case of CookieAuthentication MW, but does not do so in case of WS-FederationAuth MW.
Same thing works in MVC. In MVC app, on decorating my Action with [Authorize] attribute, application automatically redirects to IDP even when using WS-FederationAuth MW.
Is converting 401 to 302 doable in WebForms ?
My Sample Code:
  public void ConfigureAuth(IAppBuilder app)
    {

 app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions()
        {
            AuthenticationType = WsFederationAuthenticationDefaults.AuthenticationType

        });

        app.UseWsFederationAuthentication(
                new WsFederationAuthenticationOptions
                {
                    Wtrealm = "http://localhost:53785/",
                    MetadataAddress = metatdataaddress,
                }
            );
        }

A: In a WebForms application, you don't have any OWin attributes like [Authorize] to use that can tell the Owin Authentication Middleware to Challenge (redirect) your authentication provider. This is easy to solve though.
First, add a middleware that checks if your Identity is Authenticated, if not force a challenge redirect:
 app.Use((context, next) =>
{
    if (context.Authentication.User != null &&
        context.Authentication.User.Identity != null &&
        context.Authentication.User.Identity.IsAuthenticated)
    {
        return next();
    }
    else
    {
        // redirects to your provider
        context.Authentication.Challenge(authenticationTypes);
        return Task.FromResult(0);
    }
});
// note that it has to run in the right stage
app.UseStageMarker(PipelineStage.Authenticate)

Then, if you are using a Cookies authentication, it should be set as default. This means that "If you find a cookie, trust this as long as it's valid instead of redirecting to the WsFed provider"
app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

Now, when coming back from your WsFed provider, this cookie needs to be set. In the case of WebForms this normally has to be done manually, using a notification on your middleware. My experience is that .SignIn() is not enough to flag we're authenticated, so we actually re-establish the Authentication Ticket:
new WsFederationAuthenticationOptions
{
  Notifications = new WsFederationAuthenticationNotifications
  {
      SecurityTokenValidated = (notification) =>
      {
         var identity = notification.AuthenticationTicket.Identity;
         var defaultName = identity.FindFirst("<claim-that-identifies-user>");

         // Forcefully set a cookie so that the WsFed provider does not have to be consulted on every request as long as this cookie is valid

var ticket = new AuthenticationTicket(response.AuthenticationTicket.Identity, response.AuthenticationTicket.Properties);
            var currentUtc = new SystemClock().UtcNow;
            ticket.Properties.IssuedUtc = currentUtc;
            ticket.Properties.ExpiresUtc = currentUtc.Add(TimeSpan.FromMinutes(1));
            response.AuthenticationTicket = ticket;
            response.OwinContext.Authentication.SignIn(new AuthenticationProperties(), response.AuthenticationTicket.Identity);

         // context.Authentication.User.Identity.IsAuthenticated will now be true

         return Task.FromResult(notification);
      }
   },