text:
Q: Changing aws credentials in hadoop configuration for pyspark during runtime after initialization of spark context I've looked around on Stack Overflow for solutions to related problem, but it seems that this one is fairly unique. For context, I need to refresh AWS security credentials every hour due to company procedures, and I'm struggling to add the new refreshed security credentials to spark. Everything works fine in the first hour (I can access and read tables from s3, etc), but I'm unable to successfully change my aws credentials after the first hour is up and the credentials are refreshed.
Once I refresh my aws credentials, here is the code that I'm using to update spark to make them use the new aws credentials:
sc = spark.sparkContext

def getAWSKeys(profile):
   awsCreds = {}
   Config = ConfigParser.ConfigParser()
   Config.read(os.path.join(os.getenv("HOME"), '.aws', 'credentials'))
   if profile in Config.sections():
       awsCreds["aws_access_key_id"] = Config.get(
           profile, "aws_access_key_id")
       awsCreds["aws_secret_access_key"] = Config.get(
           profile, "aws_secret_access_key")
       awsCreds["aws_session_token"] = Config.get(
           profile, "aws_session_token")
   return awsCreds

awsKeys = getAWSKeys(profile)
sc._jsc.hadoopConfiguration().set("fs.s3.awsAccessKeyId",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3.awsSecretAccessKey",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3.session.token",
                                 awsKeys["aws_session_token"])
sc._jsc.hadoopConfiguration().set("fs.s3.enableServerSideEncryption", "true")
sc._jsc.hadoopConfiguration().set("fs.s3.access.key",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3.secret.key",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3.endpoint",
                                 "s3.us-east-1.amazonaws.com")

sc._jsc.hadoopConfiguration().set("fs.s3a.awsAccessKeyId",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3a.awsSecretAccessKey",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3a.session.token",
                                 awsKeys["aws_session_token"])
sc._jsc.hadoopConfiguration().set("fs.s3a.enableServerSideEncryption", "true")
sc._jsc.hadoopConfiguration().set("fs.s3a.access.key",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3a.secret.key",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3a.endpoint",
                                 "s3.us-east-1.amazonaws.com")

sc._jsc.hadoopConfiguration().set("fs.s3n.awsAccessKeyId",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3n.awsSecretAccessKey",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3n.session.token",
                                 awsKeys["aws_session_token"])
sc._jsc.hadoopConfiguration().set("fs.s3n.enableServerSideEncryption", "true")
sc._jsc.hadoopConfiguration().set("fs.s3n.access.key",
                                 awsKeys["aws_access_key_id"])
sc._jsc.hadoopConfiguration().set("fs.s3n.secret.key",
                                 awsKeys["aws_secret_access_key"])
sc._jsc.hadoopConfiguration().set("fs.s3n.endpoint",
                                 "s3.us-east-1.amazonaws.com")

sc.setSystemProperty("com.amazonaws.services.s3.enableV4", "true")
sc.setSystemProperty("com.amazonaws.services.s3n.enableV4", "true")
sc.setSystemProperty("com.amazonaws.services.s3a.enableV4", "true")

# sc._jsc.hadoopConfiguration().set("fs.s3.aws.credentials.provider",
#                                  "org.apache.hadoop.fs.s3.TemporaryAWSCredentialsProvider")

os.environ['AWS_ACCESS_KEY_ID'] = awsKeys["aws_access_key_id"]
os.environ['AWS_SECRET_ACCESS_KEY'] = awsKeys["aws_secret_access_key"]
os.environ['AWS_SESSION_TOKEN'] = awsKeys["aws_session_token"]

I've attempted to be exhaustive in my approach, but sadly nothing has worked. The error that I get is:
Py4JJavaError                             Traceback (most recent call last)
<ipython-input-57-674174eca978> in <module>()
      3 table = (
      4     spark.read.option("delimiter", "|")
----> 5     .csv(f"s3n://{s3_path}/{file1}", header = True, inferSchema=True)
      6     .select("col1", "col2", "col3", "col4")
      7 )

/usr/lib/spark/python/pyspark/sql/readwriter.py in csv(self, path, schema, sep, encoding, quote, escape, comment, header, inferSchema, ignoreLeadingWhiteSpace, ignoreTrailingWhiteSpace, nullValue, nanValue, positiveInf, negativeInf, dateFormat, timestampFormat, maxColumns, maxCharsPerColumn, maxMalformedLogPerPartition, mode, columnNameOfCorruptRecord, multiLine)
    408         if isinstance(path, basestring):
    409             path = [path]
--> 410         return self._df(self._jreader.csv(self._spark._sc._jvm.PythonUtils.toSeq(path)))
    411
    412     @since(1.5)

/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/java_gateway.py in __call__(self, *args)
   1131         answer = self.gateway_client.send_command(command)
   1132         return_value = get_return_value(
-> 1133             answer, self.gateway_client, self.target_id, self.name)
   1134
   1135         for temp_arg in temp_args:

/usr/lib/spark/python/pyspark/sql/utils.py in deco(*a, **kw)
     61     def deco(*a, **kw):
     62         try:
---> 63             return f(*a, **kw)
     64         except py4j.protocol.Py4JJavaError as e:
     65             s = e.java_exception.toString()

/usr/lib/spark/python/lib/py4j-0.10.4-src.zip/py4j/protocol.py in get_return_value(answer, gateway_client, target_id, name)
    317                 raise Py4JJavaError(
    318                     "An error occurred while calling {0}{1}{2}.\n".
--> 319                     format(target_id, ".", name), value)
    320             else:
    321                 raise Py4JError(

Py4JJavaError: An error occurred while calling o12923.csv.
: com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.model.AmazonS3Exception: Bad Request (Service: Amazon S3; Status Code: 400; Error Code: 400 Bad Request; Request ID: 9A4F6DDEA3BD8AA6), S3 Extended Request ID: xg9ZiPjfV3h4rGgs5emsUiWl8xQdv0OMhK/91qdAs/iIvapWgIlWh9m1qLTGj3ODFM9MtEnuueg=
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.handleErrorResponse(AmazonHttpClient.java:1588)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1258)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1030)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.doExecute(AmazonHttpClient.java:742)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeWithTimer(AmazonHttpClient.java:716)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.execute(AmazonHttpClient.java:699)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutor.access$500(AmazonHttpClient.java:667)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4169)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4116)
    at com.amazon.ws.emr.hadoop.fs.shaded.com.amazonaws.services.s3.AmazonS3Client.getObjectMetadata(AmazonS3Client.java:1237)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.call.GetObjectMetadataCall.perform(GetObjectMetadataCall.java:24)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.call.GetObjectMetadataCall.perform(GetObjectMetadataCall.java:10)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.executor.GlobalS3Executor.execute(GlobalS3Executor.java:82)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.invoke(AmazonS3LiteClient.java:176)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.AmazonS3LiteClient.getObjectMetadata(AmazonS3LiteClient.java:94)
    at com.amazon.ws.emr.hadoop.fs.s3.lite.AbstractAmazonS3Lite.getObjectMetadata(AbstractAmazonS3Lite.java:39)
    at com.amazon.ws.emr.hadoop.fs.s3n.Jets3tNativeFileSystemStore.retrieveMetadata(Jets3tNativeFileSystemStore.java:211)
    at sun.reflect.GeneratedMethodAccessor42.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invokeMethod(RetryInvocationHandler.java:191)
    at org.apache.hadoop.io.retry.RetryInvocationHandler.invoke(RetryInvocationHandler.java:102)
    at com.sun.proxy.$Proxy36.retrieveMetadata(Unknown Source)
    at com.amazon.ws.emr.hadoop.fs.s3n.S3NativeFileSystem.getFileStatus(S3NativeFileSystem.java:768)
    at org.apache.hadoop.fs.FileSystem.exists(FileSystem.java:1430)
    at com.amazon.ws.emr.hadoop.fs.EmrFileSystem.exists(EmrFileSystem.java:311)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:359)
    at org.apache.spark.sql.execution.datasources.DataSource$$anonfun$14.apply(DataSource.scala:348)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.TraversableLike$$anonfun$flatMap$1.apply(TraversableLike.scala:241)
    at scala.collection.immutable.List.foreach(List.scala:381)
    at scala.collection.TraversableLike$class.flatMap(TraversableLike.scala:241)
    at scala.collection.immutable.List.flatMap(List.scala:344)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:348)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:178)
    at org.apache.spark.sql.DataFrameReader.csv(DataFrameReader.scala:533)
    at sun.reflect.GeneratedMethodAccessor118.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:357)
    at py4j.Gateway.invoke(Gateway.java:280)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.GatewayConnection.run(GatewayConnection.java:214)
    at java.lang.Thread.run(Thread.java:748)

To reiterate, everything works fine in the first hour, but I get the 400 Bad Request error when I refresh the aws credentials. I've attempted to add these new aws credentials to spark, but nothing that I've tried has worked.

A: I can't see an easy way of doing this, as those credentials get bonded to the filesystem and then frozen.
If I were trying to do this, I'd write my own implementation of AWSCredentialsProvider which provides credentials for AWS calls. the default chain is something like: spark config, env vars, GET request to EC2 metadata service. You could add a new one which somehow picked up new values. You'd need to come up with a way of propagating the new session credentials to every host in the cluster though...hard work
The other thing is to know that AWS Assumed Roles have had their max life bumped up from 1 hour to 12 hours, so if you can get your IT team to increase the role you get assigned to 12 hours, you may just be able to get through the day.
Try that first.
ps: CSV "inferSchema=true" means "read through the entire CSV file once just to work out the schema". Avoid

A: Stumbled on this one recently; after some digging in the hadoop-aws java code, found out:

*

*there is a cache (cache entry: URI, hadoop conf) of credentials provider that somehow does not work; when changing the hadoop conf (to change credentials) and reading a new file, it uses the provider cache entry when it shouldn't, hence using deprecated credentials

*there is a fs.<scheme>.impl.disable.cache (in our case, scheme=s3a) to disable this cache; this will instantiate a new credentials provider everytime, but at least you'll be able to create one with the new credentials


text:
Q: k=Fold Cross Validation Issues I am trying to do a k=fold cross-validation on a polynomial regression. Unfortunately, I am getting an MSE that is vastly different from the MSE I would get if I were to just manually change the degrees in the code. Below is my code:
Validation Approach
# Polynomial Using sales, discount and quantity as dependent variables (degree = 2)

set.seed(123)
train_index <- sample(x = 1:nrow(superstore), size=floor(nrow(superstore)/2))
train_df <- superstore[train_index, ]
test_df <- superstore[-train_index, ]

mod2 <- lm(profit ~ poly(sales, discount, quantity, degree = 2), data = train_df)

mse_train2 <- mean(mod2$residuals^2)

pred2 <- predict(object=mod2, type = "response", newdata = test_df)
mse_test2 <- mean((test_df$profit - pred2)^2)
mse_test2
mean((pred2-test_df$profit)^2)

K-Fold Cross Validation (k=10)
mse_vec <- rep(0, 10)
for (i in 1:10) {
  mod_i <- lm(profit ~ poly(sales, discount, quantity, degree = i), data = train_df)
  pred_i <- predict(object = mod_i, type = "response", newdata = test_df)
  mse_vec[i] <- mean((pred_i - test_df$profit)^2)
}

tibble(degree = 1:10,
       mse = mse_vec) %>%
  ggplot(aes(degree, mse)) +
  geom_point() +
  geom_line()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spring JPA Repository query for JSON_CONTAINS A working query:
SELECT * from session WHERE JSON_CONTAINS(old_callback_codes,'"OLD-CODE"')

This is what I have tried with a Spring Repository
@Query(nativeQuery = true, value = "SELECT * from session WHERE JSON_CONTAINS(old_callback_codes,?1)")
which produces:
SELECT * from session WHERE JSON_CONTAINS(old_callback_codes,'OLD-CODE')

Any idea how to get the extra quotation marks inserted? I have tried a few ideas but cannot get it.


text:
Q: Swipe event preventing navigation My mobile page displays an image that is larger than the screen, so the user needs to swipe to the right to see the entire thing (as intended).  I want to put in an event that hides the navigation div when the user swipes:

Swipe

This works, except swiping no longer moves the image/view.  I'm testing on an iphone, although I want it to work cross-platform.
EDIT:
I tested by just having this:

And the image still won't navigate around, so the problem isn't in the remove vs hide or relevant to the divs themselves.

A: The problem is you are removing the element from DOM with
$('#arrow').remove().
What you need to do is
$('#arrow').hide()

A: I had this in the head:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">

Removing the first link fixed the problem.  If anyone would like to explain why as an answer, I'd be happy to accept it.


text:
Q: Probability of no matching pairs of shoes There are 3 different pairs ( i.e. 6 units say aa, bb, cc) of shoes in a lot. Now three person come and pick the shoes randomly (each get 2 units). Let p be the probability that no one is able to wear shoes (i.e. no one gets a correct pair) , then the value of $\frac{13p}{4-p}$ is?

A: The probability for the first person to pick a bad pair is $\frac 45$ (only one out of five shoes is a good second pick).
After this there is one valid pair left. The probability that the person to pick the left shoe of this pair also picks the right shoe, is $\frac 13$. Hence $p=\frac45\cdot\frac23=\frac{8}{15}$. I hope you can figure out the rest.

A: We use a technique that is definitely overkill for this problem, the Principle of Inclusion/Exclusion. But the idea might be useful for a larger problem, say $5$ people and $5$ pairs of shoes.
Let our people be P, Q, and R. There are $\binom{6}{2}$ ways for P to pick two shoes. And there are $\binom{3}{1}$ ways to pick a matching pair. So the probability that P picks a matching pair is $\frac{\binom{3}{1}}{\binom{6}{2}}$.
This is $\frac{1}{5}$.
If we find the sum $\frac{1}{5}+\frac{1}{5}+\frac{1}{5}$, we will have counted twice the probability P and Q both choose a matching pair, also the same for Q and R, also for P and R. Given that P chose a matching pair, the probability Q does is $\frac{\binom{2}{1}}{\binom{4}{2}}=\frac{1}{3}$.
So the probability P and Q choose a matching pair is $\frac{15}{5}\cdot\frac{1}{3}$. We subtract $3$ times this from $\frac{3}{5}$.
We have subtracted too much. We must add back the probability they all choose a matching pair, which is $\frac{1}{5}\cdot\frac{1}{3}$.
So the probability there is at least one person with a matching pair of shoes is
$$3\cdot\frac{1}{5}-3\cdot \frac{1}{5}\cdot \frac{1}{3}+1\cdot\frac{1}{5}\cdot\frac{1}{3}.$$
This simplifies to $\frac{7}{15}$.
So the probability $p$ of no match is $1-\frac{7}{15}$.


text:
Q: Build output of SpiderMonkey under Windows I built SpiderMonkey 60 under Windows (VS2017) according to the documentation, using
../configure --enable-nspr-build followed by mozmake.
In the output folder (dist\bin) I could see 5 DLLs created:
mozglue.dll, mozjs-60.dll, nspr4.dll, plc4.dll, plds4.dll
In order to run the SpiderMonkey Hello World sample I linked my C++ program with mozjs-60.lib and had to copy over to my program location the following DLLs: mozglue.dll, mozjs-60.dll, nspr4.dll
It seems that plc4.dll, plds4.dll are not needed for the program to run and execute scripts.
I could not find any documentation about what is the purpose of each one of the DLLs. Do I need all 5 DLLs? what is the purpose of each one?

A: Quoting from NSPR archived release notes for an old version I found this:

The plc (Portable Library C) library is a separate library from the
  core nspr. You do not need to use plc if you just want to use the core
  nspr functions. The plc library currently contains thread-safe string
  functions and functions for processing command-line options.
The plds (Portable Library Data Structures) library supports data
  structures such as arenas and hash tables. It is important to note
  that services of plds are not thread-safe. To use these services in a
  multi-threaded environment, clients have to implement their own
  thread-safe access, by acquiring locks/monitors, for example.

It sounds like they are unused unless specifically loaded by your application.
It seems it would be safe to not distribute these if you don't need them.


text:
Q: Colorize a photo with PHP/GD Let's say I have some original jpg image and I want to add red with 50% opacity over the image and display it on the page, how it's done with GD? Please just point me in the right direction, my googling and searching didn't give me much results, or maybe I don't know what I'm searching for because english isn't my 1st language.
Example from photoshop:

A: Well, you could either draw a rectangle and
$red = imagecolorallocatealpha($image, 255, 0, 0, 63);

Or you could use the PHP Image filters,
imagefilter($image, IMG_FILTER_COLORIZE, 127, 0, 0);

// didn't test the color though


text:
Q: Symfony 2 Form Create user and add Group I want to create a form to add a user:
$builder->add('firstname', 'text', array(
                    'required' => 'required'
                ))
                ->add('middlename')
                ->add('lastname')
                ->add('email', 'email')
                ->add('isActive');

but I want to add also one group.
I have a entity "Group" and a form "GroupType".
But how to add a choice with all my groups to select one or multiple?
I tried:
->add('groups', 'choice' )

but getting this error:
Notice: Object of class Doctrine\Common\Collections\ArrayCollection could not be converted to int in /vendor/symfony/symfony/src/Symfony/Component/Form/Extension/Core/ChoiceList/ChoiceList.php line 457

How to fix this?

A: To create a choice field populated with all the Group objects from the database, use an 'entity' field. To enable multiple selection (1+ choices) use the 'multiple' option. For example:
$builder->add('groups', 'entity', array(
    'class' => 'YourBundle:Group',
    'property' => 'name',
    'multiple' => true,
));

The value of the 'property' option determines which Group field is displayed. If you need to order the objects in the choice element or display a subset of the objects, use the 'query_builder' option to load the choice using a custom query. For example:
use Doctrine\ORM\EntityRepository;
// ...

$builder->add('groups', 'entity', array(
    'class' => 'YourBundle:Group',
    'property' => 'name',
    'multiple' => true,
    'query_builder' => function(EntityRepository $er) {
        return $er->createQueryBuilder('g')
                  ->orderBy('g.name', 'ASC');
    },
));

See entity Field Type in the Symfony2 documentation.


text:
Q: viewDidDisappear not called I work on an application, where I have a problem with my view[Will/Did]Disappear methods not being fired when returning to the app.
The case is, I have UINavigationController, which has two view controllers pushed on it. When the user presses the home button, the user is logged out. When he later returns to the app, the following (simplified) code is run in my AppDelegate:
- (void)applicationDidBecomeActive:(UIApplication *)application
{
    [(UINavigationController *)self.window.rootViewController popToRootViewControllerAnimated:NO];
    [self.window.rootViewController presentModalViewController:loginViewController animated:NO];
}

When I pop off the view controllers on my navigation controller stack, I would expect the view[will|did]disappear methods to be called. However, this is not the case, since they are (apparently) not on the screen anymore when iOS are going to fire these methods. It seems that the modal view controller has taken over.
If I do not present the modal view controller, the view[will|did]disappear methods are called as expected.
My question is: If I want the view[will|did]disappear methods to be called, how can I then structure my code? Is there a better place to present my modal loginViewController?
Edit:
In order to show my problems more clearly, I have created a very simple test project here: https://github.com/JohanVase/ModalViewCauseMissingViewDisappearCalls. Please try a couple of times to follow the instructions in the app, and see that I do not get my "resources" released in my viewWillDisappear method.

A: I finally asked Apple Technical support the same question. They concluded that this was a bug in iOS, so I have filed a bug report to Apple. The same bug seems to appear in iOS 6 and in the latest iOS 7 (Beta 5).
Apple Technical Support suggested the following:

As a workaround, you can move your cleanup code to a separate method
  which the AppDelegate would then invoke on the navigation controller's
  top view controller, before it pops the entire navigation stack.

However, I think this exposes too much of my details in the view controller, so I chose to implement it using willMoveToParentViewController: instead. This method is called when the view controller is removed from its parent, and it is called properly.


text:
Q: How does Malcolm Merlyn fake death? At the end of season 1, Oliver Queen the Arrow has apparently killed Malcolm Merlyn by driving his arrow into Merlyn's chest:

Oliver managed to stab Malcolm through the chest with one of
  Malcolm's arrows, by stabbing himself through his shoulder. Oliver
  rose from the ground, and after receiving confirmation from Felicity
  that the device was disarmed, told Malcolm that his plan had failed.
  Injured, Malcolm revealed he had a second device stationed in the
  Glades. Believing he had won, Malcolm fell on his side and succumbed
  to his apparent demise.
Despite everyone's assumptions, Malcolm had in fact survived his brush
  with death

I don't think how anyone can cheat death at this point. But Malcolm Merlyn does! And in addition to death, Malcolm Merlyn also cheats the Arrow into believing that he is really dead.
How is this even possible?

A: According to this article he used his influence to have the coroners help him fake his death:

Despite everyone's assumptions, Malcolm had in fact survived his brush with death, and had coroners make the police believe he was dead and had left Starling City. However he still had associates in the D.A.'s office including someone close to A.D.A. Adam Donner.

I don't believe the show offers much explanation beyond that.


text:
Q: Hibernate: cleaning up sessions Suppose I have the following:
public class DAOFactory {
    @Inject private final SessionFactory factory;
    private final ThreadLocal<Session> session = new ThreadLocal<>();

    // In a nutshell: create an AbstractDAO associated with the session object held by the ThreadLocal above
    public <T> AbstractDAO<T> createObject(Class<T> objectClass) { ... }
}

The problem that I have is that these sessions need to be closed, and only the thread creating the DAO from createObject() can do that.  Clearly, AbstractDAO cannot have a close routine, since the same Session can be associated with multiple AbstractDAO objects, so DAOFactory has to shoulder the burden of closing sessions.  Still, there is a risk of dangling Sessions: if the thread creating the AbstractDAO no longer exists, how can the associated Session be closed?
One approach I have is to have a cleanup method as follows:
public class DAOFactory {
    // createObject() uses Thread.getCurrentThread.getId() and sessionMap.computeIfAbsent()
    private final ConcurrentMap<Long, Session> sessionMap = new ConcurrentHashMap<>();

    public void cleanup() {
        for (Session session : sessionMap.values()) {
            session.close();
        }
        sessionMap.clear();
    }
}

The question is "how safe is this approach", "is this a good idea", and "should this be done"?  If not, what's a good alternative?
Note that DAOFactory is largely created with some kind of testing situation in mind: one thread starts a test run and creates a DAOFactory, and it may spawn other threads that uses it.  The thread creating DAOFactory will always outlast any threads that it spawns, and will always be the one calling cleanup() at the end of a test.

A: Manual Session management is not a good idea. Hibernate already offers a SPI, so that you don't have to do it yourself.
I suggest you start using Spring transaction management, which also offers automatic session management as well.


text:
Q: Missing disk space after upgrade from 11.04 to 11.10. How come? I have a problem with my disk space on Ubuntu.
I'll say some facts:

*

*When I installed Ubuntu, I told Ubuntu to take 25GB of space.

*I installed Ubuntu on my D:\ Drive, which is NOT the drive on which is my Windows 7

*I have a dual boot ( Ubuntu and windows 7 )

*I saw that I am low in disk space today, never checked before.

*Yesterday, I updated from 11.04 to 11.10

*I heard that Ubuntu takes 700mb ( this is why I don't understand what is happening )

*My D:\ Drive has about 15GB remaining.

My questions are:

*

*What took all the 24GBs ?

*How to add space to the home folder ?

*And why does my Disk Usage Analyzer shows that there is 136.7 GB in the file system? :

Disk Usage Analyzer screenshot:

Thanks to anyone who answers :)

A: First off, you have asked 3 questions instead of one. Please do create separate questions in the future. Also, it would help you get better answers if you add more information to your questions. Now on to answering your questions,
What took all the 24 GB?
You stated in the question yourself that you allocated 25 GB for Ubuntu. So well, there you go.
How do I add more space to my home folder?
There are already a few questions on the site similar to that, you can take a look at How can I add more disk space to my home directory?
Why does Disk Usage Analyzer show there is 136.7 GB in my filesystem?
The Disk Usage Analyzer is showing the entire hard-drive. Everything when mounted in Linux falls under a single root in a tree-like structure. Hence it reports to you that the entire filesystem is 136.7GB in size. Moreover, this is the Disk Usage Analyzer, you'd have better info about the size occupied by your partitions and all with a tool like Disk Utility or  gparted  . I've attached a screenshot below to show you what I mean.


text:
Q: Adding multiple expanders event programmatically wont work I've got a problem with adding Expanded event to my Expanders. I have expanders on my Window and I want to get the effect when I expand my expander all other will go down. I write functions that let me do this and it work correct. The problem is that I have 96 expanders I don't want add 96 events for Expand and 96 events for Collapse so I thought that I can add this programmatically.
look at the code:
    private void InitExpanders()
    {
        var expanders = GetExpanders(); // List<Expander> - list of expanders
        for (int i = 0; i < expanders.Count; i++)
        {
            if (i % 6 == 1)
            {
                    expanders[i - 1].Expanded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs args)
                    {
                        DisableBigExpanders(1); // problem is here!
                    });
            }
        }
    }

this code works fine but for each expander function parameter will be 1.
Ive tried to add integer and increment it but it wont works.
    private void InitExpanders()
    {
        var expanders = GetExpanders();
        int x = 0;
        for (int i = 0; i < expanders.Count; i++)
        {
            if (i % 6 == 1)
            {
                    expanders[i - 1].Expanded += new RoutedEventHandler(delegate(object sender, RoutedEventArgs args)
                    {
                        DisableBigExpanders(x);
                    });
                    x++;
            }
        }
    }

Thanks for all replies.

A: I suspect you are finding x in the delegate is always the highest value it reached during the loop. This is due to the way the compiler instantiates the instance of the anonymous method you've defined. It looks at what captured outer variables there are around the delegate and decides whether it requires separate instances or if it can use a single instance. In this case, you have no captured outer variables; therefore, the compiler is permitted to use the same instance of the delegate and therefore the same value of x.
To get around this issue, all you need to do is add a more granular variable just before the delegate and assign it the value of x. This will work:
private void InitExpanders()
{
    var expanders = GetExpanders();
    int x = 0;
    for (int i = 0; i < expanders.Count; i++)
    {
        if (i % 6 == 1)
        {
                int y = x++;
                expanders[i - 1].Expanded += delegate
                {
                    DisableBigExpanders(y);
                };
        }
    }
}

See here for more info on the theory: http://en.csharp-online.net/ECMA-334%3A_14.5.15.4_Anonymous_method_evaluation


text:
Q: How to integrate GitHub Actions OIDC with IdentityServer 4? I'm trying to allow GitHub Actions to call my REST API that is protected with IdentityServer4. I take a look on GitHub docs about its OIDC and I understand that I can request for ID Token inside Actions. The question is how to get access token from IdentityServer4 with this ID Token so GitHub Actions can invoke my REST API?

A: For a client to get a ID-token, then a user must be involved to authorize the client so that you can get the ID/access token. (using the authorization code flow).
A better approach might be to use the client credentials flow, that is used for machine-to-machine communication and you can configure a client definition in IdentityServer that issues an access token to your GitHub action using a simple username/password (client/clientsecret). That is the simplest way to get it to work. In this flow there is no use/need for any ID-token.
see https://docs.duendesoftware.com/identityserver/v5/tokens/requesting/#machine-to-machine-communication


text:
Q: use std::vector and memory release I am using a std::vector<CvPoint> to store edges from a video clip.
std::vector<CvPoint> vPt= floodfill(cvPoint(x,y), 255,  0, iplEdgeCpy, 100);

When the edge is processed, i am calling swap method to release memory.
vector<CvPoint>().swap(myVector);

But,  the memory is still not released. It shows that the amount of memory being used by my process is increased.
Anyone can help me or give me some suggestions?

A: Depends on your OS. Under most OSes, the process doesn't give "release" freed memory, it hangs on to it in a free list so that if the process wants to allocate more memory, it already has it and doesn't have to go to the OS.
How are you measuring memory size? If you are worried about leaks, then a tool like valgrind is more useful than just looking at the amount of memory a process has.


text:
Q: Codingbat FrontBack exercise weird result I'm starting to learn to use Java.
I'm stuck on a problem in codingbat (http://codingbat.com/prob/p123384):
here is my code
public String frontBack(String str) {
 if (str.length() > 1)
  {
   char first = str.charAt(0);
   char last = str.charAt(str.length()-1);
   String middle = str.substring(1,(str.length()-1));
   return last + first + middle;
  }
 else
   return str;
 }

And here is the output:
(I can't put an image as I'm a new user)
                         Expected:       Run:
 frontBack("code") →      "eodc"        "200od"      X
 frontBack("a") →         "a"           "a"          OK
 frontBack("ab") →        "ba"          "195"        X
 frontBack("abc") →       "cba"         "196b"       X
 frontBack("") →          ""            ""           OK
 frontBack("Chocolate") → "ehocolatC"   "168hocolat" X
 frontBack("aavJ") →      "Java"        "171av"      X
 frontBack("hello") →     "oellh"       "215ell"     X

Why do I get all these fancy numbers? My solution is fairly similar to the solution provided by codingbat...

A: Java is assuming that you want to do Integer addition on your chars, then appending your string.
To force string concatenation, you could use a StringBuilder, or something like:
return "" + last + first + middle;

or
return new String(last + first + middle);


text:
Q: Setting window.location within setTimeout on Mobile Safari Within a setTimeout, I am setting the location of a newly opened window.  To avoid the pop-up blocker, the window is opened with a temporary local URL, and then location is changed to the target URL.  This works fine on all desktop browsers including Safari.
However, in Mobile Safari, the location of the new window is not updated until the user returns their focus to the originating window i.e. the temporary page is left sitting there.
This is what the relevant bit of the JavaScript/jQuery looks like:
var self = $(this);
if (self.is("a")) {
    var clickEventHandler = function(event) {
        event.preventDefault();
        if (self.attr("target")) {
            var newWindow = window.open('loading.htm',self.attr("target"));
            var externalURL=self.attr("href");
            setTimeout( function() { newWindow.location=externalURL; }, 100 );
        }
    }
    $(this).bind("click", eventHandler);
}


text:
Q: Quaternary Quadratic Forms What is a Quaternary Quadratic Form? I've looked for a definition online and cannot find a precise clear definition.
I am not taking a course. Just reading about quadratic forms.
Thank you.

A: A quaternary quadratic form is a quadratic form in 4 variables. (A binary form is one in 2 variables, a ternary in 3, etc.)

A: For positive ones see
http://www.math.rwth-aachen.de/~Gabriele.Nebe/LATTICES/nipp.html
http://www.math.rwth-aachen.de/~Gabriele.Nebe/LATTICES/nipp.html#form
http://www.math.rwth-aachen.de/~Gabriele.Nebe/LATTICES/d4to457.html
I do not know of any tables of indefinite quaternaries. The interesting examples are of this type: $$ w^2 - 2 x^2 + 3 y^2 - 6 z^2.  $$
For real irrational values of the variables, it is easy to make this add up to $0,$ just take $w=\sqrt 2, x=1, y=0,z=0.$ For integers (and so rationals) the sum cannot be $0$ unless all four of $w,x,y,z=0.$ This is simply because, for integers, $w^2 - 2 x^2 + 3 y^2 - 6 z^2 \equiv 0 \pmod 9$ means $w,x,y,z \equiv 0 \pmod 3. $ If there were any nontrivial integer expression $w^2 - 2 x^2 + 3 y^2 - 6 z^2=0,$ there would also be one with $\gcd(w,x,y,z) = 1;$ but we see that this is not possible.


text:
Q: How to store created date on clicking submit button How can I get created date  and store it to Database when I click command button.
     <p:inputText id="diff" styleClass="daysNumber" value="#{dayDiffBean.diff}">
     <f:valueChangeListener value="#{vacatioBean.vacation.balanceDay}" />
     </p:inputText>
     <h:commandButton styleClass="sndbutton1" value="#{text['employee.send']}"
                action="#{vacationBean.addVac}" />

In Bean I have
private static final long serialVersionUID = 1L;
private Date vEndDate;
private Date vStartDate;
private Date createdDate;
    private String isNobody;
Requestrelax vacation;
Employee e;
    private short balanceDay;

@EJB
VacationLocal vacations;

@ManagedProperty(value="#{loginBean.userId}")

    Integer userId;

@EJB
EmployeesLocal employees;

@PostConstruct
public void init(){
    System.out.println("0");
    vacation=new Requestrelax();
    e=employees.getEmployee(userId);
    vacation.setEmployee(e);

}

public void addVac(){
    System.out.println("1");
    System.out.println("____________" +createdDate);
    vacation.setCreatedDate(createdDate);

    vacations.addEmployeeVacation(vacation);

}

    public Integer getUserId() {
    return userId;
}

public void setUserId(Integer userId) {
    this.userId = userId;
}

public Employee getE() {
    return e;
}

public void setE(Employee e) {
    this.e = e;
}

public Requestrelax getVacation() {
    return vacation;
}

public void setVacation(Requestrelax vacation) {
    this.vacation = vacation;
}

public Date getvEndDate() {
    return vEndDate;
}

public void setvEndDate(Date vEndDate) {
    this.vEndDate = vEndDate;
}

public Date getvStartDate() {
    return vStartDate;
}

public void setvStartDate(Date vStartDate) {
    this.vStartDate = vStartDate;
}

public short getBalanceDay() {
    return balanceDay;
}

public void setBalanceDay(short balanceDay) {
    this.balanceDay = balanceDay;
}

public Date getCreatedDate() {
    return createdDate;
}

public void setCreatedDate(Date createdDate) {
    this.createdDate = createdDate;
}

 }

How can I get created date using backing bean when I try to print it on console it is show null
Any suggetions?

A: In addition to Josef E.'s answer, I would also suggest using Joda Time because of how Java Date APIs are in previous versions of Java.
Fortunately, in Java 8 this issue has been fixed.

A: Your Date object is null because it is never initialized. You need to do:
Date createdDate = new Date();

This is also what gives createdDate the actual Date that is created as its value.

On a small tangent, I would suggest using a Calendar when dealing with dates. Partly because the Date API is mostly flawed and deprecated.
Calendar is a Singleton object that can be used as following:
Calendar createdDate = Calendar.getInstance();

When creating this object it will use the current Locale and TimeZone, unless you specify otherwise.
Hope that helps!


text:
Q: Scrollview goes under status bar when using KeyboardAvoidingView If you take a look on the left of the time on the status bar, you can see part of the scrollview showing. When scrolling up i can see the scrollview with all the elements ( pickers ,textinputs etc) scrolling underneath the statusbar.

My hierarchy looks like this
        <React.Fragment>
          <SafeAreaView forceInset={true} style={{ flex: 1, backgroundColor: colors.black, zIndex: 10000 }}>

           <View style={{flex:1}}>
           <Header/> //has certain height. had to add zIndex=10000 to avoid same issue
             <KeyboardAvoidingView behavior='position'>
               <ScrollViewWithContent/>
             </KeyboardAvoidingView>
           </View>

          </SafeAreaView>
        </React.Fragment>

Are you seeing anything obviously off?

A: Adding overflow:hidden; will do the trick. However i feel like this shouldnt be happening in the first place. The original bug is a weird state where part of the scrollview shows ( the text ) and part of it doesnt ( the background )


text:
Q: performance monitor - getting current downloaded bytes I need to monitor all internet traffic and collect how many bytes was downloaded.
Im trying to use performance counter but it doesnt get the current value, instead it shows only 0. It works when i'm using previously set instance name, but when i'm trying to iterate all of them the value doesnt update
static PerformanceCounterCategory category = new PerformanceCounterCategory("Network Interface");
String[] instances = category.GetInstanceNames();
double bytes;

private void updateCounter()
{
    foreach (string name in instances)
    {
        PerformanceCounter bandwitchCounter = new PerformanceCounter("Network Interface", "Bytes Received/sec", name);

        bytes += bandwitchCounter.NextValue();
        textBox1.Text = bytes.ToString();
    }
}

now when i set the timer off, the instance name changes but not the value

A: This is a rate counter.  The first time you read a rate counter (by calling NextValue), it returns 0.  Subsequent reads will calculate the rate since the last time you called NextValue.
Since you create a new PerformanceCounter object each time, NextValue will always return 0.
You might be able to get the information you want by looking at RawValue instead.

A: I'll answer myself. as OldFart mentioned, by calling new object each time I reset the counter to 0 every time. I managed to handle this by previously creating a list of all instances and iterating them later. Like this:
List<PerformanceCounter> instancesList = new List<PerformanceCounter>();
private void InitializeCounter(string[] instances)
{

    foreach(string name in instances)
    {
        instancesList.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", name));
    }

}
private void updateCounter()
{
    foreach(PerformanceCounter counter in instancesList)
    {
        bytes += Math.Round(counter.NextValue() / 1024, 2);
        textBox1.Text = bytes.ToString();
    }
}


text:
Q: Javascript reduce() on array of objects, with entries being simple variables and array as well I'm trying to use the reduce function in order to iterate through an array of objects and to get an output summing up the data shown inside of the array of objects (a kind of duplicate remover in fact).
On data such as :
mainData = [
   {data : {name: "item1", color: "red", type: ["metal", "wood"]}, id: 1},
   {data : {name: "item2", color: "green", type: ["wood"]}, id: 2},
   {data : {name: "item3", color: "green", type: ["wood", "stone", "marble"]}, id: 3},
   {data : {name: "item4", color: "red", type: ["stone"]}, id: 4}
]

when using the function :
const getValues = (data, key) => {
    return data.reduce((acc, item) => {
        if(acc.indexOf(item.data[key]) > -1) {
            return [...acc]
        } else {
            return [...acc, item.data[key]]
        }
    }, [data[0].data[key]]) //initial value
}

It will fork fine if I call this getValues function getValues(mainData, "color") for the color key,
giving the following output : ["red", "green"], which is expected.
But if i call the function with getValues(mainData, "type"), this function will ignore most of the values from the array type value from the key type.
I tried to solve it by using a for loop limited by data["type"].length just before the if...else condition of the reduce function, like this :
const getValues = (data, key) => {
    return data.reduce((acc, item) => {
        for(let i = 0; i < item.data[key].length; i++) {
            if(acc.indexOf(item.data[key][i]) > -1) {
                return [...acc]
            } else {
                return [...acc, item.data[key][i]]
            }
        }
    }, [data[0].data[key][0]])
}

But it does not work either.
Anyone has an idea of how to solve this ?

A: you can use flatMap for that
like this

const mainData = [
   {data : {name: "item1", color: "red", type: ["metal", "wood"]}, id: 1},
   {data : {name: "item2", color: "green", type: ["wood"]}, id: 2},
   {data : {name: "item3", color: "green", type: ["wood", "stone", "marble"]}, id: 3},
   {data : {name: "item4", color: "red", type: ["stone"]}, id: 4}
]

const getValue = (data, key) => [...new Set(data.flatMap(({data}) => Array.isArray(data[key])?data[key]: [data[key]]))]

console.log(getValue(mainData, 'name'))
console.log(getValue(mainData, 'type'))

A: It maybe easier to use a Set to dedupe the values.

const mainData=[{data:{name:"item1",color:"red",type:["metal","wood"]},id:1},{data:{name:"item2",color:"green",type:["wood"]},id:2},{data:{name:"item3",color:"green",type:["wood","stone","marble"]},id:3},{data:{name:"item4",color:"red",type:["stone"]},id:4}];

// Pass in the data, and the prop you want to look at
function finder(arr, prop) {

  // Create a new set
  const set = new Set();

  // Iterate over the array of objects
  for (const obj of arr) {

    const value = obj.data[prop];

    // If `value` is an array add each value to the set
    if (Array.isArray(value)) {
      value.forEach(v => set.add(v));
    } else {

      // Otherwise just add the value
      set.add(obj.data[prop]);
    }
  }

  // Return an array from the set
  return [...set];

}

console.log(finder(mainData, 'color'));
console.log(finder(mainData, 'type'));
console.log(finder(mainData, 'name'));

A: *

*.flatMap() the first layer searching for keyA ("data"). Each data:{...} object is converted into an array of pairs:
[["name","item1"],["color","red"],["type",["metal","wood"]],...];

*Another .flatMap() iterates through the array of pairs and returns a value when it gets a match with keyB. Everything else is returned as an empty array that will result in nothing since .flatMap() flattens it's returns.
([k, v]) => k === keyB ? v :[])

*Finally, the return of both flatMap()s are made into a Set() then the Set is returned as an array sans duplicates.
return [...new Set(output)];

const mainData = [
   {data : {name: "item1", color: "red", type: ["metal", "wood"]}, id: 1},
   {data : {name: "item2", color: "green", type: ["wood"]}, id: 2},
   {data : {name: "item3", color: "green", type: ["wood", "stone", "marble"]}, id: 3},
   {data : {name: "item4", color: "red", type: ["stone"]}, id: 4}
];

function compact(objArray, keyA, keyB) {
  const output = objArray.flatMap(
    obj => Object.entries(obj[keyA]).flatMap(
      ([k, v]) => k === keyB ? v :[]
    )
  );
  return [...new Set(output)];
}
console.log(compact(mainData, 'data', 'type'));
console.log(compact(mainData, 'data', 'color'));
console.log(compact(mainData, 'data', 'name'));


text:
Q: How to implement websocket++ ping handler? I'm trying to detect lost connections that closed without sending the close frame by sending pings on a websocket++ application.
I'm having trouble setting up the handler.
I initially tried to set it up like how the handlers are setup with the broadcast_server example:
m_server.set_ping_handler(bind(&broadcast_server::on_m_server_ping,this,::_1,::_2));

That gives this error:

note: candidate is:
websocketpp/endpoint.hpp:240:10: note: void websocketpp::endpoint::set_ping_handler(websocketpp::ping_handler) [with connection = websocketpp::connection; config = websocketpp::config::asio_tls_client; websocketpp::ping_handler = std::function, std::basic_string)>]
void set_ping_handler(ping_handler h) {

I thought that setting up a typedef like with this problem would solve it, but putting it outside the class broadcast_server makes it impossible to access m_server.
How can this handler be properly implemented?
Includes & flags
Boost 1.54
#include <websocketpp/config/asio.hpp>
#include <websocketpp/server.hpp>
#include <websocketpp/common/thread.hpp>
typedef websocketpp::server<websocketpp::config::asio_tls> server;

flags
-std=c++0x -I ~/broadcast_server -D_WEBSOCKETPP_CPP11_STL_
 -D_WEBSOCKETPP_NO_CPP11_REGEX_ -lboost_regex -lboost_system
 -lssl -lcrypto -pthread -lboost_thread

typedef
typedef websocketpp::lib::function<bool(connection_hdl,std::string)> ping_handler;

A: Solving quite easy. First, the definition in websocket/connection.hpp:
/// The type and function signature of a ping handler
/**
 * The ping handler is called when the connection receives a WebSocket ping
 * control frame. The string argument contains the ping payload. The payload is
 * a binary string up to 126 bytes in length. The ping handler returns a bool,
 * true if a pong response should be sent, false if the pong response should be
 * suppressed.
 */
typedef lib::function<bool(connection_hdl,std::string)> ping_handler;

gives the basic idea that function must have the definition:
bool on_ping(connection_hdl hdl, std::string s)
{
  /* Do something */
  return true;
}

Now everything comes to the right place:
m_server.set_ping_handler(bind(&broadcast_server::on_ping,this,::_1,::_2));

The complete modified example source looks like:
#include <websocketpp/config/asio_no_tls.hpp>

#include <websocketpp/server.hpp>

#include <iostream>

/*#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/condition_variable.hpp>*/
#include <websocketpp/common/thread.hpp>

typedef websocketpp::server<websocketpp::config::asio> server;

using websocketpp::connection_hdl;
using websocketpp::lib::placeholders::_1;
using websocketpp::lib::placeholders::_2;
using websocketpp::lib::bind;

using websocketpp::lib::thread;
using websocketpp::lib::mutex;
using websocketpp::lib::unique_lock;
using websocketpp::lib::condition_variable;

/* on_open insert connection_hdl into channel
 * on_close remove connection_hdl from channel
 * on_message queue send to all channels
 */

enum action_type {
    SUBSCRIBE,
    UNSUBSCRIBE,
    MESSAGE
};

struct action {
    action(action_type t, connection_hdl h) : type(t), hdl(h) {}
    action(action_type t, connection_hdl h, server::message_ptr m)
      : type(t), hdl(h), msg(m) {}

    action_type type;
    websocketpp::connection_hdl hdl;
    server::message_ptr msg;
};

class broadcast_server {
public:
    broadcast_server() {
        // Initialize Asio Transport
        m_server.init_asio();

        // Register handler callbacks
        m_server.set_open_handler(bind(&broadcast_server::on_open,this,::_1));
        m_server.set_close_handler(bind(&broadcast_server::on_close,this,::_1));
        m_server.set_message_handler(bind(&broadcast_server::on_message,this,::_1,::_2));
        m_server.set_ping_handler(bind(&broadcast_server::on_ping,this,::_1,::_2));
    }

    void run(uint16_t port) {
        // listen on specified port
        m_server.listen(port);

        // Start the server accept loop
        m_server.start_accept();

        // Start the ASIO io_service run loop
        try {
            m_server.run();
        } catch (const std::exception & e) {
            std::cout << e.what() << std::endl;
        } catch (websocketpp::lib::error_code e) {
            std::cout << e.message() << std::endl;
        } catch (...) {
            std::cout << "other exception" << std::endl;
        }
    }

    void on_open(connection_hdl hdl) {
        unique_lock<mutex> lock(m_action_lock);
        //std::cout << "on_open" << std::endl;
        m_actions.push(action(SUBSCRIBE,hdl));
        lock.unlock();
        m_action_cond.notify_one();
    }

    void on_close(connection_hdl hdl) {
        unique_lock<mutex> lock(m_action_lock);
        //std::cout << "on_close" << std::endl;
        m_actions.push(action(UNSUBSCRIBE,hdl));
        lock.unlock();
        m_action_cond.notify_one();
    }

    void on_message(connection_hdl hdl, server::message_ptr msg) {
        // queue message up for sending by processing thread
        unique_lock<mutex> lock(m_action_lock);
        //std::cout << "on_message" << std::endl;
        m_actions.push(action(MESSAGE,hdl,msg));
        lock.unlock();
        m_action_cond.notify_one();
    }

    bool on_ping(connection_hdl hdl, std::string s)
    {
      /* Do something */
      return true;
    }

    void process_messages() {
        while(1) {
            unique_lock<mutex> lock(m_action_lock);

            while(m_actions.empty()) {
                m_action_cond.wait(lock);
            }

            action a = m_actions.front();
            m_actions.pop();

            lock.unlock();

            if (a.type == SUBSCRIBE) {
                unique_lock<mutex> con_lock(m_connection_lock);
                m_connections.insert(a.hdl);
            } else if (a.type == UNSUBSCRIBE) {
                unique_lock<mutex> con_lock(m_connection_lock);
                m_connections.erase(a.hdl);
            } else if (a.type == MESSAGE) {
                unique_lock<mutex> con_lock(m_connection_lock);

                con_list::iterator it;
                for (it = m_connections.begin(); it != m_connections.end(); ++it) {
                    m_server.send(*it,a.msg);
                }
            } else {
                // undefined.
            }
        }
    }
private:
    typedef std::set<connection_hdl,std::owner_less<connection_hdl>> con_list;

    server m_server;
    con_list m_connections;
    std::queue<action> m_actions;

    mutex m_action_lock;
    mutex m_connection_lock;
    condition_variable m_action_cond;
};

int main() {
    try {
    broadcast_server server_instance;

    // Start a thread to run the processing loop
    thread t(bind(&broadcast_server::process_messages,&server_instance));

    // Run the asio loop with the main thread
    server_instance.run(9002);

    t.join();

    } catch (std::exception & e) {
        std::cout << e.what() << std::endl;
    }
}


text:
Q: Mixing european numbers and units with persian text I am working on language mutation of frontend of our app for Iranian market, but currently we got stuck with issue with mixing europian numerals and units with persian texts. For example our desired format for one text is:
Result: <value>s (e.g. Result: 50s)

But when I try to compose this string in javascript, number 50 is before text (after in persian language) like this
50 :persiantext s

Is there any solution how to mix these things together, or it doesn't even make any sense to mix it and it all should be in persian?
Thank you for all help/suggestions.

A: Use placeholders in your text and then replace it with the number. If you have
Result: {$d}s

for english, and
{$d}s :نتیجه

for persian, then you can replace {$d} with 50 and get the correct text in both cases.
There are a few libraries, which could help replacing variables like Underscore or Lodash (though they use a slightly different syntax for the variables), see template function.

A: When concatenating mixed RTL/LTR text you should use corresponding Right-to-left and Left-to-right marks (as shown in this Java question - String concatenation containing Arabic and Western characters).
 myArabicString + "\u202A" + englishNumberAndText + "\u202C" + moreArabic

Alternatively most RTL languages have native numbers that flow RTL too. To use that approach you will need to write own code to replace each individual digits - similar to code in convert numbers from arabic to english.
Mixing in Latin punctuation like ":" and "!" need to be done carefully - you may need to wrap it to RTL/LTR marks - but make sure to review results with people who actually know how text should look like.
Side note: you may want to check out JavaScript equivalent to printf/string.format if you need a lot of formatting.


text:
Q: `webkit-overflow-scrolling: touch;` creates bouncing on iOS I need a smooth scrolling for my app, so I added webkit-overflow-scrolling: touch;.
Unfortunately, now the content bounces when I pull down the view.
Is there a fix for it or another property that I can use to have the same scrolling smooth behavior?


text:
Q: typescirpt don't understand my validation function logicallay Hello i wan't to check some object or array is empty or undefined or null
so i make a util func like this
const isEmpty = (obj: Array<any> | undefined | null | object): boolean => {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
  }
  if (!obj) return true;
  return true;
};

but look at this
      if (!isEmpty(houseData)) {
          const { GetAllHouseForSuperUser } = houseData; // ⛔ error here
      }

typescript told me
Property 'GetAllHouseForSuperUser' does not exist on type 'getAllHouseForSuperUser | undefined'.

but logically
houseData can't be undefined
how can i notice to typescript that houseData is not undefined ?

UPDATE about interface
export interface getAllHouseForSuperUser {
  GetAllHouseForSuperUser: getAllHouseForSuperUser_GetAllHouseForSuperUser;
}

export interface getAllHouseForSuperUser_GetAllHouseForSuperUser {
  __typename: 'GetAllHouseForSuperUserResponse';
  ok: boolean;
  error: string | null;
  allHouse: getAllHouseForSuperUser_GetAllHouseForSuperUser_allHouse[] | null;
}

A: TypeScript doesn't perform data flow through the function boundaries, it assumes that the signatures are accurate. That's why checks performed inside the function don't propagate outside.
There is a feature for this case, however: type guards. They can be user-defined as a functions returning special type referring to the one of their arguments. In your case, it would be written as such:
const isEmpty = (obj: Array<any> | undefined | null | object): obj is null | undefined => {
  for (const key in obj) {
    if (Object.prototype.hasOwnProperty.call(obj, key)) return false;
  }
  if (!obj) return true;
  return true;
};

Note that obj is type: it is the way to show that the boolean returned from this function has a meaning on the type level. Of course, it's up to you to check whether the implementation is correct.


text:
Q: VBScript Dictionary Error I'm stuck working on an old project created with classic ASP (VBScript).
I've found the dictionary collection type which seems to be what I need. However, it keeps telling me "This key is already associated with an element of this collection." when I try to load it from a database recordset.
Here is the code.
set objRS = objDBConn.Execute("SELECT AreaAbbrev, Area FROM tblArea WHERE CompanyID = 15")
Set areaDict = CreateObject("scripting.dictionary")
areaDict.CompareMode=vbTextCompare

WHILE NOT objRS.EOF
    Response.Write(objRS("AreaAbbrev") & " ::: " & objRS("Area") & "<br />")
    areaDict.add objRS("AreaAbbrev"), objRS("Area")
    objRS.movenext
WEND

This is the output:
00K ::: Kellogg
00G ::: Girdler

Microsoft VBScript runtime  error '800a01c9'

This key is already associated with an element of this collection

As you can see, "00G" is not the same as "00K". Can anyone tell me why this may be giving me this error?
Thanks!

A: After some further research, I found adding .Value in this line fixed the issue:
areaDict.add objRS("AreaAbbrev").Value, objRS("Area").Value


text:
Q: Is there a Ruby gem that can insert JavaScript into an existing PDF file? Are there any Ruby gems that can open an existing PDF and insert JavaScript into it?
I  found prawn-js which can insert the JavaScript, but it will not work for me because Prawn cannot open existing PDF files, it can only generate new ones.

A: There is a popular gem called WickedPDF which internally uses shell utility WkHtmlToPDF.
If you refer to the wiki, while rendering PDF, if you specify
   :disable_javascript=> false

that should help you out. Let us know, if it helped you or you need something else. Btw, are you using some charts/graphs in your PDF?


text:
Q: How can I update a static property in React component? I have a component with redux state and static property which depends on state. How can I update this static property?
import React, { Component } from 'react';
import CustomIcon from './CustomIcon';
import { connect } from 'react-redux';
import { getTranslate } from 'react-localize-redux';

class ExitButton extends Component {
  static navigationOptions = {
    drawerLabel: this.props.translate('exit'), // here
    drawerIcon: <CustomIcon name='sign-out' size={27} withoutFeedback />
  }

  render() {
    return null;
  }
}

export default connect(
  state => ({
    translate: getTranslate(state.locale)
  })
)(ExitButton);

A: You could consider creating a separate container and hooking it into the static property.
const Translator = ({ translate, text }) => translate(text)
export default connect(
  state => ({
    translate: getTranslate(state.locale)
  })
)(Translator);

And then in your ExitButton component
...
static navigationOptions = {
  drawerLabel: <Translator text='exit'>,
  drawerIcon: <CustomIcon name='sign-out' size={27} withoutFeedback />
}
...

I haven't tested this but by HOC conventions, should work.


text:
Q: Slash commands don't disappearing (nextcord) I'm developing a discord bot using nextcord.
When i'm registering slash command and deleting it later, it's also staying at discord command list.
What can I do to delete non-existent slash commands or sync actual bot's command list with discord?
P.S. All of my commands are in different cogs
I was waiting about 4 hours for registering and sync slash commands by discord but to no avail.

A: You should try kicking your bot and then inviting it back to your server. If this doesn't work, regenerate your bot's token. This should sync it back with Discord, and the command should be gone.

A: The solution is adding all servers in default_guild_ids variable
Use methods on_ready and on_guild_join
Example code:
class Bot(nextcord.ext.commands.Bot):
    async def on_ready(self):
        for guild in self.guilds:
            self.default_guild_ids.append(guild.id)

    async def on_guild_join(self, guild: nextcord.Guild):
        self.default_guild_ids.append(guild.id)


text:
Q: important points when you write any file I am writing a file which is very important for the application (Client & vendor specific). I would like to know what are the point should i consider at writting the file. Please see below a demo file writing process
public class EDIWriter {
    public final static String END_OF_ATTRIBUTE = "|";
    File file;
    BufferedWriter writer;
    public void writer(){
    try{
    file = new File("C://edifile.edi");
    writer = new BufferedWriter(new FileWriter(file));

    StringBuilder editext = new StringBuilder();
    editext.append("ISA");
    editext.append(END_OF_ATTRIBUTE);
    editext.append("00");
    editext.append(END_OF_ATTRIBUTE);

    writer.write(editext.toString());
    writer.flush();
    writer.close();
        }catch(IOException e){

            e.printStackTrace();

        }catch(Exception e){

            e.printStackTrace();
        }
    }

    public static void main(String arg[]){
        new EDIWriter().writer();
    }
}

A: One point is to be sure to close the file, even if an exception occurred. So I would suggest to add a finally block:
finally {
 try {
    if (writer != null) {
      writer.close();
    }
 } catch (IOException ioexception) {
    //log exception
 }

Another point I just remembered: As your method is public, it could be called twice (from different callers). Synchronization may help to handle this issue.

A: Yes, it is necessary to close the resources(which are all opened to parse/write) while handling the file operations. Else, you will end up with out of memory related issues.

A: maybe you should backup your original file before edit, then check the file for correctness after edit, if it's broken, restore from the backup file.
just a suggestion.

A: The most important point to consider is: Is my program working correctly and as specified? Does it pass my tests and meet all of my requirements? If not, then come here when you have a specific problem you are trying to solve. If so, then move on to the next task.

A: First,the file must exists.
    if(!file.exists()){
        file.createNewFile();
    }


text:
Q: Extract specific values surrounded by quotation marks using java I am reading an REST API in JSON format. When reading the JSON i cannot extract the leaves with JSONPath. So what i would like to do is run thru the JSON string with Java and get the values i need, they are always in the same order. This is the JSON string i need to extract values from:
{
"10516": {
    "estimated": {
        "value": 10.0,
        "text": "10.0"
    },
    "completed": {
        "value": 7.5,
        "text": "7.5"
    }
},
"10244": {
    "estimated": {
        "value": 15.5,
        "text": "15.5"
    },
    "completed": {
        "value": 7.5,
        "text": "7.5"
    }
},
"10182": {
    "estimated": {
        "value": 12.0,
        "text": "12.0"
    },
    "completed": {
        "value": 10.0,
        "text": "10.0"
    }
},
"10391": {
    "estimated": {
        "value": 16.0,
        "text": "16.0"
    },
    "completed": {
        "value": 3.0,
        "text": "3.0"
    }
},
"10183": {
    "estimated": {
        "value": 12.0,
        "text": "12.0"
    },
    "completed": {
        "value": 7.0,
        "text": "7.0"
    }
},
"10123": {
    "estimated": {
        "value": 11.5,
        "text": "11.5"
    },
    "completed": {
        "value": 5.5,
        "text": "5.5"
    }
},
"10447": {
    "estimated": {
        "value": 7.0,
        "text": "7.0"
    },
    "completed": {
        "value": 3.0,
        "text": "3.0"
    }
}}

As you can see the ID 10516 has estimated and completed, i would like to extract those values for each ID. So the output should look like this:
ID    | ESTIMATED  |  COMPLETED
10516 | 10.0       |  7.5
10244 | 15.5       |  7.5
10182 | 12.0       |  10.0

and so on..
it is important that for every ID the values are in the same row because i need to upload them to my PostgreSQL db and join this data with other data on the ID.
My idea is to coun't the values surrounded by quotation marks and get the 1st, 5th, 9th, 10th, 14th and 18th value and so on. because the JSON string is always in the same order i guess it could be done like that..
please help out and keep in mind i don't have any experience in java at all and the implementation will be done in Talend Open Studio. also see my other question that raised this question because JSONPath cannot help me: Extract leaves from JSON file with JSONpath

A:
what JSON parser will help me extract the leaves (10516,10244 etc.)?

Examples with Jackson (com.fasterxml.jackson.core:jackson-databind:2.0.6):
The quick and dirty approach:
    String json = "{\n" +
            "\"10516\": {\"estimated\": {\"value\": 10.0,\"text\": \"10.0\"},\"completed\": {\"value\": 7.5,\"text\": \"7.5\"}},\n" +
            "\"10244\": {\"estimated\": {\"value\": 15.5,\"text\": \"15.5\"},\"completed\": {\"value\": 7.5,\"text\": \"7.5\"}},\n" +
            "\"10182\": {\"estimated\": {\"value\": 12.0,\"text\": \"12.0\"},\"completed\": {\"value\": 10.0,\"text\": \"10.0\"}}\n" +
            "}";

    ObjectMapper mapper = new ObjectMapper();
    TypeReference<Map> typeRef = new TypeReference<Map>(){};
    try {
        Map<String, Object> map = mapper.readValue(json, typeRef);
        System.out.println(map);
    } catch (IOException e) {
        // log error
    }

Output:
{10516={estimated={value=10.0, text=10.0}, completed={value=7.5, text=7.5}}, 10244={estimated={value=15.5, text=15.5}, completed={value=7.5, text=7.5}}, 10182={estimated={value=12.0, text=12.0}, completed={value=10.0, text=10.0}}}

This way you can parse any JSON string. You can of course access all JSON fields as long as you cast to the corresponding type:
        Map item = (Map) map.get("10182");
        System.out.println(item);

        Map estimated = (Map) item.get("estimated");
        Double value = (Double) estimated.get("value");
        System.out.println(value);

        String text = (String) estimated.get("text");
        double newValue = value + 10;
        System.out.println("old text: "+text+", new value: "+newValue);

Output:
{estimated={value=12.0, text=12.0}, completed={value=10.0, text=10.0}}
12.0
old text: 12.0, new value: 22.0

The cleaner, better approach
Of course, a better approach would be to define some model classes like the following:
class Model {
    ModelContent estimated;
        public ModelContent getEstimated() {return estimated;}
        public void setEstimated(ModelContent estimated) { this.estimated = estimated;}
    ModelContent completed;
        public ModelContent getCompleted() {return completed;}
        public void setCompleted(ModelContent completed) { this.completed = completed;}
    public Model() {}
}

class ModelContent {
    Double value;
        public Double getValue() {return value;}
        public void setValue(Double value) { this.value = value;}
    String text;
        public String getText() {return text;}
        public void setText(String text) {this.text = text;}
    public ModelContent() {}
}

And use them as the value type for the root map:
    ObjectMapper mapper = new ObjectMapper();
    TypeReference<Map<String,Model>> typeRef = new TypeReference<Map<String,Model>>(){};
    try {
        Map<String, Model> map = mapper.readValue(json, typeRef);
        Model item = map.get("10182");
        ModelContent completed = item.getCompleted();
        Double completedValue = completed.getValue();
        System.out.println("value: "+completedValue);
    } catch (IOException e) {
        // log error
    }

Output:
value: 10.0

A: String jsonString="YOUR JSON STRING";
JSONObject mainObject=new JSONObject(jsonString);
Iterator<String> keys= mainObject.keys();
while (keys.hasNext())
    {
    String keyValue = (String)keys.next();
    JSONObject obj1 = mainObject.getJSONObject(keyValue);
    JSONObject estimatedObj = obj1.getJSONObject("estimated");
    JSONObject completedObj = obj1.getJSONObject("completed");
    System.out.print(keyvalue+"-"+estimatedObj.getString("text")+"-"+completedObj.getString("text"));
    System.out.println();
    }


text:
Q: ¿Como puedo transmitir datos de mysql a variables php? El codigo es este
<?php
  session_start();

  require 'database.php';

  if (isset($_SESSION['user_id'])) {
    $records = $conn->prepare('SELECT id, user, email, password, rank FROM users WHERE id = :id');
    $records->bindParam(':id', $_SESSION['user_id']);
    $records->execute();
    $results = $records->fetch(PDO::FETCH_ASSOC);

    $user = null;

    if (count($results) > 0) {
      $user = $results;
    }
  }
if(!empty($user)){
    $logged = true;
} else {
    $logged = false;
    header("Location: /login.php");
}

Quiero transpasar el rank de la base de datos a una variable llamada $rank. y también el usuario a otra llamada $user. Un saludo


text:
Q: How to properly end a users session? I've been working on the security of my site (PHP) and there's a ton of information to ingest. I've tried to implement security I've researched on OWASP, but one thing I'm a little nervous about, among other things, is how to handle SESSIONS when the user logs out.
Currently all I'm using is:
session_destroy();

But, I've read that I should change the XRSF token and start another SESSION so it forces the user to resubmit login credentials in-turn explicitly ending the users SESSION.
Is session_destroy() enough?
EDIT
I've downloaded michael-the-messenger, which I believe was created by Michael Brooks (Rook) which should be VERY secure, and I saw some code that I might want to use. Is this something that could safely replace the session_destroy() I'm using?
CODE
if($_SESSION['user']->isAuth())
{
    /* if they have clicked log out */
    /* this will kill the session */
    if($_POST['LogMeOut'] == 'true')
    {
        //When the user logs out the xsrf token changes.
        $tmp_xsrf = $_SESSION['user']->getXsrfToken();
        $_SESSION['user']->logout();
        $loginMessage = str_replace($tmp_xsrf, $_SESSION['user']->getXsrfToken(), $loginMessage);
        print layout('Authorization Required', $loginMessage);
    }
    else
    {
        header("Location: inbox.php");
        //user is allowed access.
    }
}
else
{
    // code goes on ....

LOGOUT
public function logout()
{
    $_SESSION['user'] = new auth();
}

Obviously $_SESSION['user'] = new auth(); reinstantiates the object which sets a private variable $auth to false.

A:
but one thing I'm a little nervous about, among other things, is how
  to handle SESSIONS when the user logs out.

According to manual:

In order to kill the session altogether, like to log the user out, the
  session id must also be unset. If a cookie is used to propagate the
  session id (default behavior), then the session cookie must be
  deleted. setcookie() may be used for that.

So, in order to safely destroy a session, we'd also erase it on the client-machine.
session_destroy() along with setcookie(session_name(), null, time() - 86400) will do that.
Apart from that,
What you are doing wrong and why:

Session storage merely uses data serialization internally.  By storing
  an object in the $_SESSION superglobal you just do
  serialize/unserialize that object on demand without even knowing it.

1) By storing an object in $_SESSION you do introduce global state. $_SESSION is a superglobal array, thus can be accessed from anywhere.
2) Even by storing an object that keeps an information about logged user, you do waste system memory. The length of object representation is always greater than a length of the strings.
But why on earth should you even care about wrapping session functionality? Well,

*

*It makes a code easy to read, maintain and test

*It adheres Single-Responsibility Principle

*It avoids global state (if properly used), you'll access session not as $_SESSION['foo'], but $session->read['foo']

*You can easily change its behaivor (say, if you decide to use DB as session storage) without even affecting another parts of your application.

*Code reuse-ability. You can use this class for another applications (or parts of it)

If you wrap all session-related functionality into a signle class, then it will turn into attractive:
$session = new SessionStorage();

$session->write( array('foo' => 'bar') );

if ( $session->isValid() === TRUE ) {

    echo $session->read('foo'); // bar

} else {

    // Session hijack. Handle here
}

// To totally destroy a session:
$session->destroy();

// if some part of your application requires a session, then just inject an instance of `SessionStorage`
// like this:
$user = new Profile($session);

// Take this implementation as example:

final class SessionStorage
{
    public function __construct()
    {
        // Don't start again if session is started:
        if ( session_id() != '' ) {
            session_start();
        }

        // Keep initial values
        $_SESSION['HTTP_USER_AGENT'] = $_SERVER['HTTP_USER_AGENT'];
        $_SESSION['REMOTE_ADDR'] = $_SERVER['REMOTE_ADDR'];
    }

    /**
     * You can prevent majority of hijacks using this method
     *
     * @return boolean TRUE if session is valid
     */
    public function isValid()
    {
        return $_SESSION['HTTP_USER_AGENT'] === $_SERVER['HTTP_USER_AGENT'] && $_SESSION['REMOTE_ADDR'] === $_SERVER['REMOTE_ADDR'] ;
    }

    public function __destruct()
    {
        session_write_close();
    }

    /**
     * Fixed session_destroy()
     *
     * @return boolean
     */
    public function destroy()
    {
        // Erase the session name on client side
        setcookie(session_name(), null, time() - 86400);

        // Erase on the server
        return session_destroy();
    }

    public function write(array $data)
    {
        foreach($data as $key => $value) {
            $_SESSION[$key] = $value;
        }
    }

    public function exists()
    {
        foreach(func_get_args() as $arg){

            if ( ! array_key_exists($arg, $_SESSION) ){
                return false;
            }
        }

        return true;
    }

    public function read($key)
    {
        if ( $this->exists($key) ){

            return $_SESSION[$key];

        } else {

            throw new RuntimeException('Cannot access non-existing var ' .$key);
        }
    }

}

A: Maybe session_unset() is what you are looking for.


text:
Q: visual studio 2010 installation problem I'm trying to install visual studio 2010.
but at the begining of installation I get this error message box:
" setup.exe has stopped working
A problem coused the program to stop working correctly. Windows will close the program and notify you if a solution is available."
and I can just click the button " close program"!
the version of my Windows is seven ultimate x86.
can anybody help me ?

A: Look for a running msiexec on your system.  Slay it and try again.


text:
Q: fastlane tools and xcode8, should I still use it? I am using fastlane tools to handle all my signing needs in Xcode 7. As I started using Xcode 8 I've been having some issues. Xcode 8 introduces a new "automatic" signing approach. I am still able to use fastlane tools by telling Xcode not to use automatic signing and by selecting the correct values that come up in the signing options when disabling the automatic check box.
I would like to start using the automatic signing option, but I am not 100% sure how to do it properly using fastlane. I believe I need to understand how to use PROVISIONING_PROFILE_SPECIFIER option?
Can anybody explain how fastlane is supposed to work with Xcode 8 automatic signing?

A: If you want to use fastlane for code signing, you should disable automatic code signing and let fastlane do its thing. You can however also enable automatic code signing and let Xcode manage the profiles for you.
You can find more information about how to use fastlane with Xcode 8 and the new Automatic code signing in the XcodeProject fastlane docs


text:
Q: Reflectivity of a glass+film
A Ti02 film of index 2.5 is placed on glass of index 1.5 to increase
the reflection in the visible. Choosing a suitable value for wavelength, how
thick a layer in microns would you want, and what reflectivity would this
give you?

My question is about the last question presented above. Precisely, i am having some trouble to understand what it means by "reflectivity", i guessed that it is the coefficiente R that points the intensity obtained from a reflection, in this case normal, so generally $r_{12}=(\frac{n_1 - n_2}{n_1 + n_2})^2$. In this case, i thought that, since we want to increase the reflection and at the same time decrease the intensity, the reflected wave need to be out of phase by pi and the reflectivity would be $|r_{10}-r_{12}|$, where 0 is the air, one is the film and two is the glass.
But, the answer is $r=(\frac{n_0 - n_1²/n_2}{n_0 + n_1²/n_2})^2$, i have no idea how does the author got this answer. Any help?


text:
Q: How to avoid Outlook security alert when reading outlook message from C# program I have a requirement of reading subject, sender address and message body of new message in my Outlook inbox from a C# program. But I am getting security alert 'A Program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this'.
By some googling I found few third party COM libraries to avoid this. But I am looking for a solution which don't require any third party COM library.

A: Try this
Tools-->Macro-->Security-->Programmatic Access
Then choose Never warn me about suspicious activity.

A: "But I am looking for a solution which don't require any third party COM library."
You won't find it. Kasper already pointed out the only solution that I know of. Redemption has been the only thing that has kept the Outlook plug-ins and code to work. I have done commercial Outlook add-ins for Franklin Covey. We explored a lot things, but Redemption was the only thing that got us over this hurdle.

A: I ran into same issue while accessing sender email address for outlook mail item. To avoid 'security alert' do not create new Application object, instead use Globals.ThisAddIn.Application to create new mailitem.
string GetSenderEmail(Outlook.MailItem item)
    {
        string emailAddress = "";
        if (item.SenderEmailType == "EX")
        {
            Outlook.MailItem tempItem = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);
            tempItem.To = item.SenderEmailAddress;
            emailAddress = tempItem.Recipients[1].AddressEntry.GetExchangeUser().PrimarySmtpAddress.Trim();

        }
        else
        {
            emailAddress = item.SenderEmailAddress.Trim();

        }

        return emailAddress;
    }

A: Sorry, I have had that annoying issue in both Outlook 2003 and Outlook 2007 add-ins, and the only solution that worked was to purchase a Redemption license. In Outlook 2007 that pesky popup should only show up if your firewall is down or your anti-virus software is outdated as far as I recall.

A: If your application is not a Outlook plug in you can look at MAPI to read data from the inbox

A: We use Advanced Security for Outlook from Mapilab for this. It is free, also for commercial use, and still keeps Outlook safe (by only allowing access from approved applications). Just apposed to previously mentioned solutions that cost either money, or may compromise security.

A: You can disable the security pop-up using Outlook's Trust Center.
Check here.


text:
Q: MySQL specific sorting of the result based on multiply 'LIKE' and better matching of the founded results I'm trying to build search engine and wondering is there a way to sort the results based on more precise matching?
I have a simple table library with the user names stored there:

userName

john hampton

smith horne

john smith junior

kevin spencer

john white smith

luke junior

alan smith junior

based on search field inputs. For example if I want to search for john smith junior I would like not only to check for the full name matching,  also  want to check for the matching part of the name. so expected result should be:

userName

john smith junior

john white smith

alan smith junior

john hampton

smith horne

luke junior

First line need to be top rated as we have three matches, second and third line have two matches and rest there is just one match, but ordered by the input field submission.
I started to build following query:
SELECT `userName`
FROM `library`
WHERE `userName` like '%john%smith%junior'
  OR `userName` like '%john%smith%'
  OR `userName` like '%john%junior%'
  OR `userName` like '%smith%junior%'
  OR `userName` like '%john%'
  OR `userName` like '%smith%'
  OR `userName` like '%junior%'
ORDER BY ???

but I blocked how to sort of the results, so my question is - is it possible to add some special clauses in ORDER BY to get results sorted as required (priority based on where clause adding order)?

*

*First all results  where '%john%smith%junior' sorted ASC

*Second all results where userName like '%john%smith%' sorted ASC

*etc.

*Last is all results where userName like '%junior%' sorted ASC

A: ...
ORDER BY (`userName` like '%john%smith%junior') * @weight1 +
         (`userName` like '%john%smith%')       * @weight2 +
         (`userName` like '%john%junior%')      * @weight3 +
         (`userName` like '%smith%junior%')     * @weight4 +
         (`userName` like '%john%')             * @weight5 +
         (`userName` like '%smith%')            * @weight6 +
         (`userName` like '%junior%')           * @weight7

Take into account that real weight of the condition is a sum of weights for it and all its subconditions.
For example, a row which matches condition like '%john%smith%' also matches like '%john%' and like '%smith%', i.e. actual weight of this pattern is @weight2 + @weight5 + @weight6.


text:
Q: CMake toolchain expressions I am trying to write a Toolchain file for a custom compiler and I am stuck at the options of the tools. I actually need a variation of the output filename to be added to a parameter in CMAKE_CXX_LINK_EXECUTABLE variable.
I found random examples on the internet on how to include some expressions, like <TARGET> and <OBJECTS> but https://cmake.org/cmake/help/latest/manual/cmake-toolchains.7.html avoids to explain them properly. What are those? Some look like variables, some like Generator expressions (https://cmake.org/cmake/help/latest/manual/cmake-generator-expressions.7.html ) , some like CMake properties.
But where are the valid ones listed? And which string operations can I do with them?

A: They are placeholders. They don't necessarily correspond to any variable or property. They are specific to rules like CMAKE_<LANG>_LINK_EXECUTABLE.
I couldn't find any documentation about them, but there's some information in the source for CXX rules.
Sources:

*

*How do CMake placeholders work?

*cmRulePlaceholderExpander::ExpandVariable

*Example of setting up RuleVariables from the source


text:
Q: MySQL: Get only objects with currently not active plan I want to create a query that gets me only those object ids, who belog to a plan that's current status is quitted (-1). This can be done via the begin field, but i don't know how to exclude past quitted plans. Of course there can be many plans and many objects. I trimmed the original structure down to this:
TABLE objects
--------------------
id, title, xid, state
1, a, 6, 1
2, b, 6, 1
3, c, 6, 1
4, d, 2, 1

TABLE plans
--------------------
xid, status, begin
6, 1, 2017
2, -1, 2017
6, -1, 2016

This query gets all objects that have a plan which status is quitted (-1).
Problem is, that this query also gets all objects ids if the quitted plan lies in the past and the current active plan ist fine.
SELECT o.id
FROM objects AS o
LEFT JOIN plans AS p ON o.xid=p.xid
WHERE p.status = -1
ORDER BY p.begin

This outputs:
1,2,3,4
But it should only output
4
I want this because in the end i want a query that deactivates (o.state=0) all objects that currently don't have an active plan.

A: You can get the current status for each xid by doing:
select p.*
from plans p
where p.begin = (select max(p2.begin) from plans p2 where p2.xid = p.xid);

You can get the objects in such plans using join, exist, or in:
select o.*
from objects o
where o.xid in (select p.xid
                from plans p
                where p.begin = (select max(p2.begin) from plans p2 where p2.xid = p.xid) and
                      p.status = -1
               );

A: You can add another filter to your existing query to filter out those that are active.
SELECT o.id
FROM objects AS o
LEFT JOIN plans AS p ON o.xid=p.xid
WHERE p.status = -1
AND p.xid NOT IN (SELECT xid FROM plans WHERE status = 1)
ORDER BY p.begin


text:
Q: How to add items to a QTreeView? What's wrong with the code below? It's creating the QTreeView, however, the view doesn't display anything, just a thin border.
I was also trying to find a way to add a widget into a specific row. I tried with a QPushButton.
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);

    QGridLayout* layout = new QGridLayout();
    ui.centralWidget->setLayout(layout);

    QTreeView* treeView = new QTreeView(this);
    treeView->setStyleSheet(R"(
        QTreeView {
            background-color: transparent;
        }
    )");

    // Create a model to hold the data
    QStandardItemModel model;

    // Set the model to the tree view
    treeView->setModel(&model);

    // Add columns to the model
    QStandardItem* column1 = new QStandardItem("Column 1");
    column1->setBackground(QBrush(Qt::red));

    model.setHorizontalHeaderItem(0, column1);
    model.setHorizontalHeaderItem(1, new QStandardItem("Column 2"));

    // Add data to the model
    for (int i = 0; i < 5; i++) {
        // Create a new row
        QList<QStandardItem*> row;

        // Create items for the row
        QStandardItem* item1 = new QStandardItem("Data " + QString::number(i));
        QStandardItem* item2 = new QStandardItem("More data " + QString::number(i));

        // Add the items to the row
        row << item1 << item2;

        // Create a push button
        QPushButton* button = new QPushButton("Button " + QString::number(i));

        // Add the button to the first column
        item1->setData(QVariant::fromValue(static_cast<void*>(button)));

        // Add the row to the model
        model.appendRow(row);
    }

    layout->addWidget(treeView);
    treeView->show();
    return;
}

A: The problem is your model destroyed after MainWindow ctor's scope finishes.
// Create a model to hold the data
    QStandardItemModel model;

You can define this model as member variable (recommended) or create on heap like this auto model = new QStandardItemModel;.


text:
Q: Big O-Notation complexity order I have read about the Big-O complexity order. On the internet it said the order is:

O(1) < O(log n) < O(n) < O(n log n) < O(n^2) < O(n^3) < O (2^n) < O
  (10^n)

Now I want to sort these O-Notations in their complexity order going from the lowest to the highest.
a: O(π^e n^2)
b: O(n+n^2/√n^3)
c: O((1/10^100)n!+5n^2)
d: O(25√9n)
e: O(log(n^n)

Is the order e, d, a, b correct? I am not sure where c belongs.

A: First, note that mathematically speaking, I've never heard about a properly defined order relationship on the image of the O operator, so when you're saying O(1) < O(log n), as far as I know there is no mathematical definition for it and it only means that an algorithm performing with a complexity of O(1) will be slower (for large problems) than an algorithm with a complexity of O(n).
Now to answer your question, let's simplify all expressions:
a: O(π^e n^2)           <=> O(n^2)      (a constant factor doesn't affect the nature of complexity itself although it will impact running time)
b: O(n+n^2/√n^3)        <=> O(n^2/√n^3) (eliminating a term that evolves slower than the other term)
                        <=> O(√n)       (simplifying expression)
c: O((1/10^100)n!+5n^2) <=> O(n!)       (eliminating a term that evolves slower than the other term and removing constant factors)
d: O(25√9n)             <=> O(n)        (removing constant factors)
e: O(log(n^n))          <=> O(n log(n)) (simplifying expression)

Now it becomes clear that the "order", from faster to slower, will be: b, d, e, a, c


text:
Q: Lemma from galois representation book Let $\mathcal{O}$ be a complete Noetherian local rings with residue field $k$ and suppose $A \to B$ is a surjective morphism of Noetherian local $\mathcal{O}$-algebras (with residue field $k$) with principal kernel annihilated by $m_A$ (the maximal ideal of $A$. Suppose $\rho \colon G \to \textrm{GL}_2(A)$ is a continuous representation of a profinite group $G$ such that the only matrices commuting with the image of $G$ in $\textrm{GL}_2(B)$ or $\textrm{GL}_2(k)$ are scalars. I'd like to show that similarly, $M \in \textrm{GL}_2(A)$ commutes with the image of $\rho$ if and only if $M$ is scalar. This is essentially Lemma 3.8 in "Deformations of Galois Representations" by Fernando Q. Goueva, but the proof in the book seems to contain a mistake.
Suppose $M \in \textrm{GL}_2(A)$ commutes with the image of $\rho$. Then its image $\overline{M}$ in $\textrm{GL}_2(B)$ must be a scalar by hypothesis, so $M = r + tM'$, where $r \in \textrm{GL}_2(A)$ is a scalar matrix, $t \in \textrm{GL}_2(A)$ is a scalar matrix whose diagonal entry generates $\ker(A \to B)$, and $M' \in M_2(A)$. We have
$$(r + tM')\rho(g) = \rho(g)(r + tM')$$
for all $g \in G$. Since $r$ is scalar, this implies
$$tM'\rho(g) = \rho(g)tM'$$
for all $g \in G$. Here is where the book seems to go wrong. It's claimed that this means $M'$ commutes with $\rho(g)$. But $t$ is not invertible, so this doesn't seem to follow. The book then goes on to say that the image of $M'$ in $\textrm{GL}_2(k)$ is a scalar by the hypothesis, but this again seems to be erroneous as we don't know that $M'$ is invertible. Is this salvageable?
What we can say is that
$$t(M'\rho(g) - \rho(g)M') = 0$$
for all $g \in G$. If $t = 0$, then $M$ is scalar and we're done. If not, then we can say that $M'\rho(g) - \rho(g)M'$ has entries in $m_A$ for all $g \in G$.

A: Small note: $t \notin GL_2(A)$, $t$ is a scalar matrix in $M_2(A)$ (but in fact, its determinant is zero).
Anyway, we indeed have $t(M'\rho(g)-\rho(g)M')=0$. This implies that the images of $M'$ and $\rho(g)$ in $k$ commute, because $m_A$ is the annihilator of $t$.
(In other words: let $N=M'\rho(g)-\rho(g)M'$: then $tN=0$. So no coefficient of $N$ can be invertible, so the image of $N$ in $M_2(k)$ is zero.)
It follows that the image of $M'$ in $k$ is a scalar matrix, so $M'=a+M''$, where $a \in AI_2$ and $M'' \in m_AM_2(A)$. Thus $tM'=ta$ and $r+tM'=r+ta$ is scalar.


text:
Q: Find missing values between two lists of IDs using SQL I have a large list of IDs that received a certain status (Ex: status is 'EMAIL SENT'). These should be accompanied by another row with another status (Ex: 'EMAIL OPENED').
I have both lists of IDs, a list of all of those that are EMAIL SENT and a list of all of those IDs that also received EMAIL OPENED. What is the best way, using an SQL query, to find the IDs that have EMAIL SENT but have not received EMAIL OPENED?
The IDs I am searching on are not primary keys, there can be multiple IDs in this table each with its own status.
I had though of using EXISTS but this will just give a T/F. The desired result would be a list of IDs that are found in the larger list of EMAIL SENT but not found in the smaller list of EMAIL OPENED.


text:
Q: CSS file can be intentionally changed I have been informed that that our CSS file can be intentionally changed by a bad actor on our web application. To give you a bit more context:
We are sending to our clients emails containing a link (see below) with personalized news. The 'Suggestions' site is a single page web application that lists news that are recommended to the user. The URL parameters are: lang, css, and proposals. The css is provided as URL parameter and will be loaded in addition to the default CSS.
https://somecompany.com/Suggestions/index.jsp?lang=en&css=https://www.test.com/style.css&proposals=Random Client ID //eg 12435
What type of attach is this? I am trying to find more info online in order to mitigate the issue but I am a bit lost. Can this be a "relative path overwrite" attack, or an "Unvalidated redirects" attack or "Web Parameter Tampering" attack or what else??
Than you in advance for your help

A: Most probably someone meant XSS. Someone could inject code if you do not sanitize the css GET parameter (if this is the case this is a very serious security risk), or possibly make the client machine connect to a specific server ( the one specified in the CSS var ) this could be used for DDoS (but highly unlikely) or other reasons (this is not really a big risk).
Of course the most obvious attack would be to change how your page looks - it might not seem very useful, but for example changing the "remove account" button to be 100% width 100% height covering the page and transparent might not be what you would like ?

A: "what type of attach is this?" It's a GET string. Whatever you pass to a web page via GET can be changed by the user easily. As easy as going to the URL bar at the top of the browser and changing the values there.
Conclusion, you shouldn't be passing CSS really at all, whether GET or POST. Second conclusion, if you don't want params to be user-editable (say by a bad actor) then use POST instead of GET.

A: There's two different potential issues at stake:

*

*As @n00b mentioned, if the CSS isn't properly sanitised, then (like any GET / POST / WHATEVER parameter), then it can be used to inject malicious code into the site (such as rerouting the user to a similarly styled but malicious phishing site.

*Alternately, eve if the CSS has been sanitised, it means an unfriendly user can share the link and pass in a random stylesheet - which may be used to deface the application (and hurl insults at your customers).
The other bit that worries me - your client IDs seem to be guessable. I only have to iterate through all of them to access other people's "personalized" news.