text:
Q: How to connect to on-premise Oracle-db using Azure Functions? I'm trying to create an Azure Function to connect and query an on-premise Oracle-DB. I can not see that the Oracle Client or an ODBC-driver is installed on the servers to handle this.
Are there any solutions to this using JS or Python?
I have tried using the node-odbc driver, but the server is missing the Oracle client.

A: Partially answer for connecting to on-premise service like Oracle-db from Azure Functions, there is an existing SO thread How to Azure function configure for Site-to-Site Connectivity? had answered it, which you can refer to. So first, you must make sure networking access to on-premise server available.
Then, if you want to query oracle database via odbc, the oracle odbc driver must be installed on the client-side. However, the oracle odbc driver is a commerce componet, which you need to pay for getting it, and install it manually in Azure Functions. So even you want to use JS or Python to connect it, I think using Java with Oracle jdbc driver is a better solution from Azure Functions to connect Oracle DB to avoid the additional installation.
The other way I thought is to deploy a REST API app as proxy on your on-premise server to handle the query request from Azure Functions with JS or Python to help connecting Oracle DB.

A: Create and deploy your code to Azure Functions as a custom Docker container using a Linux base image. Install the Oracle client libraries in custom image. Check out my blog on the topic:
https://www.ravitella.com/azure-function-container/

A: You will need to establish a hybrid connection. see https://learn.microsoft.com/en-us/azure/app-service/app-service-hybrid-connections
Then you can refer to this thread to establish a context:
https://social.msdn.microsoft.com/Forums/en-US/2434fe10-3219-4625-bdbf-b9e96421230b/entity-framework-with-oracle-and-sql
For a nodejs solution, I would add the NPM and install it using Kudu using node-oracledb:
https://oracle.github.io/node-oracledb/doc/api.html#getstarted
// myscript.js
// This example uses Node 8's async/await syntax.
var oracledb = require('oracledb');

var mypw = ...  // set mypw to the hr schema password

async function run() {

  let connection;

  try {
    connection = await oracledb.getConnection(  {
      user          : "hr",
      password      : mypw,
      connectString : "localhost/XEPDB1"
    });

    let result = await connection.execute(
      `SELECT manager_id, department_id, department_name
       FROM departments
       WHERE manager_id = :id`,
      [103],  // bind value for :id
    );
    console.log(result.rows);

  } catch (err) {
    console.error(err);
  } finally {
    if (connection) {
      try {
        await connection.close();
      } catch (err) {
        console.error(err);
      }
    }
  }
}

run();

sample code


text:
Q: Why is sbt failing to find these jackson dependency I´m trying to add the dependencies to support java.time for jackson library. Those dependencies are:
val jacksonVersion = "2.9.7"
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-parameter-names" % jacksonVersion
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-datatype-jdk8" % jacksonVersion
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-datatype-jsr310" % jacksonVersion

as specified here
The problem is that sbt can't find them. Based on the maven webpage here, they should be available at Maven Central and JCenter so I added the resolvers to my dependencies:
resolvers += Resolver.JCenterRepository
resolvers += Resolver.DefaultMavenRepository

I know one should be enough but they don't seem to work. The urls that they resolve for are:
[warn] ==== jcenter: tried
[warn]   https://jcenter.bintray.com/com/fasterxml/jackson/module/jackson-datatype-jsr310/2.9.7/jackson-datatype-jsr310-2.9.7.pom
[warn] ==== public: tried
[warn]   https://repo1.maven.org/maven2/com/fasterxml/jackson/module/jackson-datatype-jsr310/2.9.7/jackson-datatype-jsr310-2.9.7.pom

but apparently they are not there. I don't know what I'm missing...
This is the error for the jackson-datatype-jdk8 one.
[warn]  Note: Unresolved dependencies path:
[warn]      com.fasterxml.jackson.module:jackson-datatype-jdk8:2.9.7 (/Users/overflow/MyDocuments/JaviOverflowDrive/_workspaces/RandomPlays/eurostar/pipeline/build.sbt#L15-16)
[warn]        +- default:pipeline_2.12:0.1
[warn]      com.fasterxml.jackson.module:jackson-datatype-jsr310:2.9.7 (/Users/overflow/MyDocuments/JaviOverflowDrive/_workspaces/RandomPlays/eurostar/pipeline/build.sbt#L16-17)
[warn]        +- default:pipeline_2.12:0.1
[error] sbt.librarymanagement.ResolveException: unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jdk8;2.9.7: not found
[error] unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jsr310;2.9.7: not found
[error]     at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:332)
[error]     at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:208)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:239)
[error]     at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)
[error]     at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)
[error]     at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)
[error]     at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
[error]     at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
[error]     at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
[error]     at xsbt.boot.Using$.withResource(Using.scala:10)
[error]     at xsbt.boot.Using$.apply(Using.scala:9)
[error]     at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
[error]     at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
[error]     at xsbt.boot.Locks$.apply0(Locks.scala:31)
[error]     at xsbt.boot.Locks$.apply(Locks.scala:28)
[error]     at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:238)
[error]     at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:193)
[error]     at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)
[error]     at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)
[error]     at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:45)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:93)
[error]     at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:106)
[error]     at scala.util.control.Exception$Catch.apply(Exception.scala:224)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:106)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:89)
[error]     at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)
[error]     at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:120)
[error]     at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2561)
[error]     at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error]     at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:67)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:278)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error]     at java.lang.Thread.run(Thread.java:748)
[error] sbt.librarymanagement.ResolveException: unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jdk8;2.9.7: not found
[error] unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jsr310;2.9.7: not found
[error]     at sbt.internal.librarymanagement.IvyActions$.resolveAndRetrieve(IvyActions.scala:332)
[error]     at sbt.internal.librarymanagement.IvyActions$.$anonfun$updateEither$1(IvyActions.scala:208)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.$anonfun$withModule$1(Ivy.scala:239)
[error]     at sbt.internal.librarymanagement.IvySbt.$anonfun$withIvy$1(Ivy.scala:204)
[error]     at sbt.internal.librarymanagement.IvySbt.sbt$internal$librarymanagement$IvySbt$$action$1(Ivy.scala:70)
[error]     at sbt.internal.librarymanagement.IvySbt$$anon$3.call(Ivy.scala:77)
[error]     at xsbt.boot.Locks$GlobalLock.withChannel$1(Locks.scala:95)
[error]     at xsbt.boot.Locks$GlobalLock.xsbt$boot$Locks$GlobalLock$$withChannelRetries$1(Locks.scala:80)
[error]     at xsbt.boot.Locks$GlobalLock$$anonfun$withFileLock$1.apply(Locks.scala:99)
[error]     at xsbt.boot.Using$.withResource(Using.scala:10)
[error]     at xsbt.boot.Using$.apply(Using.scala:9)
[error]     at xsbt.boot.Locks$GlobalLock.ignoringDeadlockAvoided(Locks.scala:60)
[error]     at xsbt.boot.Locks$GlobalLock.withLock(Locks.scala:50)
[error]     at xsbt.boot.Locks$.apply0(Locks.scala:31)
[error]     at xsbt.boot.Locks$.apply(Locks.scala:28)
[error]     at sbt.internal.librarymanagement.IvySbt.withDefaultLogger(Ivy.scala:77)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:199)
[error]     at sbt.internal.librarymanagement.IvySbt.withIvy(Ivy.scala:196)
[error]     at sbt.internal.librarymanagement.IvySbt$Module.withModule(Ivy.scala:238)
[error]     at sbt.internal.librarymanagement.IvyActions$.updateEither(IvyActions.scala:193)
[error]     at sbt.librarymanagement.ivy.IvyDependencyResolution.update(IvyDependencyResolution.scala:20)
[error]     at sbt.librarymanagement.DependencyResolution.update(DependencyResolution.scala:56)
[error]     at sbt.internal.LibraryManagement$.resolve$1(LibraryManagement.scala:45)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$12(LibraryManagement.scala:93)
[error]     at sbt.util.Tracked$.$anonfun$lastOutput$1(Tracked.scala:68)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$19(LibraryManagement.scala:106)
[error]     at scala.util.control.Exception$Catch.apply(Exception.scala:224)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11(LibraryManagement.scala:106)
[error]     at sbt.internal.LibraryManagement$.$anonfun$cachedUpdate$11$adapted(LibraryManagement.scala:89)
[error]     at sbt.util.Tracked$.$anonfun$inputChanged$1(Tracked.scala:149)
[error]     at sbt.internal.LibraryManagement$.cachedUpdate(LibraryManagement.scala:120)
[error]     at sbt.Classpaths$.$anonfun$updateTask$5(Defaults.scala:2561)
[error]     at scala.Function1.$anonfun$compose$1(Function1.scala:44)
[error]     at sbt.internal.util.$tilde$greater.$anonfun$$u2219$1(TypeFunctions.scala:40)
[error]     at sbt.std.Transform$$anon$4.work(System.scala:67)
[error]     at sbt.Execute.$anonfun$submit$2(Execute.scala:269)
[error]     at sbt.internal.util.ErrorHandling$.wideConvert(ErrorHandling.scala:16)
[error]     at sbt.Execute.work(Execute.scala:278)
[error]     at sbt.Execute.$anonfun$submit$1(Execute.scala:269)
[error]     at sbt.ConcurrentRestrictions$$anon$4.$anonfun$submitValid$1(ConcurrentRestrictions.scala:178)
[error]     at sbt.CompletionService$$anon$2.call(CompletionService.scala:37)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
[error]     at java.util.concurrent.FutureTask.run(FutureTask.java:266)
[error]     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
[error]     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
[error]     at java.lang.Thread.run(Thread.java:748)
[error] (update) sbt.librarymanagement.ResolveException: unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jdk8;2.9.7: not found
[error] unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jsr310;2.9.7: not found
[error] (ssExtractDependencies) sbt.librarymanagement.ResolveException: unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jdk8;2.9.7: not found
[error] unresolved dependency: com.fasterxml.jackson.module#jackson-datatype-jsr310;2.9.7: not found

Any idea why the dependencies are not there?

A: According to the link you provided, your last 2 dependencies should be with datatype :
val jacksonVersion = "2.9.7"
libraryDependencies += "com.fasterxml.jackson.module" % "jackson-module-
parameter-names" % jacksonVersion
libraryDependencies += "com.fasterxml.jackson.datatype" % "jackson-datatype-jdk8"
% jacksonVersion
libraryDependencies += "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % jacksonVersion

BTW, there is already newer version - 2.9.8 - take a look here

redpajama_set_name: RedPajamaStackExchange


text:
Q: CCXT okex5 swap contracts - Parameter posSide error I am trying to create a perpetual limit order using ccxt on okex exchange version 5.
The API is successfully placing orders(both limit and market) on spot exchange but not on perpetual exchange.
Here is what I am trying -
exchange_swap = ccxt.okex5({
'apiKey': credentials['okex']['apikey'],
'secret': credentials['okex']['secretkey'],
'password': credentials['okex']['password'],
'options': {
    'defaultType': 'swap',
      }
})
params =  {
   "test":True
}
order = exchange_swap.createLimitBuyOrder('XRP-USDT-SWAP',100,0.7)

Error message-
ccxt.base.errors.BadRequest: okex5 {"code":"1","data":[{"clOrdId":"","ordId":"","sCode":"51000","sMsg":"Parameter posSide  error ","tag":""}],"msg":""}

After searching about this error I found this in their documentation-
Error message           Http status code     Error code
Parameter {0} error.    400                  51000

Documentation link - Okex v5
P.S - I am able to place this via trading dashboard on okex but not through the API. I have enough balance to create this order.
Entire error message is this-
Traceback (most recent call last):
File "C:\Users\ishaa\Desktop\trading\Crypto Vibhor\Testing Files\ccxt_test.py", line 70, in
 <module>
  order = exchange_swap.createLimitBuyOrder('XRP-USDT-SWAP',100,0.7)
  File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line 1983, in create_limit_buy_order
return self.create_order(symbol, 'limit', 'buy', amount, price, params)
 File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\okex5.py", line 1287, in create_order
response = self.privatePostTradeOrder(self.extend(request, params))
File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line 461, in inner
return entry(_self, **inner_kwargs)
File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line
 486, in request
  return self.fetch2(path, api, method, params, headers, body)
  File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line 482, in fetch2
  return self.fetch(request['url'], request['method'], request['headers'], request['body'])
  File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line 634, in fetch
  self.handle_errors(http_status_code, http_status_text, url, method, headers, http_response, json_response, request_headers, request_body)
  File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\okex5.py", line 2230, in handle_errors
  self.throw_exactly_matched_exception(self.exceptions['exact'], errorCode, feedback)
  File "C:\Users\ishaa\Desktop\trading\tradingenv\lib\site-packages\ccxt\base\exchange.py", line 500, in throw_exactly_matched_exception
   raise exact[string](message)
   ccxt.base.errors.BadRequest: okex5 {"code":"1","data":
   [{"clOrdId":"","ordId":"","sCode":"51000","sMsg":"Parameter posSide  error
    ","tag":""}],"msg":""}

A: This could happen if you have the wrong Order Placement Mode in your OKX account settings.
Go to your OKX account > trade > perpetual swap > setting > order placement mode and set it to Long/Short mode.

A: The error message says Parameter posSide error which means you have an error in the posSide paramater you are sending in your request.
As far as I can see from your code you have only provided the ticker, size and price but are missing the posSide parameter.
Contrary to other exchanges, on Okex you can buy or sell a long or short for FUTURES and SWAP products so you need to add the posSide parameter.
It's counter intuitive and took me some time to figure out as well. Effectively you can both buy a long and buy a short at the same time. You can try it out in the Okex gui to see exactly how it works.
The docs tell us that posSide parameter is:

Another option is to disable the long/short mode (which is set by default) and use net mode instead. Using net mode means you won't need to add the posSide parameter to your request string.
Here is the link to the docs which explain how to set the position mode.
And here is a working example which includes two requeired parameters for a limit order, namely setting tdMode and posSide:
import ccxt

exchange = ccxt.okex5({
    'apiKey': '...',
    'secret': '...',
    'password': '...',
})

exchange.createLimitBuyOrder('XRP-USDT-SWAP', 100, 0.4,
                             {"tdMode": "cross", "posSide": "long"})

You can read more about setting Custom Order Params in the ccxt doc here.


text:
Q: Error 4712 al hacer truncate table Hola tengo estas tablas en mi base de datos

El problema es que necesito hacer TRUNCATE TABLE a la tabla de Empresa y posteriormente a la de Login pero cuando quiero hacer el primer TRUNCATE me sale el error 4712 ya se hace referencia a la llave foranea, pero ¿hay una manera de hacer el TRUNCATE sin necesidad de borrar los datos que tengo en la tabla TipoEmpresa?
De antemano les agradezco la ayuda.
Saludos.

A: Para usar TRUNCATE TABLE la tabla en cuestión no debe estar referenciada por una llave foránea. No importa si la tabla Empresa está vacía, no podrás utilizar el TRUNCATE en Login porque sigue teniendo una relación con la tabla Empresa. Si quisieras usar TRUNCATE necesitarías eliminar esa llave foránea.
Esto sucede porque TRUNCATE no revisa las filas y por lo tanto tampoco va a revisar las llaves foráneas. TRUNCATE sólo limpia las páginas de datos usadas por la tabla.
Aquí dejo el ejemplo de como eliminar la llave foránea antes de usar el TRUNCATE y como crearla de nuevo. Es importante asegurarnos de que sea en un proceso controlado y no perdamos la integridad referencial.
CREATE TABLE Logins(
    IdLogin int CONSTRAINT PK_Logins PRIMARY KEY,
    Usuario sysname,
    Contrasena  varchar(50)
);

CREATE TABLE Empresa(
    IdEmpresa int,
    IdLogin int CONSTRAINT FK_Empresa_Logins FOREIGN KEY REFERENCES Logins,
    --...
);
GO
ALTER TABLE Empresa DROP CONSTRAINT FK_Empresa_Logins;
TRUNCATE TABLE Logins;
ALTER TABLE Empresa WITH CHECK ADD CONSTRAINT FK_Empresa_Logins FOREIGN KEY( IdLogin) REFERENCES Logins ;


text:
Q: Levi-Civita & Kronecker delta identity I am trying to prove the following identity:
$\epsilon^{ijk}\epsilon_{pqk}=\delta_p^i\delta_q^j-\delta_p^j\delta_q^i$
Starting from the following identity:
$\epsilon^{ijk}\epsilon_{pqr}=\begin{vmatrix}
\delta^i_p & \delta^i_q & \delta^i_r \\
\delta^j_p & \delta^j_q & \delta^j_r \\
\delta^k_p & \delta^k_q & \delta^k_r \\
\end{vmatrix}$
But, when I expand out the matrix, I end up with:
$\epsilon^{ijk}\epsilon_{pqr}=\delta_p^i(\delta_q^j\delta_r^k-\delta_q^k\delta_r^j)-\delta_q^i(\delta_p^j\delta_r^k-\delta_p^k\delta_r^j)+\delta_r^i(\delta_p^j\delta_q^k-\delta_p^k\delta_q^j)$
Contracting by setting r=k, I obtained:
$\epsilon^{ijk}\epsilon_{pqr}=\delta_p^i(\delta_q^j\delta_k^k-\delta_q^k\delta_k^j)-\delta_q^i(\delta_p^j\delta_k^k-\delta_p^k\delta_k^j)+\delta_k^i(\delta_p^j\delta_q^k-\delta_p^k\delta_q^j)$
Then:
$\epsilon^{ijk}\epsilon_{pqr}=\delta_p^i(\delta_q^j-\delta_q^j)-\delta_q^i(\delta_p^j-\delta_p^j)+(\delta_p^j\delta_q^i-\delta_p^i\delta_q^j)$
So finally:
$\epsilon^{ijk}\epsilon_{pqr}=\delta_p^j\delta_q^i-\delta_p^i\delta_q^j$
Which is the identity I'm trying to prove, except that the right side is multiplied by -1 for some reason. I must be doing something wrong along the way, but I haven't been able to find it. Any ideas?
EDIT:
A similar question has been answered elsewhere, but it is only when expanding the determinant that I arrive at this problem. For that reason, I decided to make a separate post about this.
EDIT 2:
Added intermediate steps.
FINAL EDIT:
As Travis pointed out, I incorrectly replaced $\delta_k^k$ by $1$ instead of $3$. After correcting this, I arrived at the correct solution:
$\epsilon^{ijk}\epsilon_{pqr}=\delta_p^i(3\delta_q^j-\delta_q^j)-\delta_q^i(3\delta_p^j-\delta_p^j)+(\delta_p^j\delta_q^i-\delta_p^i\delta_q^j)=\delta_p^i\delta_q^j-\delta_p^j\delta_q^i$

A: It's hard to say for sure without seeing the intermediate steps of the contraction, but when carrying it out did you perhaps replace $\delta^k{}_k$ with $1$ instead of $3$? The latter is correct, because $$\delta^k{}_k = \delta^1{}_1 + \delta^2{}_2 + \delta^3{}_3 = 1 + 1 + 1 = 3 .$$


text:
Q: CSS leading dots with transparent BG I'm looking for a way to create leading dots after a text element. I need something that has a transparent background around the h1 element. Here is was my solutions needs to look like: http://www.redhatsociety.com/sites/all/themes/red_hat_society/images/partners/sample.png
and here is what I have right now that is not working: http://redhatsociety.com/rhs-hoot-day/prizes
Anyone know of a solution for this?

A: Use a pseudo-element like this.
Codepen Demo

h2 {
  position: relative;
  overflow: hidden;
  width:80% /* not required */

}

h2 span {
  display: inline-block;
  width:50%;
}

h2:after {
  content: "";
  position: absolute;
  top:50%;
  border: 3px red;
  border-style:dashed;
  width: 9999px;   /* some huge width */
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Saepe error ea nam corporis hic libero culpa excepturi perspiciatis, necessitatibus


text:
Q: What should I do to get an Clustered Index Seek instead of Clustered Index Scan? I've got a Stored Procedure in SQL Server 2005 and when I run it and I look at its Execution Plan I notice it's doing a Clustered Index Scan, and this is costing it the 84%. I've read that I've got to modify some things to get a Clustered Index Seek there, but I don't know what to modify.
I'll appreciate any help with this.
Thanks,
Brian

A: If the Query incldues more than a certain percentage of the rows in the table, the optimizer will elect to do a scan instead of a seek, because it predicts that it will require fewer disk IOs in that case (For a Seek, It needs one Disk IO per level in the index for each row it returns), whereas for a scan there is only one disk IO per row in the entire table.
So if there are, say 5 levels in the b-tree Index, then if the query will generate more than 20% of the rows in the table, it is cheaper to read the whole table than make 5 IOs for each of the 20% rows...
Can you narrow the output of the query a bit more, to reduce the number of rows returned by this step in the process?  That would help it choose the seek over the scan.

A: W/o any detail is hard to guess what the problem is, and even whether is a problem at all. The choice of a scan instead of a seek could be driven by many factors:

*

*The query expresses a result set that covers the entire table. Ie. the query is a simple SELECT * FROM <table>. This is a trivial case that would be perfectly covered by a clustred index scan with no need to consider anything else.

*The optimizer has no alternatives:

*

*the query expresses a subset of the entire table, but the filtering predicate is on columns that are not part of the clustered key and there are no non-clustred indexes on those columns either. These is no alternate plan other than a full scan.

*The query has filtering predicates on columns in the clustred index key, but they are not SARGable. The filtering predicate usually needs to be rewritten to make it SARGable, the proper rewrite depends from case to case. A more subtle problem can appear due to implicit conversion rules, eg. the filtering predicate is WHERE column = @value but column is VARCHAR (Ascii) and @value is NVARCHAR (Unicode).

*The query has SARGale filtering predicates on columns in the clustered key, but the leftmost column is not filtered. Ie. clustred index is on columns (foo, bar) but the WHERE clause is on bar alone.

*The optimizer chooses a scan.

*

*When the alternative is a non-clustered index then scan (or range seek) but the choice is a to use the clustered index the cause can be usually tracked down to the index tipping point due to lack of non-clustered index coverage for the query projection. Note that this is not your question, since you expect a clustered index seek, not a non-clustred index seek (assumming the question is 100% accurate and documented...)

*Cardinality estimates. The query cost estimate is based on the clustered index key(s) statistics which provide an estimate of the cardinality of the result (ie. how many rows will match). On a simple query This cannot happen, as any estimate for a seek or range seek will be lower than the one for a scan, no matter how off the statistics are, but on a complex query, with joins and filters on multiple tables, things are more complex and the plan may include a scan where a seek was expected because the query optimizer may choose  plan on which the join evaluation order is reversed to what the observer expects. The reverse order choice may e correct (most times) or may be problematic (usually due to statistics being obsolete or to parameter sniffing).

*An ordering guarantee. A scan will produce results in a guaranteed order and elements higher on the execution tree may benefit from this order (eg. a sort or spool may be eliminated, or a merge join can be used instead of hash/nested joins). Overall the query cost is better as a result of choosing an apparently slower access path.

These are some quick pointers why a clustered index scan may be present when a clustered index seek is expected. The question is extremly generic and is impossible to give an answer 'why', other than relying on an 8 ball. Now if I take your question to be properly documented and correctly articulated, then to expect a clustered index seek it means you are searching an unique record based on a clustred key value. In this case the problem has to be with the SARGability of the WHERE clause.


text:
Q: id of xpath is getting changed every time in selenium python 2.7 chrome one more problem i hv,i asked similar question earlier and i tried that method but not able use that methon in this problem so pls help me. it's element
html code is - Filters
So basically, question is that there is one button its kind of toggle button and i want click on that button to select device like Desktop, Tablet & Mobile all check boxes are already (default) selected now i have to uncheck or deselect device, to do this, first i have to click on that toggle button , when i click on toggle button its id (gwt-uid-598) 598 is getting changed every time or every refresh. Can you pls help me, what should or which method should i follow in this case.
i am using below python code.
Click on device Filters
elem = driver.find_element_by_xpath('//*[@id="gwt-uid-598"]/div/div/span')
elem.click()
Thanks in advance.

A: Good question.
Try to use another selector, for example: css class or use xpath method contains().
Example: //div[contains(text(), "checkbox")]
I can help you if you can provide source code of the page or needed element.


text:
Q: Measure time required to create thread How can I measure time required to create and launch thread?
(Linux, pthreads or boost::thread).
Thanks for advices!

A: You should probably specify what exactly you want to measure, since there are at least 2 possible interpretations (the time the original thread is "busy" inside pthread_create versus the time from calling pthread_create until the other thread actually executes its first instruction).
In either case, you can query monotonic real time using clock_gettime with CLOCK_MONOTONIC before and after the call to pthread_create or before the call and as the first thing inside the thread funciton. Then, subtract the second value from the first.
To know what time is spent inside phtread_create, CLOCK_THREAD_CPUTIME_ID is an alternative, as this only counts the actual time your thread used.
Alltogether, it's a bit pointless to measure this kind of thing, however. It tells you little to nothing at all about how it will behave under real conditions on your system or another system, with unknown processes and unknown scheduling strategies and priorities.
On another machine, or on another day, your thread might just be scheduled 100 or 200 milliseconds later. If you depend on the fact that this won't happen, you're dead.
EDIT:
In respect of the info added in above comment, if you need to "perform actions on non-regular basis" on a scale that is well within "normal scheduling quantums", you can just create a single thread and nanosleep for 15 or 30 milliseconds. Of course, sleep is not terribly accurate or reliable, so you might instead want to e.g. block on a timerfd (if portability is not topmost priority, otherwise use a signal-delivering timer).
It's no big problem to schedule irregular intervals with a single timer/wait either, you only need to keep track of when the next event is due. This is how modern operating systems do it too (read up on "timer coalescing").


text:
Q: Want to remove Boostrap mobile Nav Button Border This is my first post. My website (zidanmarketing.com) is using bootstrap, When the mobile button is active there is a blue border that I am unable to remove. How do I resolve this?
.navbar-toggle:hover,
.navbar-toggle:active,
.navbar-toggle:focus
{
background:none !important;
border-color:none !important;
}

A: .navbar-toggle {
  border: none;
  outline: none;
}

For targeting 767px and below, usually where the mobile button triggers try this.
@media (max-width: 767px) {
    .navbar-toggle {
      border: none;
      outline: none;
    }
}

A: try using  outline: 0;
The blue outline is a default on pressed buttons on chrome and some other browsers. Outline 0 should have that fixed!

A: Customizing Bootstrap
Make sure when customizing Bootstrap CSS to link your custom style sheet after the bootstrap link.


text:
Q: Cuando usar is o == Python Hola a todos les pido ayuda ya que estoy tomando un curso de python, y al momento de hacer una función para saber que valor devolver, la persona del curso hacía este if:
if value is None:
  return ""

return value

Y entonces me pregunto ¿hay alguna diferencia importante entre hacer eso a hacer un?:
if value == Null:
  return ""

return value

Desde ya gracias :).

A: is devolverá Verdadero si las variables apuntan al mismo objeto y == si los objetos a los que se refieren las variables son iguales.
  >>> 1000 is 10**3
  False
  >>> 1000 == 10**3
  True

A: Si no me equivoco el == es para hacer una comparación y el is es para saber si existe dentro de un conjunto.
Mas info...


text:
Q: Laravel update password errors Hi i'm trying to update user password using ajax but i keep getting 500 error.What i've done wrong
Here is my controller
public function newPass(Request $request)
    {
        User::where('id','=', Auth::user()->id)->update(['password' => Hash::make($request->password)]);
        return response()->json(array('mess'=>'Update success'));
    }

Here is ajax
$(document).ready(function() {
    $('#btnNewPass').click(function(event) {
        event.preventDefault();
        var pass=$("#password").val();
        $.ajax({
            url: '/updatePass',
            type: 'POST',
            data: {pass: pass},
        })
        .success(function(data) {
         alert(data.mess);
     })
        .error(function() {
            alert("Error");
        });

    });
});

The routes
Route::post('/updatePass','Auth\PasswordController@newPass');

A: I think you are missing the required token in your post and the TokenMismatchException is being fired.
Try putting this meta-tag in the head section:
<meta name="_token" content="{{ csrf_token() }}">

And then add this in your js file:
$.ajaxSetup({
  headers: {'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')}
});


text:
Q: Fill in a datatable with data from database so here's what im tryng to do. I've got some data to fill a datatable from mysql database. As referred to sample projects, I've been extracting those details doing a SELECT query from an existing table(named examquestion). my query would be something like this:
SELECT * FROM entrancequestion
WHERE Subject='Abstract Reasoning'
ORDER BY RAND()
LIMIT 10)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='English'
ORDER BY RAND()
LIMIT 30)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='Mathematics'
ORDER BY RAND()
LIMIT 30)

UNION

(SELECT * FROM entrancequestion
WHERE Subject='Science'
ORDER BY RAND()
LIMIT 30 )

so all in all the datatable should be filled 100 rows total.
my problem is actually inserting those data to a datatable
first i read the data from the database
dim myqry as string
'where myqry as the codes above
dim examdt as new datatable
Dim conn As New SqlClient.SqlConnection("server=localhost;User Id=root;database=jnhsdb")

    Try
        conn.Open()

        Dim cmd As SqlCommand = New SqlCommand(myqry, conn)
        'create data reader
        Dim rdr As SqlDataReader = cmd.ExecuteReader

        'loop through result set
        rdr.Read()

        'now im lost on this part.
        'i want to insert the data into a data table. i got some code in mind but i think im doing it wrong.

        conn.Close()
    Catch ex As Exception
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
    End Try

so, how do you actually insert those data from a database to a datatable?
follow up question:
would it be possible to create a dataset from the datatable along with those queries?

A: First of all - you contradict yourself. Your query is from MySQL, while your code is for SQL Server. You have to decide what you want to use. If it's indeed MySQL - you need to install MySQL.NET connector. The code below will be almost identical, only instead SQL* classes you will be using MySQL* classes (e.g. MySqlDataAdapter instead of SqlDataAdapter).
That said:
Don't use DataReader to fill the DataTable, use DataAdapter instead. After you created your SqlCommand - try this:
Dim da As New SqlDataAdapter(cmd)
da.Fill(examdt)

Later if needed - you can creatre a DataSet and add this table:
Dim ds As New DataSet
ds.Tables.Add(examdt)

But there're other ways. For example .fill() method of the SqlDataAdapter above is capable of filling DataSet directly instead of DataTable (it will create a table automatically)


text:
Q: I'm making a snake game using python. I cant seem to make the snake moves in any direction. What should i fix and add with my codes? I have this code below where it will add a +1 or -1 unit whenever I press any of the arrow button. My question is how can I use that new value in velocity and add it to my snake to the snake moves? I believe my code is wrong in the def snake() function but I don't seem to find the solution.
additional: what else should I fix to my code here to make it cleaner and concise? thank you
import random
from tkinter import *

SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
SCORE = 0
BODY_SIZE = 10
SNAKE_COLOUR ="blue"
SNAKE_FOOD = "purple"

def food():
    x = random.randint(0,30-1)*BODY_SIZE
    y = random.randint(0,30-1)*BODY_SIZE
    canvas.create_rectangle (x,y,x+BODY_SIZE,y+BODY_SIZE,fill="GOLD")

def snake():
    SNAKE_VELOCITY_X = 0
    SNAKE_VELOCITY_Y = 0
    snakeX = 0
    snakeY = 0
    snakeX = snakeX + SNAKE_VELOCITY_X
    snakeY = snakeY + SNAKE_VELOCITY_Y
    canvas.create_rectangle (snakeX,snakeY,snakeX+BODY_SIZE,snakeY+BODY_SIZE,fill="blue")

def update():
    food()
    snake()

master =Tk()
master.geometry("%sx%s"%(SCREEN_WIDTH,SCREEN_HEIGHT))
labelName= Label(master, text="A python game!", font= ('Courier 10 underline'))
labelScore = Label(master, text="%s"%(SCORE), font=('Courier 10'))
labelName.pack()
labelScore.pack()
canvas = Canvas(master, bg="black",width=300,height=300)
canvas.pack()

update()

def right_direction(event):
    SNAKE_VELOCITY_X = 1
    SNAKE_VELOCITY_Y = 0
    print(SNAKE_VELOCITY_X)
def left_direction(event):
    SNAKE_VELOCITY_X = -1
    SNAKE_VELOCITY_Y = 0
    print(SNAKE_VELOCITY_X)
def up_direction(event):
    SNAKE_VELOCITY_X = 0
    SNAKE_VELOCITY_Y = 1
    print(SNAKE_VELOCITY_Y)
def down_direction(event):
    SNAKE_VELOCITY_X = 0
    SNAKE_VELOCITY_Y = -1
    print(SNAKE_VELOCITY_Y)

master.bind("<Right>", right_direction)
master.bind("<Left>", left_direction)
master.bind("<Up>", up_direction)
master.bind("<Down>", down_direction)

master.mainloop()

A: This is not an exhaustive answer, but should get you moving in the right direction. First, the concept: you create objects with the create_...() functions, and those functions return "handles" to the created objects. you can then use the handles to move, etc. the objects. To actually redraw the screen, you need to call the Tk.update() function.
Roughly, you need to change number of things:
the function canvas.create_rectangle(...) returns a handle to the rectangle. Save it, this is your "snake"
snakeHandle=canvas.create_rectangle(...)

then, when you execute one of your functions ..._direction(event), inside that function, tell the snake to move somewhere like this:
canvas.move(snakeHandle,x_distance, y_distance)

then kick tkinter so it updates the screen:
master.update()

A: i changed a couple off things and now it should move. but the only problem is that the the snake does not get removed after it moves. you can try canvas.delete().
i put a # after everything i changed.
import random
from tkinter import *

SCREEN_WIDTH = 500
SCREEN_HEIGHT = 500
SCORE = 0
BODY_SIZE = 10
SNAKE_COLOUR ="blue"
SNAKE_FOOD = "purple"
SNAKE_VELOCITY_X = 0 # making these variables avalable to the whole code
SNAKE_VELOCITY_Y = 0 #
snakeX = 0 #
snakeY = 0 #

def food():
    x = random.randint(0,30-1)*BODY_SIZE
    y = random.randint(0,30-1)*BODY_SIZE
    canvas.create_rectangle (x,y,x+BODY_SIZE,y+BODY_SIZE,fill="GOLD")

def snake():
    global snakeX, snakeY, SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y # global makes it so that the change is not only for the function but for the entire code
    snakeX = snakeX + SNAKE_VELOCITY_X * BODY_SIZE # makes it so that the player moves on player size instead of one pixel
    snakeY = snakeY + SNAKE_VELOCITY_Y * BODY_SIZE #
    canvas.create_rectangle (snakeX,snakeY,snakeX+BODY_SIZE,snakeY+BODY_SIZE,fill="blue")

def update():
    #food() # otherwise spawns new food
    snake()

master =Tk()
master.geometry("%sx%s"%(SCREEN_WIDTH,SCREEN_HEIGHT))
labelName= Label(master, text="A python game!", font= ('Courier 10 underline'))
labelScore = Label(master, text="%s"%(SCORE), font=('Courier 10'))
labelName.pack()
labelScore.pack()
canvas = Canvas(master, bg="black",width=300,height=300)
canvas.pack()

update()

def right_direction(event):
    global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
    SNAKE_VELOCITY_X = 1
    SNAKE_VELOCITY_Y = 0
    print(SNAKE_VELOCITY_X)
    update() # calling the update function
def left_direction(event):
    global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
    SNAKE_VELOCITY_X = -1
    SNAKE_VELOCITY_Y = 0
    print(SNAKE_VELOCITY_X)
    update() #
def up_direction(event):
    global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
    SNAKE_VELOCITY_X = 0
    SNAKE_VELOCITY_Y = -1
    print(SNAKE_VELOCITY_Y)
    update() #
def down_direction(event):
    global SNAKE_VELOCITY_X, SNAKE_VELOCITY_Y #
    SNAKE_VELOCITY_X = 0
    SNAKE_VELOCITY_Y = 1
    print(SNAKE_VELOCITY_Y)
    update() #

master.bind("<Right>", right_direction)
master.bind("<Left>", left_direction)
master.bind("<Up>", up_direction)
master.bind("<Down>", down_direction)

master.mainloop()

hope this helps
EDIT
i change your code to be in a class and cleaned some things up
import random
from tkinter import *

class game(Tk):
    def __init__(self):
        super().__init__()
        self.createVariables()
        self.createWindow()
        self.bindControls()
        self.snake()
        self.food()

    def createVariables(self):
        self.SCREEN_WIDTH = 500
        self.SCREEN_HEIGHT = 500
        self.SCORE = 0
        self.BODY_SIZE = 10
        self.SNAKE_COLOUR ="blue"
        self.SNAKE_FOOD = "purple"
        self.SNAKE_VELOCITY_X = 0
        self.SNAKE_VELOCITY_Y = 0
        self.snakeX = 0
        self.snakeY = 0
        self._snake = None

    def createWindow(self):
        self.geometry("%sx%s"%(self.SCREEN_WIDTH,self.SCREEN_HEIGHT))
        self.labelName= Label(self, text="A python game!", font= ('Courier 10 underline'))
        self.labelScore = Label(self, text="%s"%(self.SCORE), font=('Courier 10'))
        self.labelName.pack()
        self.labelScore.pack()
        self.canvas = Canvas(self, bg="black",width=300,height=300)
        self.canvas.pack()

    def bindControls(self):
        self.bind("<Right>", self.right_direction)
        self.bind("<Left>", self.left_direction)
        self.bind("<Up>", self.up_direction)
        self.bind("<Down>", self.down_direction)

    def food(self):
        x = random.randint(0,30-1)*self.BODY_SIZE
        y = random.randint(0,30-1)*self.BODY_SIZE
        self._food = self.canvas.create_rectangle (x,y,x+self.BODY_SIZE,y+self.BODY_SIZE,fill="GOLD")

    def snake(self):
        if self._snake != None:
            self.canvas.delete(self._snake)
        self.snakeX = self.snakeX + self.SNAKE_VELOCITY_X * self.BODY_SIZE
        self.snakeY = self.snakeY + self.SNAKE_VELOCITY_Y * self.BODY_SIZE
        self._snake = self.canvas.create_rectangle (self.snakeX,self.snakeY,self.snakeX+self.BODY_SIZE,self.snakeY+self.BODY_SIZE,fill="blue")

    def update(self):
        self.snake()

    def right_direction(self, event):
        self.SNAKE_VELOCITY_X = 1
        self.SNAKE_VELOCITY_Y = 0
        print(self.SNAKE_VELOCITY_X)
        self.update()
    def left_direction(self, event):
        self.SNAKE_VELOCITY_X = -1
        self.SNAKE_VELOCITY_Y = 0
        print(self.SNAKE_VELOCITY_X)
        self.update()
    def up_direction(self, event):
        self.SNAKE_VELOCITY_X = 0
        self.SNAKE_VELOCITY_Y = -1
        print(self.SNAKE_VELOCITY_Y)
        self.update()
    def down_direction(self, event):
        self.SNAKE_VELOCITY_X = 0
        self.SNAKE_VELOCITY_Y = 1
        print(self.SNAKE_VELOCITY_Y)
        self.update()

if __name__ == "__main__":
    run = game()
    run.mainloop()

hope it helps


text:
Q: Calculated in what direction should i go I have a function with 2 parameters FROM and TO. TO can only be 0, 90, 180 or 270. FROM can be some number between 0 and 360.

*

*If FROM and TO are same function should return that number.

*If FROM is for example 181 and TO is 0 return 181+1

*but if FROM 179 return 179-1
Given 360°, calculate which direction is shortest to get from FROM to TO.
How to write this function without hundred lines of if and else.
nearestPath: function(from ,to){
        to = to%360;
        from = from%360;
        if(from == to){
            return to;
        }else{
            // Calculate increment or decrement..
        }

    }

A: Something like this:

function calc(from, to) {
    from = from%360;
    to = to%360;
    if (from === to) {
        return from;
    }
    var d = from - to - 180;
    if (d > 0 || d < -180) {
        return ++from;
    }
    return --from;
}

var to = +prompt("TO");
var from = +prompt("FROM");

alert(calc(from,to));


text:
Q: Hide/Show Load function not working I have a script that shows 2 divs and hides 1 div after a user submits a form. The form's target is an Iframe on the same page.
I would like to delay the Hide/Show events until the Iframe loads. I was able to do this with a loading animation, but I am not sure how to do this with the Hide/Show script.
The script works with the submit function like this:
$(function(){
    $('#form_710370').submit(function(e){
       e.preventDefault(); // add this
       $('#form_container').hide()
       $('#mydivhide1, #mydivhide2').show();
       return false;
    });
});

But if I try to use the load function like this, it does not work, but it works for my loading animation, any suggestions on what I am doing wrong?
$(document).ready(function () {
  $('#iframe1').load(function(){
  {
    $('#form_container').hide()
      $('#mydivhide1, #mydivhide2').show()
     });

This is the loading animation script which works
    $(document).ready(function () {
    $('#iframe1').on('load', function () {
    $('#loader1').hide();
        });
    });
    / in ready()
    $('#form_710370').submit(function(){$('#loader1').show();return true;});

Here is the HTML

1111

2222

    <form id="form_710370"  target="iframe" method="post" convert.php">
        <input id="Website" name="url1" type="text" value=""/>
        <input id="saveForm" type="submit" name="submit" value="submit" />
    </form>

Here is the CSS
#mydivhide1 {display:none;}
#mydivhide2 {display:none;}

A: I think the issue you're running into is that you're preventing the form from submitting to the iframe which is then showing the divs but the iframe is never calling load again because the submit is being stopped.
Assuming that you want to show #mydivhide1 and #mydivhide2 when the form is submitted and then hide them when the iframe finishes loading, I came up with a fiddle that should do what you want: http://jsfiddle.net/CST4t/3/
Basically I just removed the e.preventDefault( ); and instead of returning false, I returned true so the form submission went through.  I also cleaned up some items like the form action attribute and moved the submit function override to $(document).ready( );.
Edit
One other thing that I did was I changed the form target and the name of the iframe to a more commonly used name that seems to work better across more browsers. Apparently the name and target values are really touchy from browser to browser, see this answer.

A: $('#iframe1').contents().load(function() {
    //window loaded
});


text:
Q: Data type Varchar2 to date format I am writing SQL code to extract data for effective start date greater than or equal to 24/09/2018 00:00:00. My effective_start_date data type is in varchar2. Below is the code I am using:
TO_DATE(TRUNC(effective_start_date),'DD/MM/YY') >='24/09/2018 00:00:00')

A: try this:
select case
 when  Cast(effective_start_date as dateTime) >= cast('2018/09/24 00:00:00' as dateTime)
 then 1 --your business
 else
 0  --your business
 end

A: You can try this:
trunc(to_date( effective_start_date, 'DD/MM/YYYY HH24:MI:SS' )) >= to_date('24/09/2018 00:00:00', 'DD/MM/YYYY HH24:MI:SS')

Storing datetime as varchar is very wrong.


text:
Q: How to save a QR code generated from the Electrum Wallet directly as a PNG or JPG file? How do I save and send the QR code:

as a jpg or png?
There are ways to use gimp and/or xclip but I would hope that I can just save the QR code directly to file.  Is this possible?
Notably, Windows has the handy windows-shift-s which will allow an easy clip-and-save.  I'd resort to that if it's not possible to directly save the above QR code.

A: Use Ubuntu's screenshot taking features. Press Shift+Print Screen, then select QR-code area at the screen using mouse. Selected area will be saved as a PNG image file in ~/Pictures folder.


text:
Q: Java Executer Service I have a database result which creating 500 records per one call
500, then next 500, then next
I need to run a each records which different thread to do the specific task
My examples as follows
List<Users> users =  find 500 users

ExecutorService executor = Executors.newFixedThreadPool(10);
//for each users
for ( int i =0 ; i<users.size(); i++) {
 Runnable worker = new MyWorker(users.get(i));
 executor.execute(worker);
}

//MyWorker.java

class MyWorker implements Runnable {
User user;

MyWorker(User user)
  this.user = user;
}

@Override
public void run() {
   system.out.println("Start);
    processCommand(this.user);
   system.out.println("End);
}

processCommand(User user){
 //processing
}

}

My problem is that before finishing current executer service it getting the next 500 users and trying to start processing ,I need to stop that and until first 500 records processed then start next pool

A: You should try to have code that at least compiles.  Anyway it sounds like you could use a CountDownLatch to wait for the threads to complete before moving onto the next 500.
private void myfunc(List<User> users) throws InterruptedException {
    ExecutorService executor = Executors.newFixedThreadPool(10);

    CountDownLatch countDownLatch = new CountDownLatch(users.size());
    for ( int i =0 ; i<users.size(); i++) {
        Runnable worker = new MyWorker(users.get(i), countDownLatch);
        executor.execute(worker);
    }
    countDownLatch.await();

}
class MyWorker implements Runnable {
    User user;
    CountDownLatch countDownLatch;

    MyWorker(User user, CountDownLatch countDownLatch) {
      this.user = user;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public void run() {
        System.out.println("Start");
        processCommand(this.user);
        countDownLatch.countDown();
        System.out.println("End");
    }

    void processCommand(User user){
        //processing
    }
}


text:
Q: My testcafe browser is not closing, when I disable the screenshots from command line My testcafe browser is not closing, when I disable the screenshots from the command line
I an npm script like this
"api:dev": "cross-env ENV=dev testcafe \"chrome\" automation_suite/tests --disable-screenshots --fixture-meta FixtureType=IntegrationTests,TestType=API_TESTS,ProjectName=PR",
When I am running the tests, once after the execution is completed, the testcafe browser is not closing.
If I removed the --disable-screenshots then the browser is closed and execution getting completed.
I am not sure what mistake I am doing! I just want to disable the screenshots, as I am running the API tests and testcafe will take a screenshot of the blank page.
Any help is appreciated.

A: We will be happy to help you and diagnose this problem, However, I was unable to reproduce it.
Submit a bug report here https://github.com/DevExpress/testcafe/issues/new?template=bug-report.md
and add your environment information there, as well as a sample project and tests so that we can suggest a solution for you.


text:
Q: Issues with useReducer not synchronously updating the state According to React docs :

useReducer is usually preferable to useState when you have complex
  state logic that involves multiple sub-values or when the next state
  depends on the previous one.

1. can somebody explain me why useReducer is not updating the state synchronously ?
const reducer = (state, action) => {
    if( action.type === 'ADD_VALUE') {
        console.log(`STATE IN REDUCER`, [...state, action.path]) // => ["1.1"]
        return [...state, action.path]
    }
}

const [state, dispatch] = useReducer(reducer, [])

<input type="button" onClick={() => {
    dispatch({ type: 'ADD_VALUE', path: "1.1"})
    console.log(`STATE`, state) // => []
    // here i want to do some stuff based on the lastest updated state (["1.1"] and not [])
    // for example dispatch an action with redux
}}/>

2. How can I do some stuff (dispatch a redux action) based on the lastest updated state (["1.1"] and not []) ?

A: Use useEffect to access the state correctly. You could add some safe-guarding if you want something invoking if a certain criterion is hit.
If you want to access your reducer across components, you can store the reducer using Context API. Look below for an example. You can see the reducer being injected into the Context on the parent component and then two child components that a) dispatches an action b) receives the update from the action.
1. Example of context reducer to use across multiple components
import React from "react";
import ReactDOM from "react-dom";

const Application = React.createContext({
  state: null,
  dispatch: null
});

function ActionComponent() {
  const { dispatch } = React.useContext(Application);
  return (

Action Component

          <button onClick={() => dispatch("lol")}>Do something</button>

  );
}

function ListenerComponent() {
  const { state } = React.useContext(Application);
  React.useEffect(
    () => {
      console.log(state);
    },
    [state]
  );
  return
Listener Component
;
}

function App() {
  const [state, dispatch] = React.useReducer(function(state = [], action) {
    return [...state, action];
  });
  return (
    <Application.Provider value={{ state, dispatch }}>

        <ActionComponent />
        <ListenerComponent />

    </Application.Provider>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

2. Example of local reducer without using Application Context
const reducer = (state, action) => {
    if( action.type === 'ADD_VALUE') {
        return [...state, action.path]
    }
}

const [state, dispatch] = useReducer(reducer, [])

React.useEffect(() => {
    console.log(state);
}, [state]);

<input type="button" onClick={() => {
    dispatch({ type: 'ADD_VALUE', path: "1.1"})
}}/>


text:
Q: Proper way to change text and elements on a page with JavaScript I've been using innerHTML and innerText for a while to change elements and text on web pages and I've just discovered that they are not W3C standard.
I've now found that innerHTML can be replaced with createElement, setAttribute and a few others but what is the best method for changing text inside an element?
I found a textContent as well but is there a standard way and is it widly implemented across older browsers?

A: textContent isn't implemented in IE8 and lower.  You can use createTextNode() similar to how you would use createElement().  However, I often use discovery techniques to find out which property I need to use and keep a reference to it:
// You can use a shorter variable name if you want
var innerTextOrTextContent = "textContent" in document.body
                               ? "textContent" : "innerText";

// Set an element's text:
myElement[innerTextOrTextContent] = "Added using: "+innerTextOrTextContent;

The createTextNode() example:
var tNode = document.createTextNode("Added using createTextNode()");
myElement.appendChild(tNode);

Something I often forget about, you can also directly set a text node's value, if you can get a reference to it:
// childNodes[0] is a text node:
myElement.childNodes[0].nodeValue = "Added using nodeValue";

Example -  http://jsfiddle.net/BxPaG/.

A: I think you can't go wrong by using whatever your javascript library offers for changing text (innerHtml for jQuery). After all one of the the main reasons for using such a library is having a platform that abstracts from different browser implementations.


text:
Q: Как сделать Bottom Navigation чтобы у каждой вкладки был свой стэк активити Хочу реализовать подобный Bottom Navigation как в Vk, Facebook, Inst.
Чтобы у каждой вкладки был свой стэк активити. Я не знаю как по-нормальному это объяснить.
Для более точного понимания моей идеи вот схема внизу

A: Все, что вы нарисовали на схеме, выражается в коде примерно так:
public class MainActivity extends AppCompatActivity {

private HashMap<String, Stack<Fragment>> mStacks;
public static final String TAB_HOME  = "tab_home";
public static final String TAB_DASHBOARD  = "tab_dashboard";
public static final String TAB_NOTIFICATIONS  = "tab_notifications";

private String mCurrentTab;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);
    navigation.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);

    mStacks = new HashMap<String, Stack<Fragment>>();
    mStacks.put(TAB_HOME, new Stack<Fragment>());
    mStacks.put(TAB_DASHBOARD, new Stack<Fragment>());
    mStacks.put(TAB_NOTIFICATIONS, new Stack<Fragment>());

    navigation.setSelectedItemId(R.id.navigation_home);
}

private BottomNavigationView.OnNavigationItemSelectedListener mOnNavigationItemSelectedListener
        = new BottomNavigationView.OnNavigationItemSelectedListener() {

    @Override
    public boolean onNavigationItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.navigation_home:
                selectedTab(TAB_HOME);
                return true;
            case R.id.navigation_dashboard:
                selectedTab(TAB_DASHBOARD);
                return true;
            case R.id.navigation_notifications:
                selectedTab(TAB_NOTIFICATIONS);
                return true;
        }
        return false;
    }

};

private void gotoFragment(Fragment selectedFragment)
{
    FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
    fragmentTransaction.replace(R.id.content, selectedFragment);
    fragmentTransaction.commit();
}

private void selectedTab(String tabId)
{
    mCurrentTab = tabId;

    if(mStacks.get(tabId).size() == 0){
        if(tabId.equals(TAB_HOME)){
            pushFragments(tabId, new HomeFragment(),true);
        }else if(tabId.equals(TAB_DASHBOARD)){
            pushFragments(tabId, new DashboardFragment(),true);
        }else if(tabId.equals(TAB_NOTIFICATIONS)){
            pushFragments(tabId, new NotificationsFragment(),true);
        }
    }else {
        pushFragments(tabId, mStacks.get(tabId).lastElement(),false);
    }
}

public void pushFragments(String tag, Fragment fragment, boolean shouldAdd){
    if(shouldAdd)
        mStacks.get(tag).push(fragment);
    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

public void popFragments(){
    Fragment fragment = mStacks.get(mCurrentTab).elementAt(mStacks.get(mCurrentTab).size() - 2);

    mStacks.get(mCurrentTab).pop();

    FragmentManager manager = getSupportFragmentManager();
    FragmentTransaction ft = manager.beginTransaction();
    ft.replace(R.id.content, fragment);
    ft.commit();
}

@Override
public void onBackPressed() {
    if(mStacks.get(mCurrentTab).size() == 1){
        finish();
        return;
    }

    popFragments();
    }
 }

Пример добавления нового фрагмента в стек вкладки HOME:
public class HomeFragment extends Fragment {
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_home, container, false);
    Button gotoNextFragment = (Button) view.findViewById(R.id.gotoHome2);

    gotoNextFragment.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ((MainActivity)getActivity()).pushFragments(MainActivity.TAB_HOME, new Home2Fragment(),true);
        }
    });
    return view;
    }
}


text:
Q: Can't import typescript module I'm using the following boilerplate as a start:
https://github.com/rokoroku/react-redux-typescript-boilerplate
I am trying to import a node_modules that has only ts files. I install it from a local directory which looks like this:
/abc-def
  /src
    /index.ts
  /package.json

The package.json of this dep looks like this:
{
  "name": "@abc/def",
  "version": "1.0.0",
  "license": "UNLICENSED",
  "main": "./src/index.ts",
}

I installed it, works fine
yarn add file:../abc-def

It shows up in node_modules under @abc/def and in the package.json of the boilerplate fine:
"dependencies": {
  "@abc/def": "file:../abc-def"
}

Although, when I run the project, typescript complains it can't find the dependency for some reason, I can't import it.
import Def from '@abc/def';

ERROR in [at-loader] ./src/containers/App/index.tsx:10:23
      TS2307: Cannot find module '@abc/def'.

I tried to replace the ts file by a js file and it works fine, although it doesn't want to import the ts file directly. There must be some ts configuration to change but I'm not sure which ones.
I went through the TS module resolution documentation but still can't figure out the right way to modify the tsconfig.json file.
Any idea why I can't import ts files directly?
Thanks
Edit:
Just found out if I move the entry file to the root folder of my module, so moving src/index.ts to index.ts, it works fine. It seems like the typescript resolution doesn't read the main field from the package.json file. Is this a bug?
I've output the resolve stack, interesting to see it ignores the main  field from the package.json:
======== Resolving module '@abc/def' from '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/src/containers/App/index.tsx'. ========
Explicitly specified module resolution kind: 'NodeJs'.
Loading module '@abc/def' from 'node_modules' folder, target file type 'TypeScript'.
Directory '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/src/containers/App/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Directory '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/src/containers/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Directory '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/src/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Found 'package.json' at '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def/package.json'.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def.ts' does not exist.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def.tsx' does not exist.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def.d.ts' does not exist.
'package.json' does not have a 'typings' field.
'package.json' does not have a 'types' field.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def/index.ts' does not exist.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def/index.tsx' does not exist.
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@abc/def/index.d.ts' does not exist.
Scoped package detected, looking in 'abc__def'
File '/Users/alexmngn/Workspace/react-redux-typescript-boilerplate/node_modules/@types/abc__def.d.ts' does not exist.
Directory '/Users/alexmngn/Workspace/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Directory '/Users/alexmngn/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Directory '/Users/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'
Directory '/node_modules' does not exist, skipping all lookups in it.
Scoped package detected, looking in 'abc__def'


text:
Q: crossval in Matlab- Predfun only runs if it has zero arguments? I'm trying to use the crossval function built into Matlab. I have a Logistic Regression function set up and ready to go, but the behaviour I'm getting is not what I'd expect from the documentation.
From the Crossval documentation page, the overload:
mse = crossval('mse',X,y,'Predfun',predfun)

seemed to fit what I needed best. The doocumentation says

mse = crossval('mse',X,y,'Predfun',predfun) returns mse, a scalar
  containing a 10-fold cross validation estimate of mean-squared error
  for the function predfun. X can be a column vector, matrix, or array
  of predictors. y is a column vector of response values. X and y must
  have the same number of rows.
predfun is a function handle called with the training subset of X, the
  training subset of y, and the test subset of X as follows:
yfit = predfun(XTRAIN,ytrain,XTEST)
Each time it is called, predfun should use XTRAIN and ytrain to fit a
  regression model and then return fitted values in a column vector
  yfit. Each row of yfit contains the predicted values for the
  corresponding row of XTEST. crossval computes the squared errors
  between yfit and the corresponding response test set, and returns the
  overall mean across all test sets.

So I defined a function in another file in the same directory, with the signature:
function ytest = logRegTester(XTRAIN, ytrain, XTEST)

Matlab was giving me the error

Error using logRegTester (line 11)
  Not enough input arguments.

To experiment, I tried reducing the number of arguments logRegTester expected, and found crossval would only call my function if it had zero arguments. Which seems to contradict the documentation, which wants a function with three arguments.

A: Please use function handle @logRegTester as required by predfun() instead using logRegTester directly.


text:
Q: Jmeter in distibuted mode I am running test for 500 users. I have one Application server and I am running JMeter in distributed mode with one master and 5 slaves.
The scenario is Jmeter is sending 5 requests to the server at any point of time. However, I need to control only Login request where each Login from the slave  has to hit the server in different intervals.
How can I do this?

A: You can set the start time of each and every thread in the slave, set the start time such that each slave starts at a different time.

If you set the thread of slave one start time as 2016/06/10 15:03:58
Set the other slaves same thread as 2016/06/10 15:03:60
This will make each slave hit the server at different time interval.
OR
you can play around with startup delay of each slave, this works too.
Hope this helps.


text:
Q: Comparing 2 objects using JUnit I have a service which I want to test:
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentDao departmentDao;
    //... other functions

    @Override
    public Department getDepartment(int depid) {
        return departmentDao.getDepartment(depid);
    }
}

and here is my test class:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:sdnext-servlet.xml")
public class TestDepartmentDetails {

    Department department  = new Department();
    DepartmentServiceImpl service = new DepartmentServiceImpl();

    @Autowired
    private DepartmentDao myDao;

    @Test
    public void testGetDepartment(){
        assertEquals("lalalalalalala", service.getDepartment(98).getDepName());
    }

Why it gives me a failure and throws a NullPointerException? Is there any other solution?
Note: This is an application which uses Spring and Hibernate.

A: Try it this way
 @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = "classpath:sdnext-servlet.xml")
    public class TestDepartmentDetails {
        @Autowired
        DepartmentService   service;
        @Test
        public void testGetDepartment(){
            assertEquals("lalalalalalala", service.getDepartment(98).getDepName());
        }

A: Here you are creating instances manually which is not the right way while using Spring.
Please refer to the Spring docs below:
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/
You have to autowire DepartmentServiceImpl service instead of DepartmentDao in this case.


text:
Q: Nodejs response is sent as string instead of an JSON I'm trying to send a JSON object with a response in a 403 event, that contains token expiration info, amongst others, to the client. However, for some reason the response is sent as a string object instead of JSON.
The response looks like this:

Here are the relevant functions.
This is from the server:
function checkYourPrivilege(checkAdmin, bearerHeader, res, reg, next){
        if (typeof bearerHeader !== 'undefined') {
                var bearer = bearerHeader.split(" ");
                bearerToken = bearer[1];
                jwt.verify(bearerToken, secret, function(err, decoded) {
                        console.log(decoded);
                        if(err){
                                return res.json({ success:false, message: 'Failed to authenticate token'});
                        }else{
                                if(Math.floor(Date.now() / 1000 < decoded.expires)){
                                        if(checkAdmin){
                                                if(decoded.privileges.admin){
                                                        console.log("Tokenisi vanhentuu" + Math.abs(decoded.expires - Math.floo$
                                                        reg.decoded = decoded;
                                                        next();
                                                }else{
                                                        console.log("et ole admin");
                                                        return res.status(403).send({
                                                          success: false,
                                                          tokenstatus: "valid",
                                                          message: "Not admin"
                                                        });
                                                }
                                        }else{
                                                console.log("Tokenisi vanhentuu" + Math.abs(decoded.expires - Math.floor(Date.n$
                                                reg.decoded = decoded;
                                                next();
                                        }
                                }else{
                                        console.log("Token Expired");
                                        return res.status(403).send({
                                                  success: false,
                                                  tokenstatus: "valid",
                                                  message: "Not admin"
                                        });
                                }
                        }
                });
        } else {
                console.log('ei tokenia');
                return res.status(403).send({
                        success: false,
                        message: 'No token provided.'
                });
        }
};

This is from the client:
.factory('authInterceptorService', ['$q', '$location', '$localStorage', function($q, $location, $localStorage){
        return {
                'request': function (config){
                        console.log(config);
                        config.headers = config.headers || {};
                        if ($localStorage.accessToken) {
                                config.headers.Authorization = 'bearer ' + $localStorage.accessToken;
                        }
                        return config;
                },
                'responseError': function(response){
                        if(response.status === 401 || response.status === 403) {
                                console.log(response);
                                $location.path('/');
                        }
                        return $q.reject(response);
                }
        };
}])

A: Try use
res.status(403).json({}) instead of
res.status(403).send({})


text:
Q: Check for correct input via scanf I have an integer 'n' that is responsible for amount of numbers to enter later on.
I need to check for any incorrect inputs here.
The first scanf for 'n' works fine, but the second has some flaws.
The case is following:
n = 3 (e.g.) - doesn't matter
Then I want to scanf: 1 2 3 4
It will be scanned first 3 values but I need to throw out an error.
Same goes with: 1 2 3.5  - (last number is float but it still reads 3)
and with a char: 1 2 3g
if (scanf("%d", n) == 1 && getchar() == '\n') {
        if (n > NMAX || n < 0) {
            error = 1;
            return;
        }
        for (int i = 0; i < n; i++) {
            if (scanf("%d", p) == 1) {

The ONLY correct input is the exact same amount of integer numbers (equals to 'n') to scan in a for  loop.
UPD: I can use only <stdio.h> library as well as only scanf.

A: Create a helper function to read an int and validate it.
The key is that to validate input, form a helper function that you can improve as needed, like using fgets() rather than scanf() once the poor "only scanf" requirement is removed.
// Sample
// Return 1 on success
// Return EOF on end-of-file
// Else return 0
int read_int(int *i, int min, int max, int line) {
  long long num;
  int result = scan("%18lld", &num);  // Accept many out of int range input
  if (result == EOF) return result;  // or if (result < 0)

  if (line) {
    // consume the rest of the line
    int ch;
    while ((ch = getchar()) != '\n' && ch != EOF) {
      if (!isspace(ch)) { // or `ch != ' ' && `ch != '\t' && ...
        result == 0;
      }
    }
  }

  if (result == 1) {
    if (num < min || num > max) {
      return  0;
    }
    *i = (int) num;
  }

  return result;
}

Sample usage
if (read_int(&n, 0, NMAX, 1) != 1) {
  error = 1;
  return;
}
for (int i = 0; i < n; i++) {
  if (read_int(&p, INT_MIN, INT_MAX, i + 1 == n) != 1) {
    error = 1;
    return;
  }
  ...

Note: read_int() does not catch all errors, just many of them.  Easy enough to improve, once all OP's limitations and goals are known.

A: Try using scansets with scanf. %1[\n] will scan up to one character that is a newline. %99[ \t] will scan up to 99 characters that are space or tab. If the character is not a newline, space or tab, it is replaced in the input stream.
If scanf with %d can't scan an int, it will return 0. scanf could also return EOF.
fgets and parse with strtol or others is the better solution.
#include <stdio.h>

int main ( void) {
    char space[100] = "";
    char newline[2] = "";
    int number = 0;
    int count = 0;
    int quantity = 3;

    printf ( "enter %d integers\n", quantity);
    while ( 1) {
        if ( 1 == scanf ( "%d", &number)) {
            ++count;
        }
        else {
            printf ( "could not parse an integer\n");
            break;
        }
        scanf ( "%99[ \t]", space);
        if ( 1 == scanf ( "%1[\n]", newline)) {
            if ( count == quantity) {
                printf ( "scanned %d integers\n", quantity);
                break;
            }
            else if ( count > quantity) {
                printf ( "too many integers\n");
                break;
            }
            else printf ( "enter another integer\n");
        }
    }
    return 0;
}

A: Check if this works
while(n-1)
{
    scanf("%d ",p);
    n-=1;
}
scanf("%d",p);
//After this you can scan again to check if there is anything extra in input
//and throw error accordingly


text:
Q: WCF Client for Axis2/Rampart Webservice using WS security without client certificate I´m just facing some problems setting up a WCF(.NET 4.0) webservice to call an Axis2 Rampart webservice.
I´m new to WCF and i didn´t find a tutorial wich completly fits this special scenario.
Here are the facts:
The webservice i have to call is an Axis2 Ramart service.
The Client i need to build uses WCF/.NET 4.0.
The Webservice uses SOAP 1.1 and WS-Security (Messagesecurity).
WS-Securtity should work like this:
The server provides a certificate with the public key.
The client generates a secret symmetric key.
The client encrypts this secret key with the servers public key.
This encrypted key is written into the Soap-header.
The client encrypts the body of the Soap request with the secret key.
(In fact the dodumentation I got from the webservice provider says that the body is encrypted with the servers public key, but in the sample request they provide, the encryption method is stated as aes128-cbc wich is a symmetric key AFAIK)
So this is what i have to do.
What i have done so far was to try some custom bindings from several tutorials.
But all samples I found uses server AND CLIENT-certificates and I didn´t managed to adjust these bindings in a way that works for me.
So here is a sample-request that shows how the request should look like:
<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
    <soapenv:Header>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
            <xenc:EncryptedKey Id="EncKeyId-Cl6B57CC684EEpm8E6E61WBp3421878712">
                <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-1_5" />
                <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                    <wsse:SecurityTokenReference>
                        <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#ThumbprintSHA1">D99lKi5jizWOxThG6yZXw6llwq4FdM=</wsse:KeyIdentifier>
                    </wsse:SecurityTokenReference>
                </ds:KeyInfo>
                <xenc:CipherData>
                    <xenc:CipherValue>Ab5i63RFNPNXcoEn6PqflaoPjsUI3E5EZh668621xkMcEDz9Jcm204A5Ecn8WQamxKX7UYEG8gPwn66X+pOj0DiWD4ShKVJIOD5gCliobcGgjVB1Uihj8Xk5MGesi8atuy9RFA=</xenc:CipherValue>
                </xenc:CipherData>
            </xenc:EncryptedKey>
            <wsc:DerivedKeyToken xmlns:wsc="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="derivedKeyId-1">
                <wsse:SecurityTokenReference>
                    <wsse:Reference URI="#EncKeyId-Cl6B57CC684EEpm8E6E61WBp3421878712"
                    ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKey" />
                </wsse:SecurityTokenReference>
                <wsc:Offset>0</wsc:Offset>
                <wsc:Length>16</wsc:Length>
                <wsc:Nonce>wQ9oyLHKjKRx6Dlm04RaL5Q==</wsc:Nonce>
            </wsc:DerivedKeyToken>
            <xenc:ReferenceList>
                <xenc:DataReference URI="#EncDataId-2" />
            </xenc:ReferenceList>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Id-15079889">
        <xenc:EncryptedData Id="EncDataId-2" Type="http://www.w3.org/2001/04/xmlenc#Content">
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc" />
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                    <wsse:Reference URI="#derivedKeyId-1" />
                </wsse:SecurityTokenReference>
            </ds:KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>
                    +Tx9+XL7QqFVZKCr5wEhyOBENlCfHm0y1y5yWwnIk2kHNoO3IFFJj2rSQdt7HiqfcU6XxAVn3eVJKmmuN+rPYISoJstl8EnStaEIqSTuUyTUrgchx5Zxor47TOknXXjo3dYhTKHqvsx8SX70GG3M+bJS/Q1CWDlWzidKWxORo8D02iVcQdu00dnw7SHWYwyzzhduQbsozyzcAER5cYnQuuUPOcBusivq/L0xDOVTFaGr9/vvPGo+yk2bN0nBLeikk0uSJr7Z/IqGL+Dqg5BA0f+8X8sxFQpRQmtSoXtvhs2bGy8v1MPkCYKPmajSR/XwMaQB2zxR6vKsGA7ODH9+ocqO+rbPOYWpRz+czogOUo5s+OYIwX9u+99NmC5zuSjvK5bwJzWWrJ0h31OM0KeTkc7rxTIm8QMR5ytBNnCtU9QXQeAMbBdwGok330rq5ZH9bN4TdBg9Qhzs8CGGpjMYZaQ9ApTt6vkGK0i9gtdXdvY1fVZpsPcU67MYvkXJARQMpwj9Z3ZDVscdiPIxvfHyBkT8Ta21mDlYRidxanr87CrLB6HyiEyhD1XKwpTZ7OpNja6UOzfGNOJx07SbgGF+ozDBaC7zs691L4iawDioXagUZSkQ9UgwaqycSh3YYa5+RYuPka1Z0z2cmdAaFnEtoZAaSftGj8k=
                </xenc:CipherValue>
            </xenc:CipherData>
        </xenc:EncryptedData>
    </soapenv:Body>
</soapenv:Envelope>

Perhaps someone could tell me how I can accomplish this, or where I can find some tutorials.
Thank you in advance.
This is the Resposne I get after I´ve implementet the Custom Binding and the Messsage-Encoder:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header>
        <wsse:Security xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" soapenv:mustUnderstand="1">
            <wsc:DerivedKeyToken xmlns:wsc="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="derivedKeyId-159">
                <wsse:SecurityTokenReference>
                    <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1">Aef7igYIlyWYa9XrbSYSt9Lh5Q4=</wsse:KeyIdentifier>
                </wsse:SecurityTokenReference>
                <wsc:Offset>0</wsc:Offset>
                <wsc:Length>16</wsc:Length>
                <wsc:Nonce>Ub30ogcNT6p7ZkH+qXFclw==</wsc:Nonce>
            </wsc:DerivedKeyToken>
            <wsc:DerivedKeyToken xmlns:wsc="http://docs.oasis-open.org/ws-sx/ws-secureconversation/200512" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="derivedKeyId-159">
                <wsse:SecurityTokenReference>
                    <wsse:KeyIdentifier EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary" ValueType="http://docs.oasis-open.org/wss/oasis-wss-soap-message-security-1.1#EncryptedKeySHA1">">Aef7igYIlyWYa9XrbSYSt9Lh5Q4=</wsse:KeyIdentifier>
                </wsse:SecurityTokenReference>
                <wsc:Offset>0</wsc:Offset>
                <wsc:Length>16</wsc:Length>
                <wsc:Nonce>Ub30ogcNT6p7ZkH+qXFclw==</wsc:Nonce>
            </wsc:DerivedKeyToken>
            <xenc:ReferenceList xmlns:xenc="http://www.w3.org/2001/04/xmlenc#">
                <xenc:DataReference URI="#EncDataId-160"/>
            </xenc:ReferenceList>
        </wsse:Security>
    </soapenv:Header>
    <soapenv:Body xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" wsu:Id="Id-1046510178">
        <xenc:EncryptedData xmlns:xenc="http://www.w3.org/2001/04/xmlenc#" Id="EncDataId-160" Type="http://www.w3.org/2001/04/xmlenc#Content">
            <xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"/>
            <ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
                    <wsse:Reference URI="#derivedKeyId-159"/>
                </wsse:SecurityTokenReference>
            </ds:KeyInfo>
            <xenc:CipherData>
                <xenc:CipherValue>zQUBHBX2nMTfL5gxXseNqqE5goAFSPQEd2D1RAsUZi+L64gqYfdQQIg//hWhw0Ed9gGFxLX8/ocq
svVX7oVTN4YkCF9LdLmY1y7/SmbDMyjKjzhxvQ5Bz2mu1EzWBtWRjAYGnMtLTJCCWEK0ZeqKGXDi
rqcHMwJYK4vGKeizAl/BMN2dLqp4gANSHB7kryGYiK4C2NncYwpbbws/It6Lm2RPuUenFW+2VCaC
OW8YdCMMfveEvO+18+BaApxS2ShckTbip9nbpDzVvGw4gFw/70xAupMkkUEGJPdBnb6ce9qC/jQm
MeBL4FSenEJbqR1qSU5xh6rD7m6Vqug5mEP7c2Tk/mPSFVlZ88TXV2S31NB+3PDAXxyZss9aftBl
L+q+m8oP/hqse9Oju8MaztP/gBQDSKuTBLWgMPvwluEZmnPnpItZX9CFOVGDaaWlnoN1Lgc6iKk/
8xDC95t87++NesK6Zqa+J15qGm4MozFBe5pS75wARrGA34USnHytNNJGyidx15wQgNrT9gxTlypQ
BU3830rWiWAsrFwzSQBC20TcNb0ofscNJqVhwmRnMHz75Gbn70jyGTM0W27PFYfq/xfJ3MCe/pov
Dqn647j2Ixvj/Rik02HJdUUm/cdmRxawWQVUvmxPbPNNOjCoccwOWxf623zXpD3DdV8U/5+jDite
eQnrpaU4griXc7jq85OIoghf++cShAK+tx5t8BjLaD1rBF3ni5Eqt2xbMoZ6cfzr314PxmffyjHM
rCzSMU4cw0BndzJrV2r0aKTEPxVRPIQur8ztEtIYCRWloceS4N2YKkdRm/W7TWBsIa+HOCpq9Rpr
bu0KLP54tBBTO5hzjIsjYn7JzfohYk5aDN/8ZsQqgsO0LhWu/9qj8j2fY+yC4W9i7m+/bLvuYSbO
Tm7B0vV5s79uG4Xi/ONM7O1NR/C1HSEddQnr0/zdDxJcJsxwAmyryILmLynaZyxeFYz5ueqQuNCZ
MTRvKdEfw2+Tt7l3lUSZ/WqPcAz2UFA7kdASk2esmQjVZjvvdLQfan7xHffU1Ga5nmafuXrCZR81
k+1OYs64oy14qFor0e3DXlyeUOPC67iEP92lBQl7hz4v9I0afSmEhmc3iR/XoYTgliP2QhkeEw11
gSGa9u6oLfQfGZVsDV6meL51kkM+FRKq8Y2QjJjSyVFUzQXmg0lAySjlTjVeYZbRCSleCSqk+tIJ
XIcsdkY9PSVxdWOiqXQcQlrae1Wj34Xf+h6NpNuIt/TSKxd896b0ACzz8ouHUvI/Wyk5Rz/Rmvzi
g/cGK9YnX8VGV2hpUzsVZLByUoWvMH+hv9ep1syQiA5EiIu+paTS92CW1i2x39pnKeMrYhI6Ug==</xenc:CipherValue>
            </xenc:CipherData>
        </xenc:EncryptedData>
    </soapenv:Body>
</soapenv:Envelope>

And This is the ReadMessage-Function of My MessageEncoder (I know it´s not the best way to parse Xml). It removes one of the two derived keys:
public override Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType)
        {

            var msg = innerEncoder.ReadMessage(buffer, bufferManager, contentType);
            var xml = msg.ToString();

            var msgbuffer = msg.CreateBufferedCopy( int.MaxValue );
            msg = msgbuffer.CreateMessage();

            MemoryStream stream = new MemoryStream();
            XmlDictionaryWriter xmlWriter = XmlDictionaryWriter.CreateBinaryWriter(stream);
            msg.WriteMessage(xmlWriter);
            xmlWriter.Flush();
            stream.Position = 0;

            XmlDictionaryReader xmlReader = XmlDictionaryReader.CreateBinaryReader(stream, XmlDictionaryReaderQuotas.Max);
            XmlDocument doc = new XmlDocument();
            doc.Load(xmlReader);

            XmlNode security = null;

            XmlNode derivdeKey = null;
            foreach (XmlNode xnode in doc.DocumentElement.FirstChild.ChildNodes)
            {
                if (xnode.LocalName == "Security")
                    foreach (XmlNode node in xnode.ChildNodes)
                    {
                        security = node;
                        if(node.LocalName == "DerivedKeyToken")
                        {

                        }
                        if(derivdeKey != null)
                        {
                            XmlNode pnode = node.ParentNode;
                            pnode.RemoveChild( node );
                        }
                        else
                        {
                            derivdeKey = node;
                        }
                    }
            }

            Stream memStream = new MemoryStream();
            xmlWriter = XmlDictionaryWriter.CreateBinaryWriter( memStream );
            doc.WriteTo(xmlWriter);
            xmlWriter.Flush();
            memStream.Position = 0;

            xmlReader = XmlDictionaryReader.CreateBinaryReader(memStream, XmlDictionaryReaderQuotas.Max);
            Message newMessage = Message.CreateMessage(xmlReader, 10240, msg.Version);
            xml = newMessage.ToString();

            return newMessage;
        }

I`m wondering about how the Message is shown as string (newMessage.ToString()) because the body is shon was ...stream....
The Problem is that I get the followingError-message:
System.ServiceModel.Security.MessageSecurityException : The 'Body', 'http://schemas.xmlsoap.org/soap/envelope/' required message part  was not signed.

So I stripped of the Security node as descriped here http://webservices20.blogspot.de/2012/04/when-enableunsecuredrespose-requires.html.
This is the stripped resonse:
<?xml version="1.0" encoding="utf-16"?><soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Body wsu:Id="Id-1532543044" xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"><xenc:EncryptedData Id="EncDataId-586" Type="http://www.w3.org/2001/04/xmlenc#Content" xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"><xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes128-cbc"></xenc:EncryptionMethod><ds:KeyInfo xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<wsse:SecurityTokenReference xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><wsse:Reference URI="#derivedKeyId-585"></wsse:Reference></wsse:SecurityTokenReference>
</ds:KeyInfo><xenc:CipherData><xenc:CipherValue>APZ9aATpcMu5qU6PdoKeTLjAblJP/uLZAzX8imgSSfvaZGGeI8prg9JNTEOjZ1SAeuWxod/ZV4pb
3OeY3b1IWxxhG5WWGxu51WAAehGBmiyFYOzJwbpR5cOHUc7aRBm7hkeqr/1RlcYDlAk4Y+G1URgv
0K2nzqfDR3m7ydZSVoa3aSWWzmhjMTnJnPyQ060fDXiU7/k0tI12danfv+tUcBAlvfssTTEB33bH
RXTjobJDuW3lEbbQBN+KD9SUu02GvFF4Vs31pSf1YxHIzMuf3Q2njz58oY0kmDRvR6+n9IIUQVgK
5+iJOx9E5pY7xzmEf5LpbiTt2RSuxmt2+nkin+wxF94hkgW/N6TwmbbjybN2TY3IyZ2PgdzobCj9
sG9UAwAE1peDvIpiXhgXyojU7eRnAfJKE4HrxEjs9GKdgA4SG3rsM7t/JAeiThqe4GZCvrKwnTHS
OZSz8wplTEV7VfALj5TvwK8DqOP4Qsk1F6pml/IQg0YSUJGQmuxZzTiM3ABRzf21/BUj9j3mlo7R
/QFhNnEAhHTLoJIW1fhKYrhT7vk6rMLlZtP7iyE63MEp4cghvSk9OZDauUBoUAkKwv9N2TSOBe3W
N0fVIpLg+gNmu8s1Myzl9MEDpqQFvJbG2+hTjREo9cyvfJdKLjZVpWVoaaghiZrOFwUWJsIGCyuy
aW+eF1wFP6WgXixmvX/mdkEqCyU29+DAlIb5yIABgIxNk4MSJP/9+cSZ7L6EOVJc9khsMgw1aGe9
k3QbIeM7WLXcHNnWFE+PuqORg7OvvG+jqFGyfGlGaE85lbD2+0ONTmxU3MwNhg9ngZLheiIzxxty
3R2KXDMkDEQpWJ7cIi2QSvwu0XZ/Ku5hwW8fXbUgHTClpAQbwu3HqeeHv2BkhrUbPbx3pRpu6B4L
tyGO4vfp/vlnPyT0xS5O99KX6iKpDDS3zqC9j0cheJIqIvixNvrLd/KrpQJ8nc7+B/29h444y/3I
jooRtDmtNuG2T3b4QB2oec7FS+ufXUJIEgPWtE6iPMZxMqiL1z64eL0sg2xO4QXWwoGzMCZHP89y
ibhjhsKDTffz/s4cgRgzRWAQSNlLpuvzDeHjbNUnXIz3C1NnQOBV0LF5KpCuyYeIfQDbJQpyTre1
q5KMTGHq4ksG2zSpgNNouS279WmlGOmuawLW28VxRBlW92K//l16yJglEcKbqlRuxzM0gcw1BG/O
9sp25te+Ad68Vo2dyELZYstIRhSnV2j2J6UyZd1WC1rBWHiu3gDvKgeCNtgUbeHKfm0RVo9ZBVbi
vHQWAL57hOBERoXK5MkhwqlsYZzOHzkoVyxok+UspcmVy1MQccOcB6y5xbuqt6zR+iFuKyZVGQ==</xenc:CipherValue></xenc:CipherData></xenc:EncryptedData></soapenv:Body></soapenv:Envelope>

Now the Service finishes without errors, but the result-object is null.
-> example:
result = testserviceproxy.testservicefunction();
result is null;

A: This binding is the closest you could get with ootb wcf:
        <customBinding>
            <binding name="NewBinding0">
                <textMessageEncoding messageVersion="Soap11" />
                <security defaultAlgorithmSuite="Basic128Rsa15" authenticationMode="AnonymousForCertificate"
                    includeTimestamp="false" messageProtectionOrder="EncryptBeforeSign">
                    <secureConversationBootstrap />
                </security>
                <httpTransport />
            </binding>
        </customBinding>

It produces a very similar XML with one different: It also adds a digital signature. There is no way to directly tell WCF not to add a signature. Most chances are this will not be a problem for you to send the message as is (with signature). If this is a problem you could implement a WCF custom message encoder to manually remove the signature element (and also the one out of two derived keys which is used specifically for signature).


text:
Q: Is it possible to share connection pool between two applications in same server ind odp.net I have two applications in server.Their db user is same.Their connections strings are same
Is it possible to share connection pool between two applications.
What I want to do?For example If one application opens 10 connection and they are idle,the other application use these idle connections not open new one

A: Generally speaking, each application would use it's own instantiation of the connection pool object and would not be able to share as you describe. You should manage each connection pool to draw down to the minimum number of persistent connections that are appropriate for each application when each app is idle.
You may be able to leverage Oracle's Universal Connection Pool (see here) to achieve the effect you want, if the applications can share the same defined data source. Check the documentation to see if that would work for your at specific apps.


text:
Q: Split utils.js into multiple files for intl-tel-input I've been using this plugin for my crossrider extension. The problem is the utils script is about 200kb+ and there's a limitation in crossrider.
My question, is there a way to split the utils.js into seperate files? I've checked the code but it was enclose in (function() {....}) so I can't just break them in half without messing something up.
Anyone tried to do this?
Thanks,
Kevin

A: Use the minified version of the library that is only 23Kb.
[Disclosure: I am a Crossrider employee]


text:
Q: Show $\sigma ( \tau) = \sigma ( A)$ as an alternative formulation of Borel $\sigma -$Algebra Let $(X, \tau)$ be a topological space. Let $A:=\{X -U: U \in \tau\}$ (i.e. the set containing all closed subsets) and $K$ is a set containing all compact subspaces. Show:
i) $\sigma(\tau)=\sigma(A)$
My ideas:
Let $B \in \tau$, it follows $B$ is open $\Rightarrow$ $B^{c}$ is closed and by definition $B^{c} \in A \Rightarrow \sigma(A)$ is a $\sigma-$Algebra, however, thus $^{c}-$Stable and so $(B^{c})^{c}=B \in \sigma(\tau)$. I still believe that I have not even shown the inclusion really here. All I showed was that:
$\tau \subseteq \sigma(A)$
If I can show that $ A\subseteq \sigma(\tau)$, can I immediately say that I have proved $\sigma(\tau)=\sigma(A)$?
ii) If $X$ is $\sigma-$compact (i.e. Countable union of compact spaces) Hausdorff-Space, then $\sigma(\tau)=\sigma(K)$
My ideas: Not at all sure on this one, but I'll give it a go. Since $X$ is compact and a Hausdorff space. Any compact subspace will be closed. Let $(A_{n})_{n}$ be any collection of compact subspaces in $X$ $\Rightarrow (A_{n}^{c})_{n}$ is a collection of open sets, $A_{n}^{c} \in \tau, \forall n \in \mathbb N$, and thus like in i), we prove that $\tau \subseteq \sigma(K)$
Am I on the right track. It does not feel like it. Any help would be strongly appreciated.

A: Your idea for part i) is pretty much correct. Since $\tau\subseteq \sigma(A)$, it follows that $\sigma(\tau)\subseteq \sigma(A)$, because $\sigma(\tau)$ is the smallest $\sigma$-algebra containing $\tau$.
I am not sure about your ideas for part ii) though. Since the space is Hausdorff, we know as you mentioned that every compact set is closed and therefore $K\subseteq A$. It follows that $\sigma(K)\subseteq\sigma(A)=\sigma(\tau)$. Now since $X$ is $\sigma$-compact, we can find a sequence of compact sets $C_n$ so that $X=\cup C_n$. Then if $S\in A$ is a closed set, we can write $S=\cup_n(S\cap C_n)$. Moreover every set $S\cap C_n$ is a closed subset of $C_n$, hence compact. It follows that $S\in\sigma(K)$, and therefore $A\subseteq\sigma(K)$. As in part i), this implies that $\sigma(A)\subseteq\sigma(K)$ and we're done.


text:
Q: Imagick is displaying blank images with php I installed imagick and checked to make sure the class exists etc. I can get it to count images in tiffs and other things. However, I cant get it to display an image. I am using the following code :
header('Content-type: image/JPG');

$image = new Imagick(' ur to my jpg here ');

$image->thumbnailImage(100, 100);

echo $image;

But it displalys a blank image. When I look at the HTML code produced I get this:
<html>
<body style="margin: 0px;">
<img style="-webkit-user-select: none" src=" url to this page imagechange.php">
</body>
</html>

Can anyone explain why the image is not being displayed? Above the HTML appears the image src as the PHP page that I am using and not the image.


text:
Q: $|f (z)|$ can reach its minimum value at an interior point when the minimum value is zero. Show that $|f (z)|$ can reach its minimum value at an interior point when the minimum value is zero.
Can someone provide any method to do this?
I have proved the fact $|f (z)|$ has a minimum value $m$ in $R$ which occurs on the boundary of $R$ and never in the interior.


text:
Q: how to subset a list on basis of multiple conditions in R? I have a list containing value, level, id, colorvalue, actual value, A,B, change, name and parent. I want to subset  "value" greater than 1000 at "level" = 2 only. It should subset only for level 2, there are 2,3,4 levels in list. Actually, data is in format of data tree having hierarchies, the levels are like layers starting from 2,3,4. So, what I actually want to achieve is that for level 2 only the value should be filtered on basis of conditions and other levels should remain same. So finally I should have all data from level 2,3,4 and level 2 having values > 1000 only.
list :
    [[1]]
[[1]]$value
[1] 19.48275

[[1]]$level
[1] 4

[[1]]$id
[1] "10"

[[1]]$colorValue
[1] 4244.56

[[1]]$actualvalue
[1] 4244.56

[[1]]$A
[1] 21786.25

[[1]]$B
[1] 17541.69

[[1]]$change
[1] 19.48275

[[1]]$name
[1] "HFSS"

[[1]]$parent
[1] "7"

[[2]]
[[2]]$value
[1] Inf

[[2]]$level
[1] 4

[[2]]$id
[1] "100"

Is there any possible way to achieve this?

A: We can use lapply to loop through the list and filter the list elements based on the condition in the OP's post.
lapply(lst, function(x) x[(x[["value"]] > 1000 & x[["level"]]==2)|x[["level"]]!=2])


text:
Q: Is every frame homomorphism induced by a measurable function? Let $M$ be the Lebesgue measure algebra of the unit interval $[0,1]$, i.e. equivalence classes of Lebesgue measurable sets modulo sets of measure $0$. This is a complete Boolean algebra, hence in particular a frame.
Let $\Omega(\mathbb{R})$ be the standard topology on $\mathbb{R}$. $\Omega(\mathbb{R})$ is also a frame. A frame homomorphism is a function between frames preserving arbitrary sups and finite meets (in particular, $\bot$ and $\top$).
Any measurable function $f : [0,1] \to \mathbb{R}$ induces a frame homomorphism $\Omega(\mathbb{R}) \to M$ by taking (equivalence classes of) preimages.
My question is, does every frame homomorphism $F : \Omega(\mathbb{R}) \to M$ arise from a measurable map $f : [0,1] \to \mathbb{R}$?