text:
Q: What are the specific security risks of this web services architecture? I need ammunition to try to promote WS-Security for a set of externally-available web services that interact directly with our production customer service application. My vision is to implement IPassword provider and authenticate with our AD store. The architecture recommendation that came down from on high is SSL, with an IP filter on the router to only allow certain IP addresses to call the web services. Access will be granted with a GUID key. No login or password required.
A key will be granted to each partner authorized to access our web services. It will be generated by us and probably emailed to them. There is no expiration policy that I'm aware of.
This feels wrong to me, but they're not buying my argument that there is no actual authentication in play here. What specific security risks are there with this architecture? Exactly what attack scenarios are possible and how easy would it be to compromise our systems? I need to be able to detail the risks, possibly even demonstrate them to our architecture team.

A: Well... there is so much that can go wrong here...
For one, the SSL server certificate only protects you against normal eavesdropping and if done correctly the identity of the server. It doesnt ensures who the client is. (Im assuming you are doing the proper security checks on the servers certificate on your client).
But that tells the server nothing about the client. To do that you need to also assign a client certificate and validate it on the server and even then this solution is still vulnerable to man in the middle attacks if not done correctly.
Going back to your configuration. If your server certificate validation is not done correctly someone could not only eavesdrop but also inject/modify the information on your communication channel (since you are not performing any signature on the message itself to verify it wasnt modified).
The IP filter is pretty weak, since most institutions have some NAT or Proxy configurations  for outside access. So pcs with outside access through the same node would show the same IP. So no "spoofing" is required... you just need to compromise any of the internal machines... like a secretary's machine (giggles).... and make the requests from there.
The IP Spoofing im not sure would be a valid attack, in this case an attacker would cause a denial of service on the client machine and then try to connect to the server forging the packets and taking advantage that the spoofed client cant respond and rst the packets to terminate the connection.
It would imply guessing the package sequence number, which is hard now days, but not impossible. from there an attacker can inject blindly whatever message he needs but in this case since the connection is not plain html but an ssl stream which involves exchange of info like keys etc, and given that the attacker cant see, since the injection is done blindly (at least unless its in the same subnet and can sniff the packets)... i doubt its possible.
Anyways... recommended configurations.
1
- Server SSL certificate with validation on the client.
- Client SSL certificate with validation on the server.
- Some sort of checksum of the message, besides the GUID token.. which i would advice to be generated each time for each session-client.
(Dont forget to distribute this certificates securely on encrypted stores pkcs12 etc otherwise this approach is susceptible to man in the middle attacks)
2
- Extend the web service soap message with the WS-Security and use client and server signature/encription with Client and Server certificates, and use timestamping services.
You can still ip bind the connections... but there would be no need... and its still weak.
On a side note, IP spoofing was used by Kevin Mitnick against Shimomura back in 1994... so it is possible and not extremely hard. I bet that depending on your servers OS version there are tools that automate most of the process already.
Id love to hear what others think. Hope this helps.

A: Your GUID/SSL method has holes.  The ability to spoof IP adresses is available and if an email is intercepted with the GUID key - You're compromised.
WS-Security is an established protocol and that means it's been studied and hammered at by security researchers and Doctorates.  These are the people to trust when implementing security measures.  Whereas home baked security almost always has critical flaws in it.

A: Depending on how you're checking IP Addresses, it is possible these could be spoofed quite easily:
http://en.wikipedia.org/wiki/IP_address_spoofing

A: That's pretty secure.  Spoofing an IP address at the router level is pretty hard and is a common security approach for banks.  By locking it down by ip adress at the router, you are pretty certain you know which organizations will be accessing your web service.
It sounds like a two factor authentication scheme, but to say that it is "air tight", I'd have to hear more about the guid key and how that is going to be implemented.  Is everyone going to use the same key, or will it be different for each person/application accessing the web service?
Their approach actually seems pretty sound.  The IP Address acts as a "user name" and the guid represents the "password" in a traditional user name / password model.  IP Address at that level of the stack are very hard to spoof, because the IP address is essentially verified by the ISP.  Spoofing an IP address on the upstream to cause a DOS might be possible for someone less experienced, but actually spoofing the IP to open between your service and a "rogue" client is extremely hard.
The most secure approach would be to combine the two by using IP filtering at the router, and force the use of a user name and password all through SSL.

A: You may be fighting a losing battle.
No security is foolproof - if you build it someone can break it. The level of security is dependent on what you are securing and the resources at hand. The proposed solution is very reasonable for many applications. Some one who has the resources to hack it has the resources to hack your solution. It probably is harder to hack the former.
The other issue is resources. Maybe the ops team can better handle security. In short even with the best arguments you may not prevail.


text:
Q: Batch bills- Submission Id I need to grab the batch bill submission id (from different vendors) of the object from netsuite.Does anyone know how to do this?
 TransactionSearchBasic transSearch = new TransactionSearchBasic();
            SearchResult resVendorBill = service.search(transSearch);
            resVendorBill.pageSize = 25;
            resVendorBill.pageSizeSpecified = true;
            resVendorBill.totalRecords = SearchRecentTransCount;
            resVendorBill.totalRecordsSpecified = true;

            transSearch.recordType = new SearchStringField() { @operator = SearchStringFieldOperator.@is, searchValue = "vendorpayment", operatorSpecified = true };
            SearchResult resVendorPayment = service.search(transSearch);

            if (resVendorPayment.status.isSuccess)
            {
                Record[] searchPaymentRecords = resVendorPayment.recordList;
                if (searchPaymentRecords != null && searchPaymentRecords.Length >= 1)
                {
                    List<VendorPayment> lstVendorPayments = searchPaymentRecords.Select(ep => (VendorPayment)ep).OrderByDescending(epo => epo.createdDate).Take(SearchRecentTransCount).ToList();

                }
            }

redpajama_set_name: RedPajamaStackExchange


text:
Q: visualizing clusters extracted from MClust using ggplot2 I am analysing the distribution of my data using mclust (follow-up to Clustering with Mclust results in an empty cluster)
Here my data for download https://www.file-upload.net/download-14320392/example.csv.html
First, I evaluate the clusters present in my data:
library(reshape2)
library(mclust)
library(ggplot2)

data <- read.csv(file.choose(), header=TRUE,  check.names = FALSE)
data_melt <- melt(data, value.name = "value", na.rm=TRUE)

fit <- Mclust(data$value, modelNames="E", G = 1:7)
summary(fit, parameters = TRUE)

----------------------------------------------------
Gaussian finite mixture model fitted by EM algorithm
----------------------------------------------------

Mclust E (univariate, equal variance) model with 4 components:

log-likelihood    n df       BIC       ICL
-20504.71 3258  8 -41074.13 -44326.69

Clustering table:
1    2    3    4
0 2271  896   91

Mixing probabilities:
1         2         3         4
0.2807685 0.4342499 0.2544305 0.0305511

Means:
1        2        3        4
1381.391 1381.715 1574.335 1851.667

Variances:
1        2        3        4
7466.189 7466.189 7466.189 7466.189

Now having them identified, I would like to overlay the total distribution with distributions of the individual components. To do this, I tried to extract the assignment of each value to the respective cluster using:
df <- as.data.frame(data)
df$classification <- as.factor(df$value[fit$classification])

ggplot(df, aes(value, fill= classification)) +
  geom_density(aes(col=classification, fill = NULL), size = 1)

As a result, I get the following:

It looks to have worked, however, I wonder,
a) where the descriptions (1602, 1639 and 1823) of the individual classifications come from
b) how I can scale the individual densities as a fraction of the total (for example 1823 contributes   only 91 values out of 3258 observations; see above)
c) if it makes sense to alternatively use predicted normal distributions based on the mean + SD obtained?
Any help or suggestions are highly appreciated!

A: I think you could get what you want in the following way:
library(magrittr)
data_melt <- data_melt %>% mutate(class = as.factor(fit$classification))
ggplot(data_melt, aes(x=value, colour=class, fill=class)) +
    geom_density(aes(y=..count..), alpha=.25)


text:
Q: mapWithState assertion failed: Block rdd_45_0 is not locked for reading I'm using the function mapWithState() to count UV in my spark streaming application. After mapWithState I get a dstream and foreachRDD with it. In the function foreachRDD, there is a rdd.foreachPartition to foreach the Iterator, and next apply foreach on Iterator with Future, but I got an error in the Future.

*

*Error log here:

>     17/07/27 10:19:54.0447 INFO Executor: Finished task 1.0 in stage 52.0 (TID 422). 1878 bytes result sent to driver
>     17/07/27 10:19:54.0454 DEBUG BlockManagerSlaveEndpoint: removing RDD 47
>     17/07/27 10:19:54.0454 INFO BlockManager: Removing RDD 47
>     17/07/27 10:19:54.0455 DEBUG BlockManagerSlaveEndpoint: Done removing RDD 47, response is 0
>     17/07/27 10:19:54.0455 DEBUG BlockManagerSlaveEndpoint: Sent response: 0 to 192.168.1.30:43968
>     17/07/27 10:19:54.0456 DEBUG BlockManagerSlaveEndpoint: removing RDD 46
>     17/07/27 10:19:54.0456 INFO BlockManager: Removing RDD 46
>     17/07/27 10:19:54.0456 DEBUG BlockManagerSlaveEndpoint: Done removing RDD 46, response is 0
>     17/07/27 10:19:54.0456 DEBUG BlockManagerSlaveEndpoint: Sent response: 0 to 192.168.1.30:43968
>     17/07/27 10:19:54.0461 WARN BoneCP: Thread close connection monitoring has been enabled. This will negatively impact on your
> performance. Only enable this option for debugging purposes!
>     17/07/27 10:19:54.0873 WARN ClickAnalysis$: before parpair data with threadName=ForkJoinPool-1-worker-5 and threadId=46
>     17/07/27 10:19:54.0873 WARN ClickAnalysis$: before parpair data with threadName=ForkJoinPool-1-worker-3 and threadId=50
>     17/07/27 10:19:54.0875 WARN ClickAnalysis$: come into foreach data with threadName=ForkJoinPool-1-worker-5 and threadId=46
>     17/07/27 10:19:54.0875 WARN ClickAnalysis$: come into foreach data with threadName=ForkJoinPool-1-worker-3 and threadId=50
>     Exception: java.util.concurrent.ExecutionException: Boxed Error
>         at scala.concurrent.impl.Promise$.resolver(Promise.scala:55)
>         at scala.concurrent.impl.Promise$.scala$concurrent$impl$Promise$$resolveTry(Promise.scala:47)
>         at scala.concurrent.impl.Promise$DefaultPromise.tryComplete(Promise.scala:244)
>         at scala.concurrent.Promise$class.complete(Promise.scala:55)
>         at scala.concurrent.impl.Promise$DefaultPromise.complete(Promise.scala:153)
>         at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:23)
>         at scala.concurrent.impl.ExecutionContextImpl$AdaptedForkJoinTask.exec(ExecutionContextImpl.scala:121)
>         at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
>         at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
>         at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
>         at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
>     Caused by: java.lang.AssertionError: assertion failed: Block rdd_45_0 is not locked for reading
>         at scala.Predef$.assert(Predef.scala:170)
>         at org.apache.spark.storage.BlockInfoManager.unlock(BlockInfoManager.scala:299)
>         at org.apache.spark.storage.BlockManager.releaseLock(BlockManager.scala:720)
>         at org.apache.spark.storage.BlockManager$$anonfun$1.apply$mcV$sp(BlockManager.scala:516)
>         at org.apache.spark.util.CompletionIterator$$anon$1.completion(CompletionIterator.scala:46)
>         at org.apache.spark.util.CompletionIterator.hasNext(CompletionIterator.scala:35)
>         at org.apache.spark.InterruptibleIterator.hasNext(InterruptibleIterator.scala:37)
>         at scala.collection.Iterator$$anon$12.hasNext(Iterator.scala:439)
>         at scala.collection.Iterator$$anon$11.hasNext(Iterator.scala:408)
>         at scala.collection.Iterator$class.foreach(Iterator.scala:893)
>         at scala.collection.AbstractIterator.foreach(Iterator.scala:1336)
>         at ClickAnalysis$.doPrepairCamAndGmtUvPs(ClickAnalysis.scala:383)
>         at ClickAnalysis$$anonfun$8.apply(ClickAnalysis.scala:353)
>         at ClickAnalysis$$anonfun$8.apply(ClickAnalysis.scala:345)
>         at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
>         at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
>         ... 5 more

*

*and my code here:
val mapState3=pairs.mapWithState(StateSpec.function(mappingFunction).timeout(Duration(uvExpireTime.toLong))).map( x => (x._1, x._2.estimatedSize.toLong))

mapState3.foreachRDD( { rdd =>{
rdd.foreachPartition( uvRecord =>{
  if (!uvRecord.isEmpty) {

      doUpdateUV(uvRecord)

  }
})
def doUpdateUV(data:Iterator[(String, Long)]):Unit ={
    if(data != null){
    val f = Future{
    var connection:Connection = null
    try{
      connection = ConnectionPool.getConnection.getOrElse(null)
      connection.setAutoCommit(false)
      val camPs: PreparedStatement = connection.prepareStatement(updateUvCamCnt_sql)
      val gmtPs: PreparedStatement = connection.prepareStatement(updateUvGmtCnt_sql)
      logger.warn("before parpair data with threadName="+Thread.currentThread().getName+" and threadId="+Thread.currentThread().getId)
      for(uvRecord <- data) {
        logger.warn("come into foreach data with threadName=" + Thread.currentThread().getName + " and threadId=" + Thread.currentThread().getId)
      }
      logger.warn("come into batch update with threadName="+Thread.currentThread().getName+" and threadId="+Thread.currentThread().getId)
      camPs.executeBatch()
      gmtPs.executeBatch()
      connection.commit()
      camPs.close()
      gmtPs.close()
    } catch {
      case exception: Exception =>
        logger.error("Error in batchUpdate "+ exception.getMessage + "-----------------------" + ExceptionUtils.getStackTrace(exception) + "-----------------------------")
        throw exception
    } finally {
      ConnectionPool.closeConnection(connection)
    }
    "success"
  }
  f onSuccess {
    case result => println(s"Success: $result")
  }

  f onFailure {
    case t => println(s"Exception: ${ExceptionUtils.getStackTrace(t)}")
  }
}

I look forward for getting any useful solution for this problem .

A: I had the same issue:

java.lang.AssertionError: assertion failed: Block rdd_xx_xx is not
locked for reading

I fixed it by just adding more clusters. It seems to have been a memory issue.

A: Based on what I have read from the different jiras, this is a race condition. Multiple attempts at fixing it have been checked in. I am experiencing this issue in 2.4.4, and looks like 3.0.0 might have fixed this issue.
For me it is happening during a call to df.rdd.isEmpty()
If you want more information what I found here are the resources:

*

*First jira on the issue

*Later jira on same issue (duplicate),
but later spark version

*More details on why this is a race
condition

*Very old jira when this seems to have first
appeared


text:
Q: DART : Merge two maps with identical key Suppose I have these maps:
Map<int,List<String>>  firstMap   = {1:["a", "b"]};
Map<int,List<String>>  secondMap  = {2:["c"]};
Map<int,List<String>>  thirdMap   = {1:["d"]};

I want to merge them without overwriting values with same key to have this output:
{1: [a, b, d], 2: [c]

I used both spread operator and adAll method and both overwrite the value for key 1 to have {1: [d], 2: [c]}
instead of {1: [a, b, d], 2: [c].

A: void main() {
  Map<int, List<String>> firstMap = {1: ["a", "b"]};
  Map<int, List<String>> secondMap = {2: ["c"]};
  Map<int, List<String>> thirdMap = {1: ["d"]};

  var mergedMap = <int, List<String>>{};
  for (var map in [firstMap, secondMap, thirdMap]) {
    for (var entry in map.entries) {
      // Add an empty `List` to `mergedMap` if the key doesn't already exist
      // and then merge the `List`s.
      (mergedMap[entry.key] ??= []).addAll(entry.value);
    }
  }
  print(mergedMap); // Prints: {1: [a, b, d], 2: [c]}
}


text:
Q: Logic for looping back to start of alphabet after last letter in Caesar's Cipher I've been writing the below program as an implementation of Caesar's Cipher and it works unless the key provided is larger than 26. The problem is that I don't know how to loop back once the value exceeds 'z' or 'Z'.
What I've tried so far is to nest if statements and while loops, which caused a memory leak (LOL), so suffice it to say, that I'm pretty stuck.
How to use the program:
gcc -o caesar caesar.c -lcs50 -lm && ./caesar key(number) where caesar.c is the filename.
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>

bool input_valid(int count, string arg);

int main(int argc, string argv[])
{
    int key;
    char final_val;
    string string;
    char cipher_string[80];

    if (!input_valid(argc, argv[1]))
    {
        printf("Invalid input!\nUSAGE: ./caesar key\n");
        return 1;
    }

    string = get_string("plaintext: ");
    key = strtol(argv[1], NULL, 10);

    for (int i = 0; i < strlen(string); i++)
    {
        int ascii_val = (int)string[i];

        bool valid_lower_case = (ascii_val + key) >= 'a' && (ascii_val + key) < 'z';
        bool valid_upper_case = (ascii_val + key) >= 'A' && (ascii_val + key) < 'Z';

        if (isalpha(string[i]))
        {
            if (valid_lower_case || valid_upper_case)
            {
                final_val = ascii_val + key;
            }
            else
            {
                // loop back to 'a' if ascii_val reaches 'z'
                final_val = 'a' + (key - ('z' - (ascii_val - 1)));
            }
        }
        else
        {
            final_val = ascii_val;
        }

        cipher_string[i] = final_val;
    }

    printf("ciphertext: %s\n", cipher_string);
}

bool input_valid(int count, string arg)
{
    // input has more args than just the file name
    // input is an integer
    return count > 1 && isdigit(arg[0]);
}

A: Are you familiar with the MOD operator, %?
It's useful for implementing "ring-oriented" data, e.g.
array = [0, 1, 2] // "ring"

array[0 % 3] == 0
array[1 % 3] == 1
array[2 % 3] == 2
array[3 % 3] == 0 // "ring" loops back to 0
array[4 % 3] == 1
array[5 % 3] == 2

Mathematically, it's the remainder of division.
10 / 4    # (4 * 2) + 2
10 % 4             == 2

17 / 2    # (2 * 8) + 1
17 % 2             == 1


text:
Q: How to assign specific values to colours in imagesc I'm trying to assign three possible values of a matrix to three colours when plotted using imagesc in MATLAB.
All I want is imagesc() to represent 0 as white, 1 as black and 2 as red.
Initially imagesc() does this, but as the for-loop proceeds, the colours for 1 and 2 get swapped.
I have tried re-ordering the colours assigned to colormap(), but the colours still swap.
Here is my code:
Grid = 10;
M = zeros(Grid);
M(3,1:3)=1;M(2,3)=1;M(1,2)=1;
Black = [0 0 0];
White = [1 1 1];
Red = [1 0 0];
Background = White;
colormap([Background; Red; Black])
figure()
imagesc(M)

...so far, so good. I have five black squares in the corner.
However as my loop proceeds and 2's are introduced, the matrix looks like this:
0   0   0   0   0   0   0
0   2   1   0   0   0   0
1   0   1   0   0   0   0
0   1   1   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0
0   0   0   0   0   0   0

but now the image shows BLACK for 2, and RED for 1.
How do I maintain the colour-to-value relationships?

A: Your main mistake is having the red and black colors reversed in your colormap. You probably did this because putting the colors in the correct order made the pixels red in your first matrix - which was unwanted. The reason for this is the way pixel values are mapped to colormap colors, which can be seen by showing a colorbar. Your custom colormap happened to work because red was used for pixels with a value of about 0.5 - of which there were none.
What you need to do is correctly set the color limits for your axes:
colormap([Background; Black; Red])
set(gca, 'CLim', [0 2]);

Then, this is what would happen for the initial matrix (note that there are no red pixels in the image, but the colormap is ready for them nonetheless):


text:
Q: Illegal invocation with $.get inside $.ajax success Attempting to fetch some content if this route returns true, however I'm getting Uncaught TypeError: Illegal invocation for the $.get line -- would anybody happen to know why?
$.ajax({
  url: "/route_to_check_if_item_exists/",
  type: "GET",
  success: function(){
    console.log('Item exists! Now fetch it:');

    $.get($('#articles').data('url'), {
      after: $('#articles')
    });
  },
  error: function() {
    console.log('Uh oh');
  }
});

A: The only multi-argument syntax for $.get is jQuery.get( url [, data ] [, success ] [, dataType ] )
where data can be a simple object, however you can't send a DOM element, or a jQuery object
$.get($('#articles').data('url'), {
  after: $('#articles')
});

Note that you're sending $('#articles'), which is a jQuery wrapper around a DOM element, and that can't be sent, hence an illegal invocation
It's not very clear what you're actually trying to do, but if you're trying to insert the content of the request, that would be more like
$.get($('#articles').data('url'), function( data ) {
    $('#articles').after( data )
});


text:
Q: Why does console.log output modified values even before they have been modified? In Chrome 39 developer tools, this code:
var something = [
    {x: 'foo'},
    {x: 'foo'}
];

console.log(something);

something.forEach(function (element) {
    element['x'] = 'baz';
});

... outputs:

Why does console.log output modified values even before they have been modified?
A similar question from 2012 explains that due to a chromium bug, console.log is "delayed" (does not stringify the input object immediately). But the bug is marked as fixed, so why is this still happening several years later?

A: It doesn't.
When you output an object with console.log, the object is output "by reference"; the values in the console are dynamic, and they will update to reflect the current state of the object.
If you want to output a static string of text about the object, use console.dir

A: Whenever you click on the array of objects, it shows you the updated objects, and not a snapshot of how they looked when you did the console.log.
Think of it as an array of references to the corresponding objects.


text:
Q: in css3, use calc() to center vertically with vh and vw in what has to be a widely used case, using vh for height of a div, and using vm for font size.
css3
div.outer { height: 20vh; }
div.inner { font-size: 3vw; height: auto; }
div.inner2 { font-size: 2vw; }

html - case 1

center me!

html - case 2

center me top!

center me bottom!

is there any way to use calc() and other css3 properties to vertically center the div.inner within the div.outer?

A: If you only use one line you can use line-height: 20vh;.
http://jsfiddle.net/jxu2T/

A: The best thing to do which isn't future proof is to use top padding.
Sadly calc() didn't work with vh, vm on Chrome (it was fixed 2014-04-30)

A: I know this is not an answer to your exact question, though I thought I'd mention it as a possible alternative.
I'm currently tackling a vertical alignment issue myself and until recently had relied on nasty javascript calculations to get the job done! This falls over if the element or parent elements are hidden.
If you are fine using CSS3, might I suggest looking into box-align?
It seems to do the trick for me.
http://www.w3schools.com/cssref/css3_pr_box-align.asp


text:
Q: How to read "local storage" of website with js Is it possible to access the local storage of other websites with a different domain than the domain of the website that saved it, or is it restricted to a specific domain only?

A: This is not possible, the localStorage object is bound to the website origin, the origin being defined by the scheme (protocol, i.e. https), host (domain), and port.


text:
Q: Detecting file opening in Linux I'm writing a daemon, monitoring user activity on Linux. Is there any way to detect opening arbitrary file by arbitrary process? Preferred language is Python/C/C++

A: Linux has group of inotify system calls.
There is a Python wrapper for these called pyinotify.


text:
Q: How to draw a huge number of dots (with regular pattern) on canvas? The dots are arranged so they have a regular distance between them.
they are drawn at (x%4==0) and (y%4==0), they take time to be drawn in a brute force way:
for (var x = 0; x < width; x+=4) {
    for (var y = 0; y < height; y+=4) {
        draw(x, y, 1, 1);
    }
}

how to do it in a better way?

A: You can use createPattern() by first creating an offscreen-canvas, draw a single dot into it, then use that canvas as a image source for createPattern(). Set pattern as fillStyle and fill.

var ctx = c.getContext("2d");
var pattern = ctx.createPattern(createPatternImage(), "repeat");
ctx.fillStyle = pattern;
ctx.fillRect(0, 0, c.width, c.height);

function createPatternImage() {
  var ctx = document.createElement("canvas").getContext("2d");
  ctx.canvas.width = ctx.canvas.height = 4;   // = size of pattern base
  ctx.fillStyle = "#fff";
  ctx.fillRect(0,0,1,1);
  return ctx.canvas;                          // canvas can be used as image source
}
<canvas id=c style="background:#c00"></canvas>

If this is not an option you can always optimize the code you have now by not filling each dot, but adding to the path and fill once:

var ctx = c.getContext("2d");   // obtain only one time.
var width = c.width, height = c.height;

ctx.beginPath();                // clear path if it has been used previously
ctx.fillStyle = "#fff";

for (var x = 0; x < width; x+=4) {
    for (var y = 0; y < height; y+=4) {
        draw(x, y, 1, 1);
    }
}

// modify method to add to path instead
function draw(x,y,width,height) {
  ctx.rect(x,y,width,height);
}

// when done, fill once
ctx.fill();
<canvas id=c style="background:#c00"></canvas>


text:
Q: Internet does not auto reconnect Sometimes my internet fails for about 1-2minutes because the modem from my provider restarts. When this happens, i have to remove the UTP cable and put the UTP cable back into the ubuntu machine on my attic to get internet connection going again.
Is there a way that he automaticaly reconnects when the modem is back online after a few minutes? It's a bit of a pain to go up the attic everytime. Especially when i am not at home, then my server is offline for quite a time.
Thanks for helping a new user out :)
Greetings from Belgium,
Thomas


text:
Q: Existence of Pontryagin's maximum principle I would like you can recommend me some reference related to the proof the "Existence of Pontryagin's maximum principle", and thus, be able to advance a research work.
Thank a lot


text:
Q: Elegant MVC code for optional surrounding tag What would be more elegant code to accomplish the following:
foreach(var filter in Model.Filters)
{
  if(filter.Selected)
  {

      @* much more html can be here *@
      @filter.Title

        (@filter.Count)

  } else {

      @* much more html can be here but similar code as above *@
        @filter.Title

          (@filter.Count)

  }
}

*

*the repeated html code for the div / span seems bad code

*also the css-class specification should be solved in the elegant version

A: foreach(var filter in Model.Filters)
{

      @(filter.Selected? "" : string.empty)
      @filter.Title

        (@filter.Count)

  }
}

Essentially this just tests filter.Selected and is a more terse form of what you already have. I didn't test the syntax, just wrote it down off the top of my head so forgive me if it doesn't compile. I'm not sure this is more elegant, because I don't know what your definition of elegance is. I assumed you meant you more DRY.

A: @helper MyHelper(SomeDataType filter)
{
  @* much more html can be here *@
  @filter.Title

    (@filter.Count)

}

foreach(var filter in Model.Filters)
{
  if (filter.Selected)
  {

      @MyHelper(filter)

  } else {

        @MyHelper(filter)

  }
}


text:
Q: How to search DOM elements using XPath or CSS selectors in Chrome Developer Tools? The doc http://code.google.com/chrome/devtools/docs/elements.html says it supports XPath or CSS selectors, but when I tried, didn't seem to work for me.
Any one knows how to use it?

A: For xpath searches use $x('xpathSelector').
For a css selector use $('cssSelector').
However, this last selector returns only the first matching element. If you want to see all matching elements go for $$('cssSelector')

A: You can use $x in the Chrome javascript console. No extensions needed.
ex: $x("//img")

A: Just typing xpath expression in the search box should work. It works for me in tip-of-tree build.
The feature seems to be broken in Chrome 11 though, I've filed a bug on this: http://crbug.com/79716

A: If you click on any element in the elements pane then type command-F, it will open a search bar that lets you search for elements using xpath selectors.


text:
Q: eledmac: formatting endnotes I try to format endnotes with eledmac in a way that I can use them to correct printing errors of the original text, but unfortunately i don't understand how to change the fonts.
Say, for example, I edit this text:
I did it \edtext{my}{\Aendnote{may}} way

In the Appendix I want to have this:

p. 7, 2 my] my

But I don't get the manual on how to format "my" in bold and get the bracket. Can anyone help?

A: The commands involved behind the scenes for the creating and printing of lemmata are very involved.  Unless the package is extended to provide this option, you need to cheat using the \lemma command.  (OK, you don't need to cheat in this way, but this is the simplest way to achieve what you want....)
Here's one way, using a simple \if switch.  It also relies on using an abstracted version of the \edtext command, which I strongly recommend for legibility reasons.  The input file of critical edition texts gets really difficult to read (and debut) even if avoid error-prone coding like using:
\edtext{<correct text>}{\Aendnote{<incorrect text>}}

Slightly cleaner is a definition like:
\newcommand{\variant}[2]{\edtext{#1}{\Aendnote{#2}}}

which is then used in the file as
\variant{correct}{incorrect}

(Apologies if you already are doing something like that but are simply trying to keep your example low-level for the sake of the question.)
Anyway, try the below file. If you comment out the \prooftrue line, your lemmata will be set regularly, if you uncomment it, the lemmata will be bold.
% Set up an "ifproof" switch
\newif\ifproof
% When you want the bold lemma in the notes, uncomment the following
% line:
%\prooftrue
%
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage{eledmac}

\ifproof
  \newcommand{\variant}[2]{%
    \edtext{#1}{\lemma{\textbf{#1}}\Aendnote{#2}}}
\else
  \newcommand{\variant}[2]{%
    \edtext{#1}{\Aendnote{#2}}}
\fi

\begin{document}
 \beginnumbering
 \pstart

 I did it \variant{my}{may} way.

 \pend
 \endnumbering

\section{A Endnotes}
\doendnotes{A}

\end{document}


text:
Q: How to convert a method that takes an OnError and OnCompleted into an Observable There is probably a really easy answer to this but my brain just isn't working.
I have a method I need to call in a framework that is not Observable aware, that has the following pattern.
client.GetAsync<TResult>(
     string resource,
     Action<Exception> onError,
     Action<TResult> onCompleted);

I need to convert this into a synchronous action that waits for the result.
I figured Rx would help me so I tried
var observable = Observable.Create<XElement>(
    observer => () => client.GetAsync<XElement>(
        "resource1",
        observer.OnError,
        observer.OnNext);
var result = observable.First();

But this here but this just deadlocks, I tried making it ObserveOn new thread and SubscribeOn new thread. But it still deadlocks, am I even on the right track?

A: You're on the right track, with a small adjustment.:
var observable = Observable.Create<XElement>(
    observer =>
    {
        client.GetAsync<XElement>(
        "resource1",
        observer.OnError,
        x =>
        {
           observer.OnNext(x);
           observer.OnCompleted();
        });
        return () => {};
    });

Just as a comment, using RX to make synchronous stuff from asynchronous is kinda "goes against the grain". Normally, RX is used to make asynchronous from synchronous or make asynchronous easier.


text:
Q: UICollectionView showing array of buttons Swift I've been trying to figure out how i can use a UICollectionView to display an array of UIButtons. Each button has its own (different) action, image, title etc. When a button (which covers the entire cell in the collection view) is pressed that button is then deleted, and the action is executed. I'm new to Swift, not sure where to start, I know my code is wrong but I'll add it anyway:
import UIKit

let reuseIdentifier = "cell"

class CollectionViewController: UICollectionViewController {

var buttons = [UIButton]()
override func viewDidLoad() {
    super.viewDidLoad()

    let button1 = UIButton()
    let button2 = UIButton()
    let button3 = UIButton()
    buttons = [button1,button2,button3]
    button1.addTarget(self, action: #selector(target), forControlEvents: .TouchUpInside)
    button2.addTarget(self, action: #selector(target2), forControlEvents: .TouchUpInside)
    button3.addTarget(self, action: #selector(target3), forControlEvents: .TouchUpInside)
    //haven't added images and titles yet...

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()

}

override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of items
    return buttons.count
}

override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! CollectionViewCell

    cell.button = buttons[indexPath.row]

    return cell
}

Cell Class
import UIKit

class CollectionViewCell: UICollectionViewCell {

@IBOutlet var button: UIButton!

}

A: *

*I don't think it's a good idea to add a UIButton to the cell to trigger some action since that could easily be done through collectionView(_:, didSelectItemAtIndexPath:). Each cell will have an extra button that is unnecessary. If the cell count gets big, you will have a slow scrolling collection view.

Instead of embedding a button, in the implementation of collectionView(_:, didSelectItemAtIndexPath:), check the section and item, and call the function that would have been the action for the button.

*My understanding is that be it collection view or table view, the cells should be a graphic representation of some data. So if you want to make the cells go away, you should have the corresponding data go away first, and use deleteItemsAtIndexPaths.

A: Your code is really close I think.  There are lots of ways to accomplish something like this.
If you want the button (and the collectionViewCell) to disappear, you can just remove that button from buttons and call reloadData() on the collectionView.
If you want to keep the collectionView cell, and just remove the button, you could try changing your buttons definition to hold optional buttons (original declaration is not shown in your code), but like this:
var buttons : [UIButton?]

then when the button is clicked, change that button to nil.  When cellForItemAtIndexPath is called, check if the button is in the array, if it is not, just skip it (or hide it or whatever you need to do!)
Let me know if you need to see more sample code for this!


text:
Q: Write to current cell from toolbar activation in Excel-DNA I have a function which gets run from a button on a toolbar.
The button loads a windows form which allows the user to perform a product lookup and returns the product code:
Ribbon:
          <button id='btnProductLookup' label='Product Code Lookup' image='ProdCode' size='large' onAction='ProductCodeLookup'/>

Method:
    public void ProductCodeLookup(IRibbonControl control)
    {
        using (FrmProductLookup lookup = new FrmProductLookup(_callHandler))
        {
            DialogResult result = lookup.ShowDialog();
            if (result == DialogResult.OK)
            {
                ExcelReference current = XlCall.Excel(XlCall.xlfActiveCell) as ExcelReference;
                MessageBox.Show(current.ColumnFirst.ToString());
                MessageBox.Show(lookup.SelectedProductCode);
            }

        }
    }

I want to write the value in lookup.SelectedProductCode into the currently selected cell but I get an exception every time.

A: The C API (XlCall.Excel) is not directly available in a ribbon handler.
You can either transition to a macro context using ExcelAsyncUtil.QueueAsMacro(...) or use the COM object model in this setting.


text:
Q: Gridview with checkboxes exported to Excel hangs for extended periods when opening I'm in the process of troubleshooting an issue with a Gridview heavy with checkboxes exported to Excel (Sample code below.  Actual code includes more checkboxes).  What happens is that 1) the user clicks the button to begin the export process, then 2) the user either saves or downloads the file to their desktop, 3) the file takes a considerable amount of time to render the basic cells (> 15 seconds), then once the basic excel file renders 3) the spreadsheet renders the checkboxes (render time takes anywhere from 3 to 10 minutes depending on the speed of the computer) and appears to hang until the checkboxes appear like they appear in the GridView.
I should also note that this sample file is around 800k and I have been able to export other larger gridviews to Excel without the checkboxes almost instantly.
I get that the actual exported file from the web page isn't true a Excel file until you save it as a spereadsheet/workbook.  However, this seems a bit odd that a gridview with checkboxes takes so long to render as a 'spreadsheet'.
My question is this - Is this normal behavior for exporting excel spreadsheets heavy with checkboxes or is there some way I can improve the code below to ensure that the Excel spreadsheet doesn't hang for extended periods when opening?  Is there any other solution that can help speed the checkbox render time?
aspx code
<%@ Page Title="Test Page" Language="C#" MasterPageFile="~/Site.master" EnableEventValidation="false" AutoEventWireup="true" CodeFile="form2.aspx.cs" Inherits="form2" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" Runat="Server"></asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="FeaturedContent" Runat="Server"></asp:Content>
    <asp:Content ID="Content3" ContentPlaceHolderID="MainContent" Runat="Server">
  <asp:Button ID="Button1" runat="server" Height="38px"  OnClick="Button1_CLick" Text="Export to Excel" Width="200px" />
  <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" ForeColor="#333333" GridLines="None">
    <AlternatingRowStyle BackColor="White" />
    <Columns>
        <asp:CommandField ShowEditButton="True" />
        <asp:BoundField DataField="Field 1" HeaderText="Field 1" SortExpression="Field 1" />
        <asp:BoundField DataField="Field 2" HeaderText="Field 2" SortExpression="Field 2" />
        <asp:BoundField DataField="Field 3" HeaderText="Field 3" SortExpression="Field 3" />
        <asp:BoundField DataField="Field 4" HeaderText="Field 4" SortExpression="Field 4" />
        <asp:BoundField DataField="Field 5" HeaderText="Field 5" SortExpression="Field 5" />
        <asp:BoundField DataField="Field 6" HeaderText="Field 6" SortExpression="Field 6" />
        <asp:BoundField DataField="Field 7" HeaderText="Field 7" SortExpression="Field 7" />
        <asp:BoundField DataField="Field 8" HeaderText="Field 8" SortExpression="Field 8" />
        <asp:BoundField DataField="Field 9" HeaderText="Field 9" SortExpression="Field 9" />
      <asp:Panel ID="pnlClick" runat="server" CssClass="collapsiblepanelCSS">

                  Server List Collapsable Panel

                  <asp:Label ID="lblMessage" runat="server" Text="Label" />

              </asp:Panel>
        <asp:Panel ID="pnlCollapsable" runat="server" Height="0" CssClass="collapsiblepanelCSS">
        <asp:CheckBoxField DataField="Check Box 1" HeaderText="Check Box 1" SortExpression="Check Box 1" />
        <asp:CheckBoxField DataField="Check Box 2" HeaderText="Check Box 2" SortExpression="Check Box 2" />
        <asp:CheckBoxField DataField="Check Box 3" HeaderText="Check Box 3" SortExpression="Check Box 3" />
        <asp:CheckBoxField DataField="Check Box 4" HeaderText="Check Box 4" SortExpression="Check Box 4" />
        <asp:CheckBoxField DataField="Check Box 5" HeaderText="Check Box 5" SortExpression="Check Box 5" />
        <asp:CheckBoxField DataField="Check Box 6" HeaderText="Check Box 6" SortExpression="Check Box 6" />
        <asp:CheckBoxField DataField="Check Box 7" HeaderText="Check Box 7" SortExpression="Check Box 7" />
        <asp:CheckBoxField DataField="Check Box 8" HeaderText="Check Box 8" SortExpression="Check Box 8" />
        <asp:CheckBoxField DataField="Check Box 9" HeaderText="Check Box 9" SortExpression="Check Box 9" />
        <asp:CheckBoxField DataField="Check Box 10" HeaderText="Check Box 10" SortExpression="Check Box 10" />
        <asp:CheckBoxField DataField="Check Box 11" HeaderText="Check Box 11" SortExpression="Check Box 11" />
        <asp:CheckBoxField DataField="Check Box 12" HeaderText="Check Box 12" SortExpression="Check Box 12" />
          </asp:Panel>
        <CC1:CollapsiblePanelExtender ID="CollapsiblePanelExtender1" Collapsed="true" ExpandControlID="pnlClick" TextLabelID="lblMessage" CollapsedText="Click To Show" ExpandedText="Click To Hide" ImageControlID="imgArrows" ExpandDirection="Vertical" TargetControlID="pnlCollapsable" ScrollContents="false" runat="server"></CC1:CollapsiblePanelExtender>

        <asp:BoundField DataField="Field 10" HeaderText="Field 10" SortExpression="Field 10" />
        <asp:BoundField DataField="Field 11" HeaderText="Field 11" SortExpression="Field 11" />
        <asp:BoundField DataField="Field 12" HeaderText="Field 12" SortExpression="Field 12" />
        <asp:CommandField ShowEditButton="True" />
    </Columns>
    <EditRowStyle BackColor="#2461BF" />
    <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
    <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
    <RowStyle BackColor="#EFF3FB" />
    <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
    <SortedAscendingCellStyle BackColor="#F5F7FB" />
    <SortedAscendingHeaderStyle BackColor="#6D95E1" />
    <SortedDescendingCellStyle BackColor="#E9EBEF" />
    <SortedDescendingHeaderStyle BackColor="#4870BE" />
</asp:GridView>

<sql connection strings, insert/update SQL code, update parameters, and closing ASP/HTML tags>

cs file
   using System;
   using System.Configuration;
   using System.Data;
   using System.Collections.Generic;
   using System.Linq;
   using System.Web;
   using System.Web.UI;
   using System.Web.UI.WebControls;

   public partial class form2 : system.Web.UI.Page
   {

        protected void Page_Load(object sender, EventArgs e)
        {

        }

        public override void VerifyRenderingInServerForm(Control control)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {
              Response.Clear();
              Response.AddHeader("content-disposition", "attachement;filename=FileNAme.xls");
              Response.ContentType = "application/vnd.xlsx";
              System.IO.StringWriter stringWrite = new System.IO.StringWriter();
              System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
              GridView1.RenderControl(htmlWrite);
              Response.Write(stringWrite.ToString());
              Response.End();
        }

    }

A: After some research I determined that with the large amount(s) of checkboxes that are exported to Excel from a gridview (especially when the gridview is of considerable size) it will take the export process quite some time for all of the checkboxes to render correctly to a final product.
Granted, the exported Excel document isn't a true spreadsheet until it is specifically saved as a spreadsheet.  I just wanted to put this on 'record' that the checkbox rendering process takes a considerable amount of time when exported.  Perhaps this could be worked on to make the process not so lengthy in future versions of the products noted in the tags.


text:
Q: SSRS: Group by matching a pattern How can I group by based on a pattern in column to calculate the total?
My table has the following columns: CustomerAccount (char30), AccountDesc varchar(200), AccountAmount1 (decimal), AccountAmount2,....., AccountAmount5.
The CustomerAccount is in this format: xxx.xxxx.xxxxx.
Some of the values are:

How do I group the data so any value like xxx.xxxx.31xxx, xxx.xxxx.32xxx, etc is grouped together so I can calculate the AccountAmount like the image below in SSRS report? The highlighted part ranges from 30 to 39:

I am not sure if it would be easier to do it in SQL query, but not sure how.

A: If your account number is always a fixed length (or more precisely, if the numbers you want to group by are always in the same position) then you can create a row group with the group expression being something like
=MID(Fields!CustomerAccount.Value, 11,2)

If you wanted to group an everything up to that point you could do
=LEFT(Fields!CustomerAccount.Value, 13)

The numbers might be out by one as I can't remember if these are zero or 1 based functions but you'll soon notice that.


text:
Q: Как группировать узлы XML в результатах запроса SELECT XMLElement в oracle Каким образом можно перевести данные таблицы в XML ?
Есть таблица:
-------------
ALLTAGS
-------------
TAGID | COUNT
-------------
1     | 2
2     | 5
3     | 4
-------------

Нужно получить XML такого вида:
<ALLSCOPES>
    <ResultTag>
        <Tag_ID>1</Tag_ID>
        <Tag_Count>2</Tag_Count>
    </ResultTag>
    <ResultTag>
        <Tag_ID>2</Tag_ID>
        <Tag_Count>5</Tag_Count>
    </ResultTag>
    <ResultTag>
        <Tag_ID>3</Tag_ID>
        <Tag_Count>4</Tag_Count>
    </ResultTag>
</ALLSCOPES>

Пробую сделать так:
SELECT  (XMLElement("ALLSCOPES",
            XMLElement("ResultTag",
                XMLElement("Tag_ID", t.TAG_ID),
                XMLElement("Tag_Count", t.TAGCOUNT)))
        ).GetStringVal() as ALLSCOPES
FROM ALLTAGS t;

но получаю 3 записи вида:
<ALLSCOPES>
    <ResultTag>
        <Tag_ID>1</Tag_ID>
        <Tag_Count>2</Tag_Count>
    </ResultTag>
</ALLSCOPES>

<ALLSCOPES>
        <ResultTag>
            <Tag_ID>2</Tag_ID>
            <Tag_Count>5</Tag_Count>
        </ResultTag>
    </ALLSCOPES>

итд.
Как правильно решить мою задачу?

A: Ничего не понимаю в oracle. Набираю в google запрос: SELECT XMLElement, открываю первую ссылку, смотрю документацию и вижу:
SELECT XMLElement("Department", XMLAgg(XMLElement("Employee",
                                              e.job_id||' '||e.last_name)
                                   ORDER BY e.last_name))
  AS "Dept_list"
  FROM hr.employees e
  WHERE e.department_id = 30 OR e.department_id = 40;

должен давать результат:
Dept_list
------------------
<Department>
  <Employee>PU_CLERK Baida</Employee>
  <Employee>PU_CLERK Colmenares</Employee>
  <Employee>PU_CLERK Himuro</Employee>
  <Employee>PU_CLERK Khoo</Employee>
  <Employee>HR_REP Mavris</Employee>
  <Employee>PU_MAN Raphaely</Employee>
  <Employee>PU_CLERK Tobias</Employee>
</Department>

Похоже? Похоже. Пробуем приспособить к вашему запросу:
SELECT  (XMLElement("ALLSCOPES",
        XMLAgg(XMLElement("ResultTag",
            XMLElement("Tag_ID", t.TAG_ID),
            XMLElement("Tag_Count", t.TAGCOUNT))))
    ).GetStringVal() as ALLSCOPES
  FROM ALLTAGS t;

Попробуете?


text:
Q: Migrate harddisk with Ubuntu A few years ago I got a laptop, this had a internal disk with windows 10.
When I got it I inserted a second harddrive. And I made a dual boot and installed Ubuntu only on that second disk.
Now I got a new Laptop, and I want the same setup, the default harddrive windows 10, and dual boot ubuntu on my second disk.
Can I do this without reinstalling Ubuntu, and formatting that second disk?
I guess you would need to update the grub and stuff like that.
Can someone help me get started with this?
The current disks layout

A: Absolutely! - But be careful!!
It depends on a couple of things, though.
You may be able to tell your BIOS that the second disk is the primary boot disk.  Have you tried that?
If that doesn't work, then you'll need to reinstall the bootloader somewhere.  That can be:

*

*On the primary hard drive boot sector; or

*On the secondary drive boot sector (and use the Windows Boot Manager); or

*On the secondary drive boot partition; or

*Any combination of the above

The overall process is to:

*

*Gain access to the drive either by booting Ubuntu off a USB key

*Edit the /etc/default/grub file to specify the correct partition (UUIDs can be helpful here to avoid writing to the wrong device.)

*chroot into the partition and run update-grub
There may be easier options by using "Rescue a broken system" on the USB key, but I haven't tried those.
There's also a handy tutorial here.


text:
Q: Function f(x) is continuous on the interval [0,2c]. If f(c) > f(0) and f(c) > f(2c), show that there is a ∈ [0,c] such that f(c+a) = f(a). I need help with this question. Is there something to do with Intermediate Value Theorem? Not sure how to approach this. Appreciate any help, thanks!
Assume $c>0$ is a constant and the function $f(x)$ is continuous on the interval $[0,2c]$. If $f(c) > f(0)$ and $f(c) > f(2c)$, show that there is $a ∈ [0,c]$ such that $$f(c+a) = f(a)$$.

A: Consider the function $g(x):=f(x+c)-f(x)$ for $x \in [0,c]$
Show that $g(0)>0$ and $g(c)<0.$ Can you proceed ?

A:
Is there something to do with Intermediate Value Theorem?

Yes, very much.
Take a look at
$$f(c+a) = f(a)\\f(c+a) - f(a) = 0$$
Can you make something intermediate-theoremy out of that?


text:
Q: nest xml in an xml doctype entity <!DOCTYPE cruisecontrol [
    <!ENTITY triggers "<triggers><intervalTrigger seconds="30" /></triggers>">
    <!ENTITY rootdir "J:\pathyness\" >
]>

I'm trying to setup my first cruisecontrol.net server, so since I want to reduce the amount of repeated configuration I am trying to setup this nested XML entity so I can just use &triggers; within the body of the xml.
What do I need to do to that XML entity <triggers><intervalTrigger seconds="30" /></triggers> to make sure it will work as I've illustrated above? I know that the two gotchas so far are

*

*quotes

*angle brackets

So I'm not sure if I have to go so far as <triggers><intervalTrigger seconds="30" /></triggers> as that all seems like overkill of the nth degree.

A: Try going like this:
$ cat doctype-markup.xml
<!DOCTYPE cruisecontrol [
<!ENTITY triggers "<triggers><intervalTrigger seconds='30' /></triggers>">
<!ENTITY rootdir "J:\pathyness\" >
]>
<cruisecontrol>
<dir>&rootdir;</dir>
<eins>&triggers;</eins>
<zwei>&triggers;</zwei>
<drei>&triggers;</drei>
</cruisecontrol>

$ xmllint doctype-markup.xml
<?xml version="1.0"?>
<!DOCTYPE cruisecontrol [
<!ENTITY triggers "<triggers><intervalTrigger seconds='30' /></triggers>">
<!ENTITY rootdir "J:\pathyness\">
]>
<cruisecontrol>
<dir>&rootdir;</dir>
<eins>&triggers;</eins>
<zwei>&triggers;</zwei>
<drei>&triggers;</drei>
</cruisecontrol>

$ xmllint --noent doctype-markup.xml
<?xml version="1.0"?>
<!DOCTYPE cruisecontrol [
<!ENTITY triggers "<triggers><intervalTrigger seconds='30' /></triggers>">
<!ENTITY rootdir "J:\pathyness\">
]>
<cruisecontrol>
<dir>J:\pathyness\</dir>
<eins><triggers><intervalTrigger seconds="30"/></triggers></eins>
<zwei><triggers><intervalTrigger seconds="30"/></triggers></zwei>
<drei><triggers><intervalTrigger seconds="30"/></triggers></drei>
</cruisecontrol>

A: If your goal is to reduce repetition Configuration Preprocessor is vastly superior to working with entity subtitution.


text:
Q: Insertion Sort on an array of strings in C# If I have an array of strings, such as
string[] names = {"John Doe", "Doe John", "Another Name", "Name Another"};

How do I sort this array, using insertion sort?
Wikipedia has some examples: https://en.wikibooks.org/wiki/Algorithm_implementation/Sorting/Insertion_sort#C.23
static void InsertSort(IComparable[] array)
{
    int i, j;

    for (i = 1; i < array.Length; i++)
    {
        IComparable value = array[i];
        j = i - 1;
        while ((j >= 0) && (array[j].CompareTo(value) > 0))
        {
            array[j + 1] = array[j];
            j--;
        }
        array[j + 1] = value;
    }
}

and
static void InsertSort<T>(IList<T> list) where T : IComparable<T>
{
    int i, j;

    for (i = 1; i < list.Count; i++)
    {
        T value = list[i];
        j = i - 1;
        while ((j >= 0) && (list[j].CompareTo(value) > 0))
        {
            list[j + 1] = list[j];
            j--;
        }
        list[j + 1] = value;
    }
}

but it doesn't seem to work on my array of strings, unless I'm doing something wrong.
Would I not run
InsertSort(names); // like so?

A: Works fine for me:
class Program
{
    static void Main()
    {
        string[] names = { "John Doe", "Doe John", "Another Name", "Name Another" };
        InsertSort(names);
        foreach (var item in names)
        {
            Console.WriteLine(item);
        }
    }

    static void InsertSort(IComparable[] array)
    {
        int i, j;

        for (i = 1; i < array.Length; i++)
        {
            IComparable value = array[i];
            j = i - 1;
            while ((j >= 0) && (array[j].CompareTo(value) > 0))
            {
                array[j + 1] = array[j];
                j--;
            }
            array[j + 1] = value;
        }
    }
}

As expected it prints:
Another Name
Doe John
John Doe
Name Another

A: Here's my implementation:
public static void Swap<T>(ref T a, ref T b)
{
    T t = a;
    a = b;
    b = t;
}

public static void InsertionSort<T>(this T[] a) where T : IComparable<T>
{
    a.InsertionSort(Comparer<T>.Default.Compare);
}

public static void InsertionSort<T>(this T[] a, Comparison<T> c)
{
    int n = a.Length;
    for (int i = 1; i < n; ++i)
        for (int k = i; k > 0 && c(a[k], a[k - 1]) < 0; --k)
            Swap(ref a[k], ref a[k - 1]);
}

A: I do some class to do this:
public static class InsertionSort<T> where T : System.IComparable<T>
{
    public static void Sort(ref T[] array)
    {
        T[] tmp = new T[array.Length];
        tmp[0] = array[0];

        for (int i = 1; i < array.Length; i++)
        {
            int place = FindProperPlace(tmp, array[i]);
            ExpandArray(ref tmp, place);
            tmp[place] = array[i];
        }

        array = tmp;
    }

    private static int FindProperPlace(T[] numbersArray, T number)
    {
        int j;

        for (j = 0; j < numbersArray.Length; j++)
        {
            if (number.CompareTo(numbersArray[j]) < 0)
            {
                break;
            }
        }

        return j;
    }

    private static void ExpandArray(ref T[] tmp, int place)
    {
        for (int i = tmp.Length - 1; i > place; i--)
        {
            tmp[i] = tmp[i - 1];
        }
    }
}


text:
Q: Google Maps for Business crashing app with R$styleable NoClassDefFoundError Converting one of my apps over to use the new Google Maps for Business package and now I am stuck with a crash every time our activity attempts to call setContentView() in our onCreate() method.
build.gradle:
dependencies {
    // external dependencies: will need network connection if not already cached
    compile 'com.google.android.gms:play-services:6.5.87'
    compile 'com.android.support:support-v4:21.0.3'

    // local dependencies: jar libraries checked into source control
    compile files('libs/resty-0.3.4.jar')
    compile files('libs/robospice-1.4.9.jar')
    compile files('libs/robospice-cache-1.4.9.jar')
    compile files ('libs/maps_m4b-2.12.0.rc1.jar')
}

activity_location.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <fragment
        android:id="@+id/map"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        class="com.google.android.m4b.maps.MapFragment" />

Crash:
java.lang.NoClassDefFoundError: Failed resolution of: Lcom/google/android/m4b/maps/R$styleable;
            at com.google.android.m4b.maps.GoogleMapOptions.createFromAttributes(GoogleMapOptions.java:428)
            at com.google.android.m4b.maps.MapFragment.onInflate(MapFragment.java:408)
            at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2115)
            at android.app.Activity.onCreateView(Activity.java:5282)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
            at android.app.Activity.setContentView(Activity.java:2144)
            at com.nate.android.hammerhead.LocationActivity.onCreate(LocationActivity.java:106)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "com.google.android.m4b.maps.R$styleable" on path: DexPathList[[zip file "/data/app/com.nate.android.hammerhead-1/base.apk"],nativeLibraryDirectories=[/vendor/lib, /system/lib]]
            at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:511)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:469)
            at com.google.android.m4b.maps.GoogleMapOptions.createFromAttributes(GoogleMapOptions.java:428)
            at com.google.android.m4b.maps.MapFragment.onInflate(MapFragment.java:408)
            at android.app.FragmentManagerImpl.onCreateView(FragmentManager.java:2115)
            at android.app.Activity.onCreateView(Activity.java:5282)
            at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:733)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:806)
            at android.view.LayoutInflater.parseInclude(LayoutInflater.java:916)
            at android.view.LayoutInflater.rInflate(LayoutInflater.java:802)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:504)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:414)
            at android.view.LayoutInflater.inflate(LayoutInflater.java:365)
            at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:377)
            at android.app.Activity.setContentView(Activity.java:2144)
            at com.nate.android.hammerhead.LocationActivity.onCreate(LocationActivity.java:106)
            at android.app.Activity.performCreate(Activity.java:5933)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2251)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2360)
            at android.app.ActivityThread.access$800(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1278)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
    Suppressed: java.lang.ClassNotFoundException: com.google.android.m4b.maps.R$styleable
            at java.lang.Class.classForName(Native Method)
            at java.lang.BootClassLoader.findClass(ClassLoader.java:781)
            at java.lang.BootClassLoader.loadClass(ClassLoader.java:841)
            at java.lang.ClassLoader.loadClass(ClassLoader.java:504)
            ... 28 more
     Caused by: java.lang.NoClassDefFoundError: Class not found using the boot class loader; no stack available

I have followed the guide provided by Google (https://developers.google.com/maps/documentation/business/mobile/android/) and what should have been a simple swap for the new static jar library has turned into a configuration nightmare trying to track this down to little or no avail.

A: How did you import the jar file?
First you need to unzip the downloaded zip file, and copy the Jar files from the google-maps-sdk-m4b_lib -> libs folder to Android Studio's libs folder.
See the below image for the completed Jar files path:

A: After working with a Google representative it appears that this was an issue with the *.jar package for the current 2.12.0.rc1 version.


text:
Q: Get value by property im trying to create a method using scope bu i feel that im not quite getting what i expect.
My Tables are:
Products:
 - id;
 - name
...

properties:
- id;
- name
- identifier
- data_type
- field_type

products_properties
- product_id
- property_id

product_property_integer_values | product_property_text_values | product_property_datetime_values | product_property_varchar_values
 - product_properties_id;
- value (depending of the data data_type of properties, this could be integer, text, boolean or datetime

So what i need is to be able to get the value by the property id.
For example my method in the Product Model would be.
public function scopeGetPropertyValue($query, $attribute)
    {
     $property = Property::where('identifier',$attribute)->first();

      return $query...

    }

Then calling in controller like:
$product = Product::where('slug',$slug)->firstOrFail();
$brand = $product->getPropertyValue('brand');

What would be the best way? I cant get it work or find the best way in doing, is there a better way beside using scope?

A: @Levente Otta is correct, it is probably something that you need to use relations for:
// App\Product
public function properties()
{
    return $this->hasManyThrough(Property::class, ProductProperty::class);
}

public function brands() //this is for the brand property
{
    return $this->properties()
                ->where('identifier', 'brand');
}

Then in your controller you can access like this:
$product = Product::where('slug', $slug)->firstOrFail();
$brand = $product->brands()->first(); //get the first brand
$brands = $product->brands; //get all brands for the product
$my_other_property = $product->properties()->where('identifier', 'my_other_property')->first(); //get first prop called 'my_other_property'

Hopefully you get the gist here.


text:
Q: SVG - smooth morph Paths into each other I'm currently searching for a solution to morph two or more paths into each other, to create a smooth pinch2Zoom animation. Currently I'm working with opacity to blend the two path's into each other:

<?xml version="1.0" encoding="utf-8"?>
<svg version="1.1" id="Ebene_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px"
  width="100px" height="100px" viewBox="-13 15 100 100" enable-background="new -13 15 100 100" xml:space="preserve">

 <path fill="#010202" d="M78.5,93.1l0.8,1.4l-24.3,10l-0.4-1.4c0,0-0.8-2.6-3-4.2C49.7,97.4,29.7,81.2,30.2,75
  c0.3-3.2-0.8-5.4-1.6-7c-0.7-1.3-1.3-2.5-0.7-3.7c0.4-0.9,1.3-1.5,2.6-1.7c1.8-0.3,4.8,0.3,6.8,2.5c1.7,1.8,2.8,4.8,3.9,7.7
  c0.2,0.5,0.6,1.4,1,1.8c2.4,2.9,4.2,2.6,6,0.8c1.9-1.9,1.6-13.6-0.8-15c-1.8-1-4-1-6.8-1.9c-2.9-0.9-6.1-1.7-5.9-5.2
  c0.3-1.6,0.7-2.4,2.8-3.2c4.7-1.8,14.9-2.2,19.5,2.5c1.2,1.2,2.2,1.8,2.8,3.1c0.7-0.4,2.3-1.1,3.4-1.1c3.8,0,14.4,16.8,14.5,16.9
  c1.4,2.6-0.3,12.5-0.9,15.5C76.5,89.1,78.5,93.1,78.5,93.1z M56.6,100.9l18.8-7.8c-0.7-1.6-1.7-4.3-1.2-6.6
  c1.1-5.7,1.8-12.5,1.2-13.7c-1.7-3.1-10.1-14.7-12.2-15.5c-0.8,0-1.3,0.4-1.6,0.6c0.4,1.2,0.6,2.4,0.9,3.4c0.3,1.4,0.6,2.6,1,3.6
  c0.3,0.7,0,1.5-0.7,1.8c-0.7,0.3-1.5,0-1.8-0.7c-0.6-1.3-0.9-2.7-1.2-4.2c-0.3-1.2-0.5-2.5-1-3.7c0,0,0-0.1-0.1-0.1
  c-0.6-1.6-2-2.8-3.4-4.3c-3.7-3.7-12.8-3.3-16.6-1.8c-1.6,0.6-1.7,1.5-1.7,1.7c-0.1,1.1,1,1.6,4.1,2.6c3.2,1,7.8,0.8,9.6,4.6
  c0.3,0.6,0.9,3.6,0.9,4.6c0.4,8.3-0.2,10.8-4.3,13.2c-3.1,1.2-7.2-0.9-8.8-5.1c-1-2.6-2-5.4-3.3-6.8C34,65.4,32.3,65,31.3,65
  c-0.5,0-0.8,0.1-0.9,0.2c0.1,0.3,0.4,0.9,0.6,1.4c0.9,1.8,2.2,4.5,1.9,8.4c-0.4,4.6,15.3,17.5,20.3,21.4
  C55,98,56.6,100.9,56.6,100.9z">

        <animate id="animation1" begin="0.8s" attributeName="opacity" from="1" to="0" dur="0.5s" fill="freeze"/>

    </path>

 <path style="opacity:0" d="M76.9,87.2c0.5-2.9,2.1-12.7,0.8-15.2c-0.1-0.2-10.6-16.5-14.3-16.5c-0.9,0-1.6,0.2-2.3,0.5c-0.5-2.9-1-6-1.2-8.5
  c-0.4-5.3-1.3-8.5-4.9-8.9c-0.5-0.1-1.3,0-2.1,0.7c-2.1,2-3.3,8.3-2.8,16.2c0.6,12.3-1.1,20.5-3.2,21.3c-1.3,0.5-4-2.2-6.1-4.3
  c-2.1-2.2-4.3-4.4-6.6-5.4c-2.7-1.1-5.5-0.5-7.1,0.5c-1,0.7-1.6,1.6-1.6,2.6c0,1.3,1,2.1,2.1,3.1c1.3,1.1,3.2,2.6,4.3,5.6
  c2.1,5.7,18.3,18.5,20.2,20c2.2,1.6,3,4.1,3,4.1l0.4,1.4l23.7-10l-0.8-1.3C77.9,92.2,76.5,89.2,76.9,87.2z M57.2,100.9
  c-0.6-1.2-1.6-2.8-3.4-4.1C49,93,36.1,82.3,34.5,78.1c-1.3-3.7-3.6-5.5-5.1-6.8c-0.4-0.3-0.9-0.8-1.1-1c0.1-0.1,0.3-0.3,0.8-0.5
  c0.9-0.4,2.6-0.7,4.2,0c1.8,0.7,3.7,2.8,5.7,4.7c3.1,3.2,6,6.2,9,5c5.6-2.3,5.1-18.9,4.9-24c-0.5-8.9,1.2-13.5,2-14.1
  c0.9,0.1,2,0.4,2.4,6.4c0.4,5.9,2.3,15.5,3.9,19.2c0.3,0.7,1.1,1,1.8,0.7c0.7-0.3,1-1.1,0.7-1.8c-0.6-1.3-1.3-3.9-2-6.8
        c0.3-0.3,0.8-0.6,1.6-0.7c2.1,0.8,10.3,12,12,15.1c0.6,1.1-0.1,7.8-1.1,13.4c-0.5,2.3,0.5,4.9,1.2,6.5L57.2,100.9z">

         <animate id="animation2" begin="0.8s" attributeName="opacity" from="0" to="1" dur="1.3s" fill="freeze"/>

    </path>

</svg>

But this is just a workaround, and I'm not really finding much on the internet about "real" svg animations, which transform paths into, well other paths...so maybe one of you has an neat idea :) - thx in advance

A: To animate paths you need paths with the same number and types of command. Both paths start with an M but in the first path the second command is an l and in the second path its a c. Your paths are therefore not interpolatable by the UAs SMIL engines.
After you've fixed that you need to put the other path in the to or values attribute of the animate tag of the first path.


text:
Q: How to divide two negative numbers using the two's complement method? I was studying more about binary arithmetics and came across the problem -21/-3. The expected answer is 7. Of course I know we can do it by canceling the negative sign and dividing 21 by 3. I have seen the beauty of two's complement in the subtraction of two numbers.
So i started out like this:
-21 is: 11101011
-3  is: 11111101

Initially I tried out dividing but as numerator is greater than denominator division is not possible. Also it is clear that it is the equivalent of dividing 235 by 253. So my question is how can I divide two negative numbers using two's complement method. Is this division allowed or isn't it possible to divide like this?


text:
Q: Generate DateRow for every row in a dataset Dim diaryreader As SqlDataReader

diarycmd.CommandText = "dashboardusers"
diarycmd.CommandType = CommandType.StoredProcedure
diarycmd.Connection = usersconn
diaryconn.Open()
diaryreader = diarycmd.ExecuteReader()

Dim diaryTable As DataTable = New DataTable()

diaryTable.Load(diaryreader)

Dim dr As DataRow
for each (dr in diaryTable.rows)
Next

This is not working, I am getting a syntax error when i try to do for each dr in diarytable.rows

A: why don't you use data table instead ? you will just have to iterate through the table
foreach(DataRow dr in ds.Tables[0].Rows)...

A: You get errors because your braces are set wrong. This would work:
Dim dr As DataRow
For Each dr In diaryTable.Rows
Next

A: ds.Tables(0).Rows.Count retrieves the number of rows available in the DataTable. Then you can simply iterate over that count.


text:
Q: Different response format depending on get parameter A have an entity, but i need to represent it in two really different ways. Now filters seems different too, but i think of future and don't want to duplicate endpoints from the start. So i think of one endpoint.
But it seems very unclear to api client, isn't?
For example, request for user/partners should give one data response, and user/partners?custom=true gives another response data. I mean not different attributes, that can be done with query for 'fields=attribute1,attribute2'. I mean they have different entity format, that can have same or different attributes with same or different format of representation. For example, attributes username for first request can return simply login, but for second request return array of subattributes.
So is it good idea to have such different response formats in one endpoint or should i separate them from the start?

A:
So is it good idea to have such different response formats in one endpoint or should i separate them from the start?

General purpose HTTP clients don't care about "endpoints".
/abcde
/abcde?format=text
/abcde?format=json

As far as a general purpose client is concerned, these are different identifiers, that are used to look up different resources (aka "documents").
Whether or not requests for these resources is handled by the same "endpoint" is just an implementation detail.  From the outside, it makes no difference whether each resource has its own endpoint, or if some resources share an endpoint, or if all resources use the same endpoint.
What that means is that judgment of whether or not sharing an endpoint is a good idea depends on balancing other factors

*

*which spelling produces higher internal code quality (which is going to depend somewhat on the idioms used by your routing framework)

*which spelling is more convenient for human operators reviewing the access logs

*which spelling is more amenable to documentation

The right answer in the human interfaces is likely to be dependent on how these resources fit into the domain (are the really variations of a common document? or are they different documents that just happen to be derived from a common data set?).


text:
Q: Shadows doesn't disappear I made an endless runner game where the horse runs in a canyon. So i noticed that in the walls makes shadows on theirselves so i wanted to remove it beacuse it's ugly. So my problem comes here, how can i remove that shadow even if i disabled the shadow casting from the mesh renderer of that walls? I also tried to place a light point near the walls but it still don't work. How can i resolve this. I attach a photo so you can understand what i am talking about.
Picture

A: Those are most likely just objects interacting with a directional light in the scene. Instead of shadows, those are just sides of objects that as less illuminated.
I can throw in two potential solutions:
Solution1:
Go to Window->Rendering->Lighting, select Environment, change the Environment Lighting Source value and modify the color values to your liking.

Solution2:
Add a material which changes how the objects interact with lighting. One option could be to just add a standard material with some emission.


text:
Q: Adding JSON in the specified place by JSONPath I'm getting JSON and JSONPath from a user. The user also giving me a new content (value or object) that he want add to his JSON. I'm trying to create a method which will add new content to the path specified by JSONPath.
Method input: json, jsonpath, newcontent(string)
Method output: new json with added newcontent
JSON example
{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ]
  }
}

JSONPath example
$.store

Object to add
movie [title : The Godfather]

Method returns
{ "store": {
    "book": [
      { "category": "reference",
        "author": "Nigel Rees",
        "title": "Sayings of the Century",
        "price": 8.95
      },
      { "category": "fiction",
        "author": "Evelyn Waugh",
        "title": "Sword of Honour",
        "price": 12.99
      }
    ],
    "movie": [
      {
        "title" : "The Godfather"
      }
    ]
  }
}

A: You can do something like this:
string ApplyChange(string originalJson, string path, string jsonToAdd)
{
    var root = JObject.Parse(originalJson);
    var node = root.SelectToken(path);
    switch (node.Type)
    {
        case JTokenType.Object:
        {
            var objectToMerge = JObject.Parse("{" + jsonToAdd + "}");
            ((JObject)node).Merge(objectToMerge);
            break;
        }
        case JTokenType.Array:
        {
            var objectToMerge = new JArray(JToken.Parse(jsonToAdd));
            ((JArray)node).Merge(objectToMerge);
            break;
        }
        default:
            throw new NotSupportedException();
    }
    return root.ToString();
}


text:
Q: I am having trouble outputting data to a dynamically generated table with VueJS I am generating a table dynamically with VueJS and everything works fine when it comes to the creation of the  elements.
To set them up, I have a Vue component, which is getting outputted by calling the addRow function. It uses templates with values which are taken from two input fields, namely "Please add service" and "Please enter price". The values are added to an array on the data object and they are dynamically cleared so that more items can be added.
When I console log the array, what I have input and stored in the array as an object remains, regardless how many items. Their textual content is simply not in the new table rows.
The only clue I have after quite a bit of research is that the elements might not be reactive. However, they have getters and setters, which means that it is not likely. Another idea I had was, that it is related to scope.
Please advice further.
Here is my full code: https://codepen.io/MrYY/pen/PeJjZy
And here are the Vue instance and Vue component
Vue.component('table-row', {
    template: '\
\
    \
      {{ this.name }}\
    	\
    \
      {{ this.price }}\
    	\
    \
\
  ',
  props: ['row']
 })

var app = new Vue({

    el: '#app',

    data: {
        companyName: "Company Name",
        repName: "Representative's name",
        phone: "+359-00-000-0000",
        newService: "Please add service",
        price: "Please enter price",
        services: [

        ]
    },

    methods: {

        addRow: function () {
            this.services.push({
                servicesName: this.newService,
                price: this.price
            });
            this.newService = "Please add service";
            this.price = "Please enter price";
        }
    }

})

A: You can add service as a props for your component

Vue.component('table-row', {
    template: '\
\
    \
      {{ service.servicesName }}\
    	\
    \
      {{ service.price }}\
    	\
    \
\
  ',
  props: ['service']
 })


text:
Q: Should I make my CustomException serializable? I'm defining a custom exception class to signal to my handler for a specific action to be taken. I'm wondering if I should make my exception Serializable or not. I don't intend to use the exception as anything more than an exit from my current execution.
(and yes, I do need a custom exception class. I'm pretty sure about that)

A: The best practice is to make them serializable. This way they can be serialized across AppDomain, or even process, boundaries.


text:
Q: error with gdalbuildvrt, in Python I am new to python/GDAL and am running into perhaps a trivial issue.  This may stem from the fact that I don't really understand how to use GDAL properly in python, or something careless, but even though I think I am following the help doc, I keep getting a syntax error when trying to use "gdalbuildvrt".
What I want to do is take several (amount varies for each set, call it N) geotagged 1-band binary rasters [all values are either 0 or 1] of different sizes (each raster in the set overlaps for the most part though), and "stack" them on top of each other so that they are aligned properly according to their coordinate information.  I want this "stack" simply so I can sum the values and produce a 'total' tiff that has an extent to match the exclusive extent (meaning not just the overlap region) of all the original rasters. The resulting tiff would have values ranging from 0 to N, to represent the total number of "hits" the pixel in that location received over the course of the N rasters.
I was led to gdalbuildvrt [http://www.gdal.org/gdalbuildvrt.html] and after reading about it, it seemed that by using the keyword -separate, I would be able to achieve what I need. However, each time I try to run my program, I get a syntax error. The following shows two of the several different ways I tried calling gdalbuildvrt:
gdalbuildvrt -separate -input_file_list stack.vrt inputlist.txt
gdalbuildvrt -separate stack.vrt inclassfiles

Where inputlist.txt is a text file with a path to the tif on every line, just like the help doc specifies. And inclassfiles is a python list of the pathnames. Every single time, no matter which way I call it, I get a syntax error on the first word after the keywords (i.e. 'inputlist' in inputlist.txt, or 'stack' in stack.vrt).
Could someone please shed some light on what I might be doing wrong? Alternatively, does anyone know how else I could use python to get what I need?
Thanks so much.

A: gdalbuildvrt is a GDAL command line utility. From your example its a bit unclear how you actually run it, but when running from within Python you should execute it as a subprocess.
And in your first line you have the .vrt and the .txt in the wrong order. The textfile containing the files should follow directly after the -input_file_list.
From within Python you can call gdalbuildvrt like:
import os
os.system('gdalbuildvrt -separate -input_file_list inputlist.txt stack.vrt')

Note that the command is provided as a string. Using a Python list with the files can be done with something like:
os.system('gdalbuildvrt -separate stack.vrt %s') % ' '.join(data)

The ' '.join(data) part converts the list to a string with a space between the items.
Depending on how your GDAL is build, its sometimes possible to use wildcards as well:
os.system('gdalbuildvrt -separate stack.vrt *.tif')


text:
Q: Is it possible to use wildcards in SQL Server Stored Proc parameters? I am working with a Stored Proc with takes several parameters. It turns out, though, that for one of the params, I need to loop through a list of items and call the SP multiple times. But as I pass the SP every possible value of that type, it would seem more efficient (and simpler) to just bypass the parameter by saying "get them all" by means of a wildcard.
Is it possible to do that, such as with a "*" or a "%" or something?
Theoretically (based on the research I've done), "%" should work, but in my case it's not returning any records. Am I doing something wrong, with this code:
. . .
new SqlParameter()
{
    ParameterName = "@Member",
    SqlDbType = SqlDbType.VarChar,
    Value = '%'
},
. . .

?

A: No.   Without being able to modify the stored procedure code, there is nothing you can pass as a parameter that will act like a wild card.


text:
Q: How to get Min Date and Next to min date from the same table in SQL Server I have a table
create table temp1
(
   GroupId int,
   DateCol Date,
   ValueCol int,
)
insert into temp1 values(1,'2016-1-1',10);
insert into temp1 values(1,'2017-1-1',20);
insert into temp1 values(1,'2018-1-1',30);
insert into temp1 values(2,'2016-5-1',101);
insert into temp1 values(2,'2017-5-1',102);
insert into temp1 values(2,'2018-5-1',103);

I want to get a date range (min to next to min) grouped by GroupId column:
ValueCol DateCol      DateColNextToMin
111      (min Date)   (next to Min Date)

GroupId ValueCol DateCol      DateColNextToMin
1         10     2016-1-1         2017-1-1
2         101    2016-5-1         2017-5-1

How can I do this?
I tried to get thorough windows function , pivot etc, but there seems to be no such elegant solution.

A: try this,
DECLARE @table Table
(
   GroupId int,
   DateCol Date,
   ValueCol int
)

INSERT INTO @table
VALUES
     (111,  '01-Aug-2016', 0)
    ,(111,  '02-Aug-2016', 0)
    ,(111,  '03-Aug-2016', 0)
    ,(111,  '04-Aug-2016', 0)
    ,(112,  '05-Aug-2016', 0)
    ,(112,  '06-Aug-2016', 0)
    ,(112,  '07-Aug-2016', 0)
    ,(112,  '08-Aug-2016', 0)

;WITH CTE AS
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY DateCol ASC) AS RowNo
    FROM  @table
)
SELECT c1.GroupId, c1.ValueCol, c1.DateCol, c2.DateCol
FROM CTE c1
INNER JOIN CTE c2 ON c1.GroupId = c2.GroupId
    AND c1.RowNo = 1
    AND c2.RowNo = 2


text:
Q: Finding MultiIndex indices for a given cross-section Say I have a MultiIndex DataFrame:
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
                          'foo', 'bar', 'foo', 'foo'],
                   'B' : ['one', 'one', 'two', 'three',
                          'two', 'two', 'one', 'three'],
                   'C' : randn(8), 'D' : randn(8)})

df = df.set_index(['A', 'B']).sort_index()
                  C         D
A   B
bar one    0.052069 -0.541728
    three -1.703340  0.369047
    two   -0.221340  1.281790
foo one    0.219942  0.093917
    one   -2.531077  0.445473
    three  0.243135 -1.730576
    two   -1.464053  1.241126
    two   -0.846171 -1.444660

I would like to retrieve the indices of df where the second level index is two or three
How can I do that?
Update
Strangely enough, even though Jeff's answer works well for my example above, it doesn't with my real data:
> cfs_rates.index.get_level_values('B')
Out: Index([u'oXliPbXGWx', u'oXliPbXGWx', u'oXZR1VqRIH', u'oXZR1VqRIH', u'oXUMJNEcAm', u'oXUMJNEcAm', u'oXrC6luflN', u'oXrC6luflN', u'oXACDVffiH', u'oXACDVffiH', u'oXACDVffiH', u'oXMRMtC2lS', u'oXMRMtC2lS', u'oX0S45QSwf', u'oXkZVG9UEV', u'oXqs51fyxc', u'oXuLgFLVJR', u'oXiU9xrYbc', u'oXiU9xrYbc', u'oXiU9xrYbc', u'oX7rgkbLNN', u'oX7rgkbLNN', u'oXLoIyg0yU', u'oXLoIyg0yU', u'oXKcAKwKck', u'oXKcAKwKck', u'oX6EN5aKhZ', u'oX6EN5aKhZ', u'oXFyCRPD5D', u'oXFyCRPD5D', u'oXITpFj1sg', u'oXITpFj1sg', u'oXQUn2dSZ3', u'oXQUn2dSZ3', u'oXTALtx9yg', u'oXaLPOroxI', u'oXAxkDpC1q', u'oXCylQYlOG', u'oXVVE8zpgZ', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXGBjTephd', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', u'oXpOOA612p', ...], dtype='object')

> df.index.get_level_values('B').unique()
Out: array(['oXliPbXGWx', 'oXZR1VqRIH', 'oXUMJNEcAm', 'oXrC6luflN',
       'oXACDVffiH', 'oXMRMtC2lS', 'oX0S45QSwf', 'oXkZVG9UEV',
       'oXqs51fyxc', 'oXuLgFLVJR', 'oXiU9xrYbc', 'oX7rgkbLNN',
       'oXLoIyg0yU', 'oXKcAKwKck', 'oX6EN5aKhZ', 'oXFyCRPD5D',
       'oXITpFj1sg', 'oXQUn2dSZ3', 'oXTALtx9yg', 'oXaLPOroxI',
       'oXAxkDpC1q', 'oXCylQYlOG', 'oXVVE8zpgZ', 'oXGBjTephd',
       'oXpOOA612p', 'oX5xyjSEFu', 'oXNwnfODmx', 'oXc8Ef8RKp',
       'oXhSJGS9Vt', 'oX77EAPM90', 'oXJKFMxpGM', 'oXM2A7Ovs4',
       'oXMBaAdS6P', 'oXXd1TFOds', 'oXgYwsBEeU', 'oXhg0Z4v70',
       'oXmHmreVWq', 'oXpoPZHbcL', 'oXyn2Vy5Ds', 'oXLnKg7f0H',
       'oXG3N1BGRa', 'oXFgSNVf7X', 'oXSsJ9RQHM', 'oXQEX8u59U',
       'oXfn4xmkVR', 'oXirJeA6KV', 'oXTnLZFeoD', 'oXDjBE1tFg',
       'oXldRy7GrP', 'oXHtACeymW', 'oXTLupWtgO', 'oXZXJUUeUT',
       'oX6NjO05Ty', 'oXTNJtiaQH', 'oXX3eZpIT3', 'oXhPkfjnXY',
       'oXRNaqcssj', 'oXAe1bhLMy', 'oX0Yza7hgx', 'oXyG1ZiLFU',
       'oXd8fKbi5l', 'oXDNPZtUhk', 'oXml3RS3Z2', 'oX1X1ml8m3',
       'oXtRvKMbnu', 'oXh0xGRkfR', 'oXm2HJOqUT', 'oXqw4GB40Q',
       'oX5Q9UXh7V', 'oXMO23wBzX'], dtype=object)

> df.index.get_level_values('B').isin('oX6NjO05Ty').any()
Out: False

Notice, however that oX6NjO05Ty is there (it's in one of the unique entries above). In fact, this statement
entries = cfs_df.xs(`oX6NjO05Ty`, level='B')

does retrieve the entries correctly!

A: You can do this, but normally we don't use the actual indices (e.g. the integer indexes).
What is your goal?
In [10]: df[df.index.get_level_values('B').isin(['two','three'])]
Out[10]:
                  C         D
A   B
bar three  2.198031  0.329089
    two   -0.351223  2.271017
foo three  0.165734  1.638998
    two   -0.481800  0.379457
    two    1.658409 -0.390166

[5 rows x 2 columns]

In [11]: df.reset_index()[df.index.get_level_values('B').isin(['two','three'])]
Out[11]:
     A      B         C         D
1  bar  three  2.198031  0.329089
2  bar    two -0.351223  2.271017
5  foo  three  0.165734  1.638998
6  foo    two -0.481800  0.379457
7  foo    two  1.658409 -0.390166

[5 rows x 4 columns]

In [12]: df.reset_index()[df.index.get_level_values('B').isin(['two','three'])].index
Out[12]: Int64Index([1, 2, 5, 6, 7], dtype='int64')

A: How about this?
grp = df.groupby('B')
output = pd.concat(d for k,d in grp if k in ['two','three'])

output:
     A      B         C         D
3  bar  three -2.110673 -0.009817
7  foo  three -2.249249  1.396641
2  foo    two -1.531507  2.628120
4  foo    two -0.165092 -0.642685
5  bar    two -0.346419  0.960303