text:
Q: ANTLR 4 - Grammar Rule for string to support whitespace and special char i am not experienced and still learning about grammar. i just need an example grammar that support for whitespace and special character like !,",#,$,^,&.
Because with my current grammar and the rules inside i cant print out some string that support white space and special symbol. i know whitespace are tossed).
For example if i give input : Hello      World!!!!!
the output is HelloWorld <-- the whitespace & char (!) tossed
look at this image :
problem
why??
here is my current grammar example.g4
    string
    : '"' (~'"'|'\"')* '"'
    ;

Id
    : Letter(Letter|Digit)*
    ;

Num
    : Digit
    ;

fragment
    Digit
    : [0-9]+
    ;

Letter
    : [a-zA-Z]
    ;

LINE_COMMENT
    : '//' ~[\r\n]* -> skip
    ;

i was read this link :
ANTLR parse strings (keep whitespaces) and parse normal identifiers
but i cant understand what happen. i need an advice. thanks.

A: Finnaly i found someone who give me solution.
he is jim
and here his solution :
You are declaring your rule for string as a parser rule.
Lexer rules should begin with UPPER CASE: STRING : ....
You Letter rules is not a fragment, so it conflicts with Id
You have not specified what to do with whitespace in your lexer, so it will just not match and give an error.
Find one of the online tutorials, or buy the book, or better still, do both. Jim

now my problem solved, i can print out string with whitespace inside.


text:
Q: Integral Closure of Ring $k[t,s]/(s^2 -t^2(1+t))$
Let $X$ be the affine curve $\operatorname{Spec}k[t,s]/(s^2 -t^2(1+t))$.
How to verify that the normalization $X'$ of $X$ is $\operatorname{Spec}k[u]$ with $u:= s/t$ and $u^2=1+t$?

We know that since the normalization $n: X' \to X$ is an affine map, $X'$ is an affine scheme $\operatorname{Spec}A$ with $A$ integral closure of $k[t,s]/(s^2 -t^2(1+t))$ in $\operatorname{Frac}\bigl(k[t,s]/(s^2 -t^2(1+t))\bigr)$.
Is there any standard strategy to calculate integral closure of rings $R:= k[x,y]/(P(x,y))$ in $\operatorname{Frac}(R)$?

A: Prove that the normalisation of $A=k[X,Y]/(Y^2-X^2-X^3)$ is $k[t]$ where $t=Y/X$ (Reid, Exercise 4.5)
Characterizing the field of fractions of $\mathbb Q[x,y]/(x^2+y^2-1)$.
Working out the normalization of $\mathbb C[X,Y]/(X^2-Y^3)$
$\mathbb{Q}[x,y]/(x^2+y^2)\cong \mathbb{Q}[y,yi]$?
As in the above links, I think it seems easier when we find an isomorphic subring in a polynomial ring. In your case,
we first define a ring homomorphism, $\phi : k[t,s]\rightarrow k[u]$ given by $\phi(t)=u^2-1,\phi(s)=u(u^2-1)$. Then $\ker\phi=(s^2-t^2(1+t))$ and $k[t,s]/(s^2-t^2(1+t))\cong k[u^2-1,u(u^2-1)]\hookrightarrow k[u]$ and $\mathrm{Frac}(k[u^2-1,u(u^2-1)]=\mathrm{Frac}(k[u])=k(u)$. So we first  may need to parametrize variables very well. Proving the equality of the kernel is not really obvious to me and the method used in the following link and comments on that would be helpful
The kernel of $\mathbb{Q}[x,y]\rightarrow \mathbb{Q}(t)$ is $(x^2+y^2-1)$.
Another strategy is
The field of fractions of $\mathbb{R}[x,y]/(x^2+y^2-1)$ is $\mathbb{R}(x)[y]/(x^2+y^2-1)$
Showing $F[x,y]/(ax^2+by^2-1)$ is a Dedekind domain

redpajama_set_name: RedPajamaStackExchange


text:
Q: Split Strings with Multiple Delimiters and Concat I'd like to print out all possible sentences from this kind of strings below. What is the best way to do it?
[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend

*

*my best friend is

*your best friend is

*his best friend is

*her best friend is

*my true friend is

*your true friend is

*his true friend is

*her true friend is

*who is your best friend

*who is her best friend

*who is his best friend

*who is your true friend

*who is her true friend

*who is his true friend

*where is your best friend

*where is her best friend

*where is his best friend

*where is your true friend

*where is her true friend

*where is his true friend

A: There's no builtin functions for what you need. So you need to make a solution.
First of all you need to split this task into more trivial parts.
One part would accept array of arrays and perform combination on it:
// Converts [['a'], ['b', 'c']] to ['ab', 'ac']
const combination = (parts) => {
  let current = [[]]
  parts.forEach(v => {
    let result = []
    current.forEach(c => {
      v.forEach(n => {
        result.push(c.concat(n))
      })
    })
    current = result
  })
  return current.map(v => v.join(' '))
}

The other part needs to convert your input into array of arrays and format an output:

const generate = (formats) => {
  let result = []

  // Converts [['a'], ['b', 'c']] to ['ab', 'ac']
  const combination = (parts) => {
    let current = [[]]
    parts.forEach(v => {
      let result = []
      current.forEach(c => {
        v.forEach(n => {
          result.push(c.concat(n))
        })
      })
      current = result
    })
    return current.map(v => v.join(' '))
  }
  formats.split('|').forEach((format) => {
    let parts = format
      .split(/[\]\[\)\(]/) // split "[a] (b) c" to ["a", "b", "c"]
      .filter(String) // remove empy elements
      .map(s => {return s.trim()})
      .filter(String) // there can be empty strings. remove those too
    parts = parts.map(part => {return part.split('/')})
    result = result.concat(combination(parts))
  })
  return result
}

let input = "[my/your/his/her] (best/true) friend is | [who/where] is [your/her/his](best/true) friend"
generate(input).forEach((v, i) => {console.log((i+1) + '. ' + v)})

This is pretty much you need. Though there are some corner cases that should be covered and a little problem with line .split(/[\]\[\)\(]/). But I'm sure you can fix it.


text:
Q: Search for specific words in order on Firefox I searched for add-ons to search for multiple words in Firefox/Chrome, to no success. I've programmed some html, a lot of Access, and some SQL in the past. I have no experience in Java, but can understand it.
I'm trying to write a simple javascript to use in the Firefox console to search a html file with a huge amount of info in it. Many many lines of info start with "//" and end with "]"
The search will consist of a starting field "//" , the word within the range I'm looking for, and end field "]", to build the find. They have to be in this order, but obviously not being the next word.
Can someone point me to an existing process to do this or write something up?
Thank you,
Jeff
I've tried function find, function findstring, etc.. but again, I don't know enough of how to truly write it out as it doesn't appear to give auto-sample of how the command is to be written out.
My thought could be too complex, but it goes as this.

*

*Find '//'.

*Count characters from '//' to 'word' = Count1

*Count characters from '//' to next ']' = Count2

*If Count1 < Count2 then true else false. (if true count these results)

*repeat until end of page, or the process automatically counts all results like a basic find would do.


text:
Q: Converting Imperative to Functional style paradigm using Ramdajs The following script create an object filtering some input data.
It is coded in a declarative way using several nested forEach.
I would like to know which API to use in rewritting this code using ramdajs or lodash, specially I would be interested in understand if use of pipe is appropriate in this case otherwise another way.
An example of code would be appreciate (specially for ramdajs). Thanks.

  var data = {
    "type": "stylesheet",
    "stylesheet": {
      "rules": [{
        "type": "keyframes",
        "name": "bounce",
        "keyframes": [{
          "type": "keyframe",
          "values": [
            "from",
            "20%",
            "53%",
            "80%",
            "to"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "animation-timing-function",
            "value": "cubic-bezier(0.215, 0.610, 0.355, 1.000)",
            "position": {
              "start": {
                "line": 3,
                "column": 5
              },
              "end": {
                "line": 3,
                "column": 72
              }
            }
          }, {
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0,0,0)",
            "position": {
              "start": {
                "line": 4,
                "column": 5
              },
              "end": {
                "line": 4,
                "column": 34
              }
            }
          }],
          "position": {
            "start": {
              "line": 2,
              "column": 3
            },
            "end": {
              "line": 5,
              "column": 4
            }
          }
        }, {
          "type": "keyframe",
          "values": [
            "40%",
            "43%"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "animation-timing-function",
            "value": "cubic-bezier(0.755, 0.050, 0.855, 0.060)",
            "position": {
              "start": {
                "line": 8,
                "column": 5
              },
              "end": {
                "line": 8,
                "column": 72
              }
            }
          }, {
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0, -30px, 0)",
            "position": {
              "start": {
                "line": 9,
                "column": 5
              },
              "end": {
                "line": 9,
                "column": 40
              }
            }
          }],
          "position": {
            "start": {
              "line": 7,
              "column": 3
            },
            "end": {
              "line": 10,
              "column": 4
            }
          }
        }, {
          "type": "keyframe",
          "values": [
            "70%"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "animation-timing-function",
            "value": "cubic-bezier(0.755, 0.050, 0.855, 0.060)",
            "position": {
              "start": {
                "line": 13,
                "column": 5
              },
              "end": {
                "line": 13,
                "column": 72
              }
            }
          }, {
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0, -15px, 0)",
            "position": {
              "start": {
                "line": 14,
                "column": 5
              },
              "end": {
                "line": 14,
                "column": 40
              }
            }
          }],
          "position": {
            "start": {
              "line": 12,
              "column": 3
            },
            "end": {
              "line": 15,
              "column": 4
            }
          }
        }, {
          "type": "keyframe",
          "values": [
            "90%"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0,-4px,0)",
            "position": {
              "start": {
                "line": 18,
                "column": 5
              },
              "end": {
                "line": 18,
                "column": 37
              }
            }
          }],
          "position": {
            "start": {
              "line": 17,
              "column": 3
            },
            "end": {
              "line": 19,
              "column": 4
            }
          }
        }],
        "position": {
          "start": {
            "line": 1,
            "column": 1
          },
          "end": {
            "line": 20,
            "column": 2
          }
        }
      }, {
        "type": "rule",
        "selectors": [
          ".bounce"
        ],
        "declarations": [{
          "type": "declaration",
          "property": "animation-name",
          "value": "bounce",
          "position": {
            "start": {
              "line": 23,
              "column": 3
            },
            "end": {
              "line": 23,
              "column": 25
            }
          }
        }, {
          "type": "declaration",
          "property": "transform-origin",
          "value": "center bottom",
          "position": {
            "start": {
              "line": 24,
              "column": 3
            },
            "end": {
              "line": 24,
              "column": 34
            }
          }
        }],
        "position": {
          "start": {
            "line": 22,
            "column": 1
          },
          "end": {
            "line": 25,
            "column": 2
          }
        }
      }, {
        "type": "keyframes",
        "name": "spark",
        "keyframes": [{
          "type": "keyframe",
          "values": [
            "0%",
            "50%"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0,0,0)",
            "position": {
              "start": {
                "line": 29,
                "column": 5
              },
              "end": {
                "line": 29,
                "column": 34
              }
            }
          }],
          "position": {
            "start": {
              "line": 28,
              "column": 3
            },
            "end": {
              "line": 30,
              "column": 4
            }
          }
        }, {
          "type": "keyframe",
          "values": [
            "100%"
          ],
          "declarations": [{
            "type": "declaration",
            "property": "transform",
            "value": "translate3d(0,-4px,0)",
            "position": {
              "start": {
                "line": 32,
                "column": 5
              },
              "end": {
                "line": 32,
                "column": 37
              }
            }
          }],
          "position": {
            "start": {
              "line": 31,
              "column": 3
            },
            "end": {
              "line": 33,
              "column": 4
            }
          }
        }],
        "position": {
          "start": {
            "line": 27,
            "column": 1
          },
          "end": {
            "line": 34,
            "column": 2
          }
        }
      }, {
        "type": "rule",
        "selectors": [
          ".spark"
        ],
        "declarations": [{
          "type": "declaration",
          "property": "animation-name",
          "value": "spark",
          "position": {
            "start": {
              "line": 37,
              "column": 3
            },
            "end": {
              "line": 37,
              "column": 24
            }
          }
        }, {
          "type": "declaration",
          "property": "transform-origin",
          "value": "center center",
          "position": {
            "start": {
              "line": 38,
              "column": 3
            },
            "end": {
              "line": 38,
              "column": 34
            }
          }
        }],
        "position": {
          "start": {
            "line": 36,
            "column": 1
          },
          "end": {
            "line": 39,
            "column": 2
          }
        }
      }],
      "parsingErrors": []
    }
  };
  var result = {};
  var kfs = data.stylesheet.rules.filter(function(rule) {
    return rule.type === 'keyframes'
  });

  kfs.forEach(function(kf) {
    result[kf.name] = [];
    kf.keyframes.forEach(function(kfi) {
      kfi.values.forEach(function(v) {
        var r = {};
        var vNew;
        vNew = v;
        if (v === 'from') {
          vNew = 0;
        } else if (v === 'to') {
          vNew = 100;
        } else {
          vNew = parseFloat(v);
        }
        r.offset = vNew;
        kfi.declarations.forEach(function(d) {
          r[d.property] = d.value;

        });
        result[kf.name].push(r);
      });
    });
  });
  console.log(result);

EDIT:
So far I was able to achieve this result in ramdajs:
    var rulesLense = R.lensPath(['stylesheet', 'rules']);
    var ruleView = R.view(rulesLense, obj);
    var keyframes = R.filter(R.propEq('type', 'keyframes'));
    var groupByKeyframe = R.groupBy(keyframe => {
        return R.prop('name', keyframe);
    });

    var process = R.pipe(
        keyframes,
        groupByKeyframe
    );
    var result = process(ruleView);

A: Traversing complex structures by using just Ramda is hard but elegant. To modify a structure using lenses, applySpec and evolve is recommendable, these are very useful to return a new version of objects with modified values. But you are looking to transform the data in something very different to the original tree, which I assume is an AST. In Ramda, pipe and compose are essentials, it makes possible to structure the code by composing small functions. For working with trees I use converge for branching, objOf and zipObj to create new objects. Also map and reduce to work with lists.
I'm going to use the following composition strategy in this example:
          transformAST
               ^
               |
               |
      getContentOfKeyframes
         ^              ^
         |              |
         |              |
  processKeyframe   processAnimation

To start with, let's create a function that receives an array of values and an array of declarations, it returns an array which in the first position has an array of converted values, in the second position an object where the keys are the value of declaration property and the values are its corresponding declaration value.
var processKeyframe = (vals, declarations) => [
    // map each value
    R.map(R.cond([
        [R.equals('from'), R.always(0)],
        [R.equals('to'), R.always(100)],
        [R.T, parseFloat]
    ]), vals),
    // collect all property value pairs and merge in one object
    R.reduce(R.merge, {},
        R.map(R.converge(R.objOf, [
            R.prop('property'),
            R.prop('value')
        ]), declarations))
]

Now let's create a function to process animations, it receives an array of offsets and an object with transformations, returns an array of new objects with the signature {offset: offset, ...trasformations}.
var processAnimation = (offsets, transf) =>
    R.map(R.pipe(
        R.objOf('offset'),
        R.merge(transf)), offsets)

Next, map each keyframe by composing the two previous functions
var getContentOfKeyframes = R.map(R.pipe(
    // process keyframes
    R.converge(processKeyframe, [
        R.prop('values'),
        R.prop('declarations')
    ]),
    // process animations
    R.converge(processAnimation, [
        R.nth(0),
        R.nth(1)
    ])))

Finally, we define function that gets the needed properties from data, summarizes, each keyframe and finally gives the desired format in the last stage.
var transformAST = R.pipe(
    // get `stylesheet.rules` property
    R.path(['stylesheet', 'rules']),
    // get only object whose `type` property is `keyframes`
    R.filter(R.propEq('type', 'keyframes')),
    // map each item in `keyframes` collection
    // to an object {name: keyframe.name, content: [contentOfkeyframes] }
    R.map((keyframe) => ({
        name    : keyframe.name,
        content : getContentOfKeyframes(keyframe.keyframes)
    })),
    // finally make a new object using animation `name` as keys
    // and using a flatten content as values
    R.converge(R.zipObj, [
        R.map(R.prop('name')),
        R.map(R.pipe(R.prop('content'), R.flatten))
    ]))

Now you can process the AST directly passing the data object.
var result = transformAST(data)

All together.
var processKeyframe = (vals, declarations) => [
    R.map(R.cond([
        [R.equals('from'), R.always(0)],
        [R.equals('to'), R.always(100)],
        [R.T, parseFloat]
    ]), vals),
    R.reduce(R.merge, {},
        R.map(R.converge(R.objOf, [
            R.prop('property'),
            R.prop('value')
        ]), declarations))
]

var processAnimation = (offsets, transf) =>
    R.map(R.pipe(
        R.objOf('offset'),
        R.merge(transf)), offsets)

var getContentOfKeyframes = R.map(R.pipe(
    R.converge(processKeyframe, [
        R.prop('values'),
        R.prop('declarations')
    ]),
    R.converge(processAnimation, [
        R.nth(0),
        R.nth(1)
    ])))

var transformAST = R.pipe(
    R.path(['stylesheet', 'rules']),
    R.filter(R.propEq('type', 'keyframes')),
    R.map((keyframe) => ({
        name    : keyframe.name,
        content : getContentOfKeyframes(keyframe.keyframes)
    })),
    R.converge(R.zipObj, [
        R.map(R.prop('name')),
        R.map(R.pipe(R.prop('content'), R.flatten))
    ]))

var result = transformAST(data)

A: My version ends up looking quite different from the one by Yosbel Marin.
const transform = pipe(
  path(['stylesheet', 'rules']),
  filter(where({'type': equals('keyframes')})),
  groupBy(prop('name')),
  map(map(kf => map(kfi => map(v => assoc('offset', cond([
      [equals('from'), always(0)],
      [equals('to'), always(100)],
      [T, parseFloat]
    ])(v), pipe(
        map(lift(objOf)(prop('property'), prop('value'))),
        mergeAll
    )(kfi.declarations)), kfi.values), kf.keyframes)
  )),
  map(flatten)
);

I did this as a code port without really trying to understand your data at all.  (I was having a hard time doing so, this was at least in part a necessity, but it's also an interesting way to proceed.)
The first two steps should be clear, and they are very similar to the previous answer.  We grab the data from data.stylesheet.rules, then we filter it to only include those rules whose "type" property is "keyframes".  (I chose to use where in my filter, as I find the following more readable than propEq: filter(where({'type': equals('keyframes')})), but they work the same.  This is followed by groupBy(prop('name')), which leaves us with a structure like:
{
  bounce: [obj1, obj2, ...]
  spark: [objA, objB, ...]
}

The next bit is the heart of the transformation.  I converted each of the forEach calls in the original into map calls (obviously one can't always do this.)
This:
map(v => map(lift(objOf)(prop('property'), prop('value'))), kfi.declarations)

turns a declarations section into something like
[
  {"animation-timing-function": "cubic-bezier(0.215, 0.610, 0.355, 1.000)",}
  {transform: "translate3d(0,0,0)"},
]

by lifting the objOf function from working on scalar values to work on functions that return such values, and then passing in two functions which will accept a declaration.  This new function then accepts a declaration and returns an object.  Mapping it over a list of declarations gets a list of objects.  Putting it into a pipe call with mergeAll turns such a list into a single object.
And this bit replaces the if (v === 'from') { ... } else if ... code with a single expression:
cond([
  [equals('from'), always(0)],
  [equals('to'), always(100)],
  [T, parseFloat]
])(v)

that returns 0, 100, or the result of parseFloat(v), as appropriate.
Combining this with assoc('offset') and the result from the previous step we get the main objects in the result such as:
{
  "animation-timing-function": "cubic-bezier(0.215, 0.610, 0.355, 1.000)",
  offset: 0,
  transform: "translate3d(0,0,0)"
}

The only thing left to do is to clean up the nested lists left by all those maps:
{
  bounce: [[[obj1, obj2, ...]]]
  spark: [[[objA, objB, ...]]]
}

which we do by adding map(flatten).
You can see this in action on the Ramda REPL.
I have no idea if this could reasonably be made entirely points-free.  I am guessing that it would be difficult at best, and that it would end up much less readable.  This code might do well with factoring some of the functions that are being mapped into their own calls, but I'll leave that as an exercise for the reader!


text:
Q: How to update Firefox Add-ons when using Firefox in a sandbox? The SELinux sandbox works like this: If I start Firefox in a sandbox then the original Firefox directory gets copied to a temporary place, and any changes done in the sandboxed Firefox get's deleted if I close the browser.
But I always want to use the sandboxed Firefox. This means that if there are any updates to a Firefox Add-on, they will be updated in the sandbox, but the updates will be deleted when I close the browser, and when I next open the sandboxed firefox the old add-ons will be used...
I think that updating firefox Add-ons could be done via the repositories of the OS, but.. I didn't found them using "yum search all adblock", for example.
Are there any ways to solve this problem? I always need to use fresh Firefox Add-ons!

A: The easiest solution is to launch Firefox out of the sandbox, update your addons through the about:addons page, and close it again.
You can't update them through yum cause they're not part of your OS distribution, but are just Firefox addons.


text:
Q: Can I affect instance variables/properties from within a block? I have defined an array variable using @property (strong, nonatomic) __block NSArray *users;, and I try to change it inside a block using self.users = ...;. The block is sent as a parameter to [NSURLConnection sendAsynchronousRequest:queue:completionHandler]. The sendAsynchronousRequest method is called from a method which is called in the viewDidLoad method of my "Table View Controller".
When I call [awesomeObject.users count] I get 0.
As a slight tangent, do I need to implement the NSURLConnection delegate methods didReceiveResponse, didReceiveData and connectionDidFinishLoading when using sendAsynchronousRequest?
Edit:
Right. I just realized that numberOfRowsInSection is being called before the block executes. I had forgotten to add a notification to tell the table view to reload itself. Sending out a notification from inside the block has fixed the problem.

A: I was forgetting to reload my table view after processing the data. I sent out a notification from inside the block which is heard by the Table View Controller, causing the table to be reloaded once the data has been processed.


text:
Q: Moving inline Youtube API javascript code to a seprate file I have this jsfiddle.
When I move the script from the upper panel to the lower panel, it does not work any more.
And why can't I use jQuery to target the buttons? Now, I have to use vanilla JavaScript, because jQuery does not work.
Any ideas?

A: In JSFiddle, at the left panel screenshot, you can choose where to place the script. By default, it's wrapped in an onload event within the head. By default, the Mootools library is loaded.
The reason that the YouTube Player API does not work with the default settings is that the API expects a global onYouTubePlayerAPIReady event to be defined. When the code is wrapped in an onload event, the function isn't global any more.
The solution is to properly use JSFiddle: Use no wrap (body) and jQuery 1.7.2: http://jsfiddle.net/4WPmY/12/.
Another solution, though less nice than the recommended one, is to globally define onYouTubePlayerAPIReady by setting it as a property of window: http://jsfiddle.net/4WPmY/13/
window.onYouTubePlayerAPIReady = function () {

A: From the left pane of jsFiddle, in the section titled "Choose Framework" you need to change the first setting to no wrap (body) so the JS panel is run after the DOM is loaded. You should also change the second option to jQuery 1.7.2 if you wish to use that library.
Your fiddle, updated: http://jsfiddle.net/Marcel/4WPmY/11/


text:
Q: Copy Object from NSMutableArray to another NSMutableArray Here is my arrayResult (NSMutableArray) :
<__NSArrayM 0x7fd160e365f0>(
{
    Amount = 00;
    Carat = 00;
    Color = D;
    Cut = EX;
    Discount = 00;
    IsSelected = 1;
    Quality = IF;
    Rate = 00;
    Shape = RBC;
    StoneNo = "";
    Symme = EX;
},
{
    Amount = 00;
    Carat = 00;
    Color = D;
    Cut = EX;
    Discount = 00;
    IsSelected = 0;
    Quality = IF;
    Rate = 00;
    Shape = RBC;
    StoneNo = "";
    Symme = EX;
}
)

Now I want to copy an object from NSMutableArray to another NSMutableArray.
For that I use this:
    [arrayCopyRow addObject:[arrayResult objectAtIndex:0]];

But I store its address also, so if I change ValueAtIndex 0 that it automatically change it's copied object.
How do I prevent this? How do I create a deep copy?

A: For this you will need a deep copy.
So you can first run:
NSMutableArray *newArray = [[NSMutableArray alloc] initWithArray:oldArray copyItems:YES];

This will create a one level deep copy according to Apples docs and items in the array will need to conform to the NSCopying protocol.
And if you only want one object copied you can use the newArray as a temporary array then create and initialise a new mutable array and move the object there like you were in the question.
To make sure any custom objects are copied as a deep copy with the above method, you need to add the copyWithZone: method in each class.
Rough example:
-(id) copyWithZone:(NSZone *) zone
{
    ObjectInArray *object = [super copyWithZone:zone];
    object.someValue = self.someValue;
    return object;
}

A: Put a copy of the element into the other array.
[arrayCopyRow addObject:[[arrayResult objectAtIndex:0] copy]];

or
[arrayCopyRow addObject:[[arrayResult objectAtIndex:0] mutableCopy]];

If you want copies of all elements you can do a deep copy like luk2302 said.

A: Use this code:
NSMutableArray *array = [yourFirstArray mutableCopy];


text:
Q: How do you pronounce $\mathbb{F}_2, \mathbb{F}_2^n, \mathbb{N}^k, [n] = \{1,\ldots,n\},$ and $S \subseteq [n]$? How do you pronounce $\mathbb{F}_2, \mathbb{F}_2^n, \mathbb{N}^k, [n] = \{1,\ldots,n\},$ and $S \subseteq [n]$ when you're reading a text?
I've just started reading more advanced math textbooks and these are appearing all the time.

A: I think this is a matter of taste/preference.  Personally, I read them as...
"eff-two," "eff-two-enn," "enn-kay," and "box enn."

A: It's ultimately a matter of preference and taste. At some point in learning mathematics, it helps to "break away" the notation from spoken language to avoid distracting questions such as this. For instance, you know $\Bbb N$ refers to the natural numbers (and presumably know what those consist of): whether you call it "n", "the set of naturals", "the set of positive/nonnegative integers" (depending on convention), etc., you know what is being referred to, and that is what's important.
I've often heard both - an "abbreviated" name and the proper full name - interchangeably throughout my education. Personally, I think that the longer name makes the meaning behind the notation clearer if you're a novice, but this is purely a subjective thing. At the end of the day, as you get used to the notation, you'll immediately understand what a given symbol means rather than having to decipher it and all. How it's pronounced or said won't really affect that in the long run - what's important is what the notation conveys, rather than how it's said, at least where learning is concerned.
So as some examples, the shorter and longer names I've often heard for each notation you've brought up. But there's no "wrong" way to pronounce them inherently, so long as it's clear what is intended!

*

*$\Bbb F_2$:

*

*Short: "eff two"

*Long: "the (finite) field of two elements"

*$\Bbb F_2^n$: (similar for $\Bbb N^k$)

*

*Short: "eff two to the n"

*Long: "the n-ary product of eff two with itself"

*$\Bbb N$:

*

*Short: "n"

*Long: "the naturals", "the natural numbers", "the nonnegative/positive integers" (depends on your convention whether $0 \in \Bbb N$ but that's another question altogether)

*$[n]$:

*

*Short: "bracketed n" (maybe? I don't think I've ever heard this said aloud)

*Long: "the first $n$ integers" (you may specify "positive" as well, but I feel most people understand what this means)

*$S \subseteq [n]$:

*

*Short: "a subset of bracket n" (I guess? Not much shorter but whatever...)

*Long: "S is a subset of the first n integers"


text:
Q: Bootstrap containers, rows and col usage I understand for the most part containers and cols.  My question is about rows. Below is 50 / 50 Split.

          50 / 50 Content

          50 / 50 Content

If I was again, going to split one of these columns in an area do I again add another row div as below?

           50 / 50 Content

                 Sub 50 / 50 Content

                 Sub 50 / 50 Content

           50 / 50 Content

Thanks in advance!

A: If you wrap a div which has row class, inside divs paddings, margins and float settings will change.
Use both in the same page and be carefull for thees things.


text: Q: Prevent enterprise iPad kiosks from asking for Apple ID password? We have a fleet of iPad kiosks out at our branch locations and all of them ask periodically for the Apple ID password / iCloud password. This is not connected to any app. It's like the system itself asking. End-users do not and will never have that password. Is there a way to prevent this for enterprise fleets?


text:
Q: How can I find the best sellers by grouping stock units in Laravel? I am trying to select the best selling items based on how many stock units have been created on that product. The more stock units on the product = the more sales.
My product_list table looks like this:
Schema::create('product_list', function (Blueprint $table) {
    $table->increments('id');
    $table->decimal('cost', 9, 2)->default(00.00);
    $table->integer('product_category')->unsigned();            # IE Bespoke/Static/Dynamic
    $table->integer('product_type')->unsigned();                # IE Themes(Custom Or Not)/Number of pages
    $table->integer('product_score')->default(0);               # How many favourites does it have?
    $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

    $table->index(array('product_category', 'product_type'));

    $table->foreign('product_category')->references('id')->on('product_categories');
    $table->foreign('product_type')->references('id')->on('product_types')->onDelete('cascade');
    });

My products_skus table looks like this:
Schema::create('product_skus', function (Blueprint $table) {
    $table->increments('id');
    $table->string('reference');
    $table->integer('product_id')->unsigned();
    $table->timestamp('created_at')->default(DB::raw('CURRENT_TIMESTAMP'));
    $table->timestamp('updated_at')->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));

    $table->index(array('product_id'));

    $table->foreign('product_id')->references('id')->on('product_list')->onDelete('cascade');
});

Here is what I have tried so far using Eloquent - not too fussed about getting any other joins in at the moment, just getting the best sellers working:
$topSellers = DB::table('product_list')->join('product_skus', 'product_skus.product_id', '=', 'product_list.id')
                                       ->groupBy('product_skus.product_id')
                                       ->limit(5)
                                       ->get()
                                       ->all();

Which is giving me this error:

SQLSTATE[42000]: Syntax error or access violation: 1055 'iezonsolutions.product_list.id' isn't in GROUP BY (42000)

How can I find the top sold items? I create an SKU on every product_item when its sold which is a way of tracking the top sellers as well as giving the user a unique tracking ability.
Update to show relations
product_skus has a foreign key product_id which relates to product_list table column id. I want to group the stock keeping units based on the relation o the products id. The most SKU's grouped to that single product id, I want to get them products from the product_list table
$topSellers = DB::table('product_skus')->join('product_list', 'product_skus.product_id', '=', 'product_list.id')
                                       ->orderBy('product_skus.product_id')
                                       ->limit(5)
                                       ->get()
                                       ->all();

Is now grouping the correct relations, however, it is giving me an output of
array:3 [▼
  0 => {#725 ▼
    +"id": 2
    +"reference": "A400IEZON_"
    +"product_id": 2
    +"created_at": "2019-01-16 16:37:16"
    +"updated_at": "2019-01-16 16:37:16"
    +"cost": "100.00"
    +"product_category": 1
    +"product_type": 2
    +"product_score": 0
    +"rating": 0
    +"down_payment": "10.00"
  }
  1 => {#726 ▼
    +"id": 3
    +"reference": "C400IEZON_"
    +"product_id": 3
    +"created_at": "2019-01-16 16:37:25"
    +"updated_at": "2019-01-16 16:37:25"
    +"cost": "150.00"
    +"product_category": 1
    +"product_type": 3
    +"product_score": 0
    +"rating": 0
    +"down_payment": "10.00"
  }
  2 => {#727 ▼
    +"id": 3
    +"reference": "C400IEZON_"
    +"product_id": 3
    +"created_at": "2019-01-16 16:37:25"
    +"updated_at": "2019-01-16 16:37:25"
    +"cost": "150.00"
    +"product_category": 1
    +"product_type": 3
    +"product_score": 0
    +"rating": 0
    +"down_payment": "10.00"
  }
]

I want to count all of these, so here, product with the id 3 should be shown as the top product followed by product 2.

A: You could achieve this with a Sub Query.
$skus = ProductSku::selectRaw('COUNT(*)')
    ->whereColumn('product_id', 'product_list.id')
    ->getQuery();

$products = ProductList::select('*')
    ->selectSub($skus, 'skus_count')
    ->orderBy('skus_count', 'DESC')
    ->take(5)
    ->get();

This would be a lot easier if ProductList had a relationship with ProductSku.
Then you could just do this:
For example in App\ProductList, you could have something like this:
public function skus()
{
    return $this->hasMany(ProductSku::class);
}

.. then, your query would simply be:
ProductList::withCount('skus')
    ->orderBy('skus_count', 'DESC')
    ->take(5)
    ->get();

.. which will produce the same query as above. I am not entirely sure about your model names. You should change it accordingly.


text:
Q: Style and Javascript Not Working I have the following seems to work in Internet Explorer but not Chrome. Can anyone please explain why, and what I should do to correct it.
<iframe id="confirmed_list" src="./meets/confirmed.php?meet_id=$1" scrolling="no" width="80%" onload="document.getElementById('confirmed_list').height = confirmed_list.document.body.scrollHeight">
</iframe>

The script should automatically extend the height of the iframe to fit the contents. Internet Explorer gets the value right, however Chrome seems to calculate the value massively incorrectly.
Any ideas?

A: Take another good look what's happening here:
document.getElementById('confirmed_list').height = confirmed_list.document.body.scrollHeight

In this event handler, confirmed_list was never defined. I'm sure you mean document.getElementById( 'confirmed_list' ) here.
Anyway, a better solution is to use this, as it refers to the iframe:
this.height = this.document.body.scrollHeight


text:
Q: Form binding : change model to a FormModel In ASP.NET Core MVC, I use model binding for a cascading dropdown but now that I am trying to integrate other field to my form, I'm stuck, as I am used to work with a FormModel.
What I need is two cascading dropdown binded to a database, two radio buttons and another field and a button "Evaluate" which will redirect the user to another View (called "Evaluate") where I can retrieve my values using a model called BasicEvaluationForm as illustrated below
[HttpPost]
public IActionResult Evaluate(BasicEvaluationForm form)

Below you'll find some code excerpts from the Models, the Controller and the View
Thanks for any help !
Models used for the cascading dropdown
public class Make
{
    [Key]
    public int MakeID { get; set; }
    public string MakeName{ get; set; }
    [NotMapped]
    public int ModelID { get; set; }
}

public class Model
{
    [Key]
    public int ModelID { get; set; }
    public int MakeID { get; set; }
    public string ModelName { get; set; }
}

BasicEvaluationForm I am trying to integrate
public class BasicEvaluationForm
{
    public Model model { get; set; }
    public Make make { get; set; }
    public string gearingType { get; set; }
    public int mileage { get; set; }
}

Controller
public class HomeController : Controller
{
    private readonly DatabaseContext _context;

    public HomeController(DatabaseContext context)
    {
        _context = context;
    }

    [HttpPost]
    public IActionResult Evaluate(BasicEvaluationForm form)
    {
        if (ModelState.IsValid)
        {
            try
            {
                string makeTxt = form.model;
                string modelTxt = form.make;
                string kilometrage = form.kilometrage.ToString();
                string gearingType = form.gearingType;

                var model = new PredictionService().PredictPrice(makeTxt, modelTxt, mileage, gearingType).Result;
                return View("Evaluate", model);
            }
            catch (Exception e)
            {
                ViewBag.Error = e.Message;
            }
        }
        return View();
    }

    [HttpPost]
    public IActionResult Index(Make objcategory, FormCollection formCollection)
    {
        var ModelID= HttpContext.Request.Form["ModelID"].ToString();

        List<Make> makelist = new List<Make>();
        makelist = (from make in _context.Make
                    select make).ToList();
        makelist.Insert(0, new Make { MakeID = 0, MakeName = "Select" });

        ViewBag.ListofMake = makelist;
        return View(objcategory);
    }

    public JsonResult GetModel(int MakeID)
    {
        List<Model> modellist = new List<Model>();

        modellist = (from model in _context.Model
                     where model.MakeID == MakeID
                     select model).ToList();

        modellist.Insert(0, new Model { ModelID = 0, ModelName = "Select" });

        return Json(new SelectList(modellist, "ModelID", "ModelName"));
    }

    public IActionResult Index()
    {
        List<Make> makeList = new List<Make>();
        makeList = (from make in _context.Make select make).ToList();
        makeList.Insert(0, new Make { MakeID = 0, MakeName = "Select" });

        ViewBag.ListOfMake = makeList;
        return View();
    }
  }
}

View
@model whatstheprice.io.basic.Models.Make

@{

<form asp-controller="Home" asp-action="Index" method="post" class="form-horizontal" role="form">

                <select asp-for="MakeID"
                        class="form-control"
                        asp-items="@(new SelectList(@ViewBag.ListofMake,"MakeID", "MakeName"))"></select>

                ModelName
                <select class="form-control" id="ModelID" name="ModelID" asp-for="ModelID"
                        asp-items="@(new SelectList(string.Empty,"ModelID", "ModelName"))"></select>

</form>
}


text:
Q: Change value of one view controllers NSSdictonary from other view controller using custom delegate in ios I have a dictonary in one view controller with different keys.i have to change the value of one of the key of this dictonary from other view controller after some method. How can i do this using custom deleagate.

A: Add a protocol with a method for Your needs. Make the class that holds the dictionary to conform to the protocol. Implement the method in question and edit Your dict in it. In the other class, add a @property (weak, nonatomic) id <MyProtocol> delegate or some other appropriate name. When needed call the protocol via the stored delegate.
@protocol MyProtocol <NSObject>
  - (void)callback;
@end

@interface MyClass : NSObject <MyProtocol>
@property (nonatomic, copy) NSMutableDictionary *myDictionary;
@end

@implementation MyClass
// class methods

  -(void)callback {
    // edit dict here
  }

@end

@interface MySecondClass : NSObject
@property (weak, nonatomic) id<MyProtocol> delegate;
@end

@implementation MySecondClass
// class methods

- (void)someMethod {
  // some logic
  if ([self.delegate respondsToSelector:@selector(callback)]) {
    [self.delegate callback];
  }
}
@end


text:
Q: how to sort nested documents regardless of different parents I'm new to elasticsearch and struggling this situation (for example):
I want to index offices and clerks of each office. So, I've created this mapping:
PUT office
{
  "mappings": {
    "properties": {
      "office_name": {
        "type": "text"
      },
      "clerks": {
        "type": "nested"
      }
    }
  }
}

and indexing some data:
PUT /office/_doc/1
{
  "name": "office a",
  "clerks": [
    {
      "name": "a a a a"
    },
    {
      "name": "a a"
    },
    {
      "name": "b"
    }
  ]
}

PUT /office/_doc/2
{
  "name": "office b",
  "clerks": [
    {
      "name": "a a a"
    }
  ]
}

Now, I want to search for 'a':
GET /office/_search
{
  "query": {
    "nested": {
      "path": "clerks",
      "query": {
        "match": {
          "clerks.name": "a"
        }
      },
      "inner_hits": {}
    }
  }
}

the result is:
{
  "took" : 624,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 2,
      "relation" : "eq"
    },
    "max_score" : 1.1272885,
    "hits" : [
      {
        "_index" : "office",
        "_type" : "_doc",
        "_id" : "2",
        "_score" : 1.1272885,
        "_source" : {
          "name" : "office b",
          "clerks" : [
            {
              "name" : "a a a"
            }
          ]
        },
        "inner_hits" : {
          "clerks" : {
            "hits" : {
              "total" : {
                "value" : 1,
                "relation" : "eq"
              },
              "max_score" : 1.1272885,
              "hits" : [
                {
                  "_index" : "office",
                  "_type" : "_doc",
                  "_id" : "2",
                  "_nested" : {
                    "field" : "clerks",
                    "offset" : 0
                  },
                  "_score" : 1.1272885,
                  "_source" : {
                    "name" : "a a a"
                  }
                }
              ]
            }
          }
        }
      },
      {
        "_index" : "office",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.1184678,
        "_source" : {
          "name" : "office a",
          "clerks" : [
            {
              "name" : "a a a a"
            },
            {
              "name" : "a a"
            },
            {
              "name" : "b"
            }
          ]
        },
        "inner_hits" : {
          "clerks" : {
            "hits" : {
              "total" : {
                "value" : 2,
                "relation" : "eq"
              },
              "max_score" : 1.1468691,
              "hits" : [
                {
                  "_index" : "office",
                  "_type" : "_doc",
                  "_id" : "1",
                  "_nested" : {
                    "field" : "clerks",
                    "offset" : 0
                  },
                  "_score" : 1.1468691,
                  "_source" : {
                    "name" : "a a a a"
                  }
                },
                {
                  "_index" : "office",
                  "_type" : "_doc",
                  "_id" : "1",
                  "_nested" : {
                    "field" : "clerks",
                    "offset" : 1
                  },
                  "_score" : 1.0900666,
                  "_source" : {
                    "name" : "a a"
                  }
                }
              ]
            }
          }
        }
      }
    ]
  }
}

I expect 'a a a' appears before 'a a' and the result to be like this:
[
{
  "name": "a a a a"
},
{
  "name": "a a a"
},
{
  "name": "a a"
}
]

How can I achieve this result?


text:
Q: org.springframework.beans.factory.BeanCreationException: in Ecommerce project I work with a Spring boot project and when I run, I get the following error,
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'userSecurityService': Unsatisfied dependency expressed through field 'userRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Could not create query metamodel for method public abstract Ecommerce.entities.User Ecommerce.repository.UserRepository.findByUsername(java.lang.String)!

I assume the last lines  are what is important in the error stack,
Could not create query metamodel for method public abstract Ecommerce.entities.User Ecommerce.repository.UserRepository.findByUsername(java.lang.String)!

I have the User repository provided below,
public interface UserRepository extends CrudRepository<User, Long> {

    User findByUsername(String username);

    User findByEmail(String email);
}

The user entity is also provided,
@Entity
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userId", nullable = false, updatable = false)
    private Long userId;

    private String userName;

    private String password;

    private String firstName;

    private String lastName;

    @Column(name = "email", nullable = false, updatable = false)
    private String email;

    private String phone;

    private boolean enabled = true;

    @OneToOne(cascade = CascadeType.ALL, mappedBy = "user")
    private ShoppingCart shoppingCart;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private List<UserShipping> userShippingList;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "user")
    private List<UserPayment> userPaymentList;

    @OneToMany(mappedBy = "user")
    private List<Order> orderList;

    @JsonIgnore
    @OneToMany(mappedBy = "user", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    private Set<UserRole> userRoles = new HashSet<>();

    // ..............
    // more lines of code for overriding the methods

}

What is the issue here and how to solve it?

A: In Spring JPA Repository, the auto-generated finders obey the naming convention as follows.
findBy<DataMember><Op>

<Op> can be Like,Between etc..

A: Apparently, the name of the method findByUsername should match with the property in the user entity. In the user entity class, I have used,
@Entity
public class User implements UserDetails {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userId", nullable = false, updatable = false)
    private Long userId;

    private String userName;
}

After I changed to the username from the userName, the problem is solved. I have done this after consulting other SOF posts, but, I still seek for the better explanation.


text:
Q: Erro ao usar distribuição Gradle Estou iniciando no mundo Groovy junto com Grails. Ao rodar o comando 'dbm-update' (para atualizar com bd em minha máquina e as migration etc) ocorre este erro de compilação.
Sei quase nada de java. ( apenas preparar o ambiente, e olhe lá).
Observação importante: rodei um projeto grails do zero, roda tranquilamente.(sem integração com bd)
Já este, o qual clonei do gitlab para trabalhar...dá este erro.
Agradeço dês de já pela ajuda!
ommand execution error: org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
Script1.groovy: 194: unexpected token: << @ line 194, column 1.
   <<<<<<< HEAD
   ^

1 error

> Task :dbmUpdate FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':dbmUpdate'.
> Process 'command 'C:\Program Files\AdoptOpenJDK\jdk-8.0.292.10-hotspot\bin\java.exe'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug  option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 46m 27s
6 actionable tasks: 6 executed
| Error Command [dbm-update] error: Could not execute build using Gradle distribution
 'https://services.gradle.org/distributions/gradle-4.10.3-all.zip'. (Use --stacktrace to see the full trace)

A: Pelo erro me parece mais um problema com um merge git.
Faça git status para ter mais informações e depois dê uma olhada no arquivo Script1.groovy para ver se não tem balisas que indicam um merge em andamento, como <<<<<<< HEAD por exemplo.


text:
Q: Setting text based on objects using eureka i'm trying to set the value based to name in a realm object however it keep showing Ladder { as text in cell instead of the name. here is my code
    <<< MultipleSelectorRow<Ladder>("Rank") {
           $0.hidden = Condition.predicate(NSPredicate(format: "$Game == nil"))
           $0.title = $0.tag

           }.cellUpdate { cell, row in

               let formvalues = self.form.values()
               let game = formvalues["Game"] as! Game
               let ranks = Array(game.ranks)
               row.options = ranks
               row.displayValueFor = { (rowValue: Set<Ladder>?) in
                   return rowValue?.map({ $0.name }).sorted().joined(separator: ", ")
               }

               cell.textLabel?.font = UIFont(name: "Avenir-Book", size: 16)

               cell.preservesSuperviewLayoutMargins = false
               cell.separatorInset = UIEdgeInsets.zero
               cell.layoutMargins = UIEdgeInsets.zero

       }

ranks output
[Ladder {
    id = 58268b08f5f51a16b8d53472;
    name = Bronze;
}, Ladder {
    id = 58268b08f5f51a16b8d53473;
    name = Silver;
}, Ladder {
    id = 58268b08f5f51a16b8d53474;
    name = Gold;
}, Ladder {
    id = 58268b08f5f51a16b8d53475;
    name = Platinium;
}, Ladder {
    id = 58268b08f5f51a16b8d53476;
    name = Diamond;
}, Ladder {
    id = 58268b08f5f51a16b8d53477;
    name = Master;
}, Ladder {
    id = 58268b08f5f51a16b8d53478;
    name = Challenger;
}]

realm model
class Ladder: Object {

    dynamic var id = ""
    dynamic var name = ""

    override static func primaryKey() -> String? {
        return "id"
    }

}


text:
Q: PC(s) wont post - Memory Error I am in the final stages of building two PCs, but upon testing, neither pass POST.
When turned on, fans spin and lights flash but there's no BIOS screen and motherboard error related to memory.
PC 1 - Gives error 53
PC 2 - Gives error 19
What we have tried so far:

*

*Removing all components except MOBO, CPU and PSU

*Inserting one RAM stick, tried each slot

*Clearing CMOS (Button press and Jumper)

*Updated BIOS (PC1)

Any Ideas?
See build below:
PC 1
MOBO - Asus X99M WS
CPU - Xeon E5-2697 V4
RAM - Kingston 64GB PC4-2133 CL15 288-Pin RDIMM Kit (4x16GB)
GPU - Quadro M4000
SSD - Samsung 850 Pro
PSU - EVGA Supernova 650W Gold
Case - Silverstone TJ08-E
PC 2
Mobo - Asrock Fatality X99M Killer
CPU - Xeon E5-2697 V4
RAM - Kingston 64GB PC4-2133 CL15 288-Pin RDIMM Kit (4x16GB)  KVR21R15D4K4/64
GPU - Quadro M4000
SSD - Samsung 850 Pro
PSU - EVGA Supernova 650W Gold
Case - Silverstone TJ08-E

A: Both these motherboards appear to only support Xeon V3 processors.  The LGA2011-V3 socket will fit an LGA2011-V4 processor but a bios update is required for compatibility and if it's unavailable it will not work.
If you're positive you're running a BIOS version capable of supporting V4 you may want to purchase a single stick of DDR4 from a local store to check that your RAM is good given that it's all from the same vendor/manufacture.


text:
Q: log4j2 in Wildfly 9 I use log4j2 as my default logging, when I run my webapp with Wildfly, My logs get wrapped as an INFO like follows:
17:28:31,127 INFO  [stdout] (default task-6) DEBUG 2015-10-15 17:28:31,127 za.co.manticore.core.aspect.cacing.CachingAspect - Entering Caching Aspect for method getApplicationMeta
This is causing my logs to be cluttered, as all my logs are logged as INFO. How can I configure Wildfly to not do this. I have done some googleing but could not find an answer that worked.

A: I think, you should properly configure log4j2. It looks like currently it has console appender - try remove console appender from log4j2 config

A: Ok you can configure Wildfly not to wrap your stdout and stderr logs.
Run the following CLI commands
sh jboss-cli.sh --connect '/subsystem=logging/console-handler=JUST-PRINT:add(formatter="%s%E%n")'
sh jboss-cli.sh --connect '/subsystem=logging/logger=stderr:add(use-parent-handlers="false", handlers=[JUST-PRINT])'
sh jboss-cli.sh --connect '/subsystem=logging/logger=stdout:add(use-parent-handlers="false", handlers=[JUST-PRINT])'


text:
Q: keycloak redirect to update password url "login-actions/required-action" I am building Identity management portal, using keycloak for authentication , i want to have one change password screen in this portal, when user click on that , it should redirect to keycloak theme update password screen ("http://host:port/auth/relams/<relam-name>/login-actions/required-action?execution=UPDATE_PASSWORD&client_id=test&tab_id=J4X7UdFi")
Can we achieve this in Keycloak  after login?, this screen comes if we have Required Action as "UPDATE_PASSWORD" in Keyclaok UserRepresentation Object and before login if this action is there then keycloak itself redirects automatically to Update Password Screen ,
but can we give the Keycloak Update Password Screen directly to the user on UI after he logins.

A: We need to create RequiredActionProvider
package com.keycloak.password;

import java.util.List;
import java.util.concurrent.TimeUnit;

import org.jboss.logging.Logger;
import org.keycloak.authentication.RequiredActionContext;
import org.keycloak.authentication.RequiredActionProvider;
import org.keycloak.common.util.Time;
import org.keycloak.credential.CredentialModel;
import org.keycloak.credential.CredentialProvider;
import org.keycloak.credential.PasswordCredentialProvider;
import org.keycloak.credential.PasswordCredentialProviderFactory;
import org.keycloak.models.UserModel;

public class CustomUpdatePassword implements RequiredActionProvider {

    private static final String OPENID_CONNECT_PROTOCOL = "openid-connect";
    private static final String CLAIM_VALUE = "claim.value";
    private static final Logger LOG = Logger.getLogger(CustomUpdatePassword.class.getName());

    @Override
    public void evaluateTriggers(RequiredActionContext context) {

        try {
                //some custom logic add required_action
                    if (password.getCreatedDate() == null) {
                        context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);
                    } else {
                        long timeElapsed = Time.toMillis(Time.currentTime()) - password.getCreatedDate();
                        long timeToExpire = TimeUnit.DAYS.toMillis(daysToExpirePassword);
                        if (timeElapsed > timeToExpire) {
                            context.getUser().addRequiredAction(UserModel.RequiredAction.UPDATE_PASSWORD);=
                        }
                    }

            }
        } catch (Exception e) {
            LOG.error(e.getMessage());
        }

    }

    @Override
    public void requiredActionChallenge(RequiredActionContext context) {
    }

    @Override
    public void processAction(RequiredActionContext context) {
    }

    @Override
    public void close() {

    }
}

And Factory class
package com.keycloak.password;

import org.keycloak.Config;
import org.keycloak.authentication.RequiredActionFactory;
import org.keycloak.authentication.RequiredActionProvider;
import org.keycloak.models.KeycloakSession;
import org.keycloak.models.KeycloakSessionFactory;

public class CustomUpdatePasswordFactory implements RequiredActionFactory {

    private static final CustomUpdatePassword SINGLETON = new CustomUpdatePassword();

    @Override
    public String getDisplayText() {
        return "Password Update";
    }

    @Override
    public RequiredActionProvider create(KeycloakSession keycloakSession) {
        return SINGLETON;
    }

    @Override
    public void init(Config.Scope scope) {

    }

    @Override
    public void postInit(KeycloakSessionFactory keycloakSessionFactory) {

    }

    @Override
    public void close() {

    }

    @Override
    public String getId() {
        return "Password Update";
    }
}

Then these class jars needs to deploy in the jboss folder
COPY --chown=jboss:root /target/<above_project_jar>-*.jar /opt/jboss/keycloak/providers/


text:
Q: Java - Why am I unable to click generate javadoc button on netbeans? Im trying to generate a javadoc for the project I have created by right clicking the project on the navigator on the left. I see the option, but it wont let me click the button "Generate Javadoc" in net beans.
Could someone please tell me whats causing this problem and how to solve this?

A: The Generate JavaDoc Button does not actually generate any JavaDocs. You need to write the docs yourself.
But once you have all the docs in your code, you can click that button and it will generate you a list of nicely formatted HTML pages and put them into your target (dist) directory
This is what you need to have a complete JavaDoc for a method:
 /**
 * This is a JavaDoc example for an example Method
 *
 * @param someParameter here an explanation what this parameter stands for
 * @return the String value of the parameter
 */
 public String exampleMethod(int someParameter){
      // just a useless example
      return ""+someParameter;
 }

You need @param <name of the parameter> for each parameter in your method signature and if the method returns something you need the @return tag. Even if everyone sees what type this method returns, it is good practice to mention it again in a short sentence.
If you have that you will no longer get any warnings. And maybe (when there are no more warnings) NetBeans will let you generate the html pages with that button.


text:
Q: Datastore to Firestore(datastore mode) automatic migration: request timeout while accessing datastore after REDIRECT_STRONGLY_CONSISTENT_READS step I am using Objectify(v5) for accessing Datastore, in App Engine Standard Environment, with Java. Entities are cached by Objectify automatically, and I am also using Memcache separately.
This issue of Datastore APIs timing out started happening exactly post REDIRECT_STRONGLY_CONSISTENT_READS migration step. Strangely, it happens roughly after every hour or 2 hours, lasts for 3-4 mins and then gets back to normal. Since requests latency is going up from ~200ms to more than 60s, lots of new instances are getting created and am getting charged heavily.
here are some of the errors:
com.google.api.server.spi.SystemService invokeServiceMethod: exception occurred while calling backend method
java.util.concurrent.CancellationException: Task was cancelled.
at com.google.common.util.concurrent.AbstractFuture.cancellationExceptionWithCause(AbstractFuture.java:1550)
at com.google.common.util.concurrent.AbstractFuture.getDoneValue(AbstractFuture.java:590)
at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:467)
at com.google.common.util.concurrent.AbstractFuture$TrustedFuture.get(AbstractFuture.java:122)
at com.google.appengine.tools.development.TimedFuture.get(TimedFuture.java:55)
at com.google.common.util.concurrent.ForwardingFuture.get(ForwardingFuture.java:68)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89)
at com.google.appengine.api.datastore.Batcher$ReorderingMultiFuture.get(Batcher.java:114)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89)
at com.googlecode.objectify.cache.TriggerFuture.get(TriggerFuture.java:100)
at com.googlecode.objectify.impl.ResultAdapter.now(ResultAdapter.java:34)
at com.googlecode.objectify.util.ResultWrapper.translate(ResultWrapper.java:22)
at com.googlecode.objectify.util.ResultWrapper.translate(ResultWrapper.java:10)
at com.googlecode.objectify.util.ResultTranslator.nowUncached(ResultTranslator.java:21)
at com.googlecode.objectify.util.ResultCache.now(ResultCache.java:30)
at com.googlecode.objectify.util.ResultWrapper.translate(ResultWrapper.java:22)
at com.googlecode.objectify.util.ResultWrapper.translate(ResultWrapper.java:10)
at com.googlecode.objectify.util.ResultTranslator.nowUncached(ResultTranslator.java:21)
at com.googlecode.objectify.util.ResultCache.now(ResultCache.java:30)

and
com.googlecode.objectify.cache.EntityMemcache getAll: Error obtaining cache for [<dummy-entity-name>]
    java.util.concurrent.CancellationException: Task was cancelled.

and
java.lang.InterruptedException
        at com.google.common.util.concurrent.AbstractFuture.get(AbstractFuture.java:460)

I have tried upgrading to latest versions:
implementation 'com.google.appengine:appengine-api-1.0-sdk:2.0.5'
implementation 'javax.servlet:javax.servlet-api:3.1.0'
implementation 'com.googlecode.objectify:objectify:5.1.25'

and also flushed memcache. nothing has worked.
Has anyone faced this issue?

A: It turned out to be an issue with migration itself. Reached out to Google Cloud support(paid), Datastore/Firestore Product team paused the migration, which I could not do it myself by the way, wasn't allowed for my project. They did some fixing and completed the migration. Now Datastore queries as running as expected.


text:
Q: How to find the base of union of 2 subspaces Suppose we have 2 subspaces V,W.
What is the base and the dimention of:  V U W ?
Its clear to me that V U W is not always a subspace!
I was thinking about taking the base of U and the base of W and try to Gaussian elimination but that doesnt goes well becouse for example:
$V={(a,0,0)|a \text{ from } R}$. The base of V: $(1,0,0)$
$W={(0,b,0)|b \text{ from } R}$. The base of V: $(0,1,0)$
While doing Gaussian elimination to the matrix : $(1,0,0),(0,1,0)$ , we get that the base from the union of V with W is : ${(1,0,0),(0,1,0)}$ and this is not true becouse we create from this base the vector $(1,1,0)$ that doesnt exist in the uniton of V with W.
Thanks alot!
Stav

A: I'm assuming that by "base", you mean "basis". What do you mean by a "basis of $V \cup W$"? As you noted, $V \cup W$ is not always a vector space; the definition of "basis" only applies to vector spaces. Usually people would talk about the basis of the span of $V \cup W$, in which case your method works fine.
Note that if $V \cup W$ did have a basis in the traditional sense (i.e., there existed linearly independent $v_1, \dots, v_n$ whose span was equal to $V \cup W$), then $V \cup W$ would certainly be a vector space, though this only happens when $V \subseteq W$ or $W \subseteq V$.


text:
Q: How to change the font of Axis label in Pyqtgraph I have a custom font, I am able to set this font in title of the graph, I need help in setting the axis label font.(left, bottom axis labels)
I am able to set the font to the title of the graph like this
    graphWidget = pyqtgraph.PlotWidget()
    graph = graphWidget.getPlotItem()
    graph.titleLabel.item.setFont(font)

I would like to know if there's any similar way to set the font for axis labels.

A: To set custom QFont to axis label, you have to setFont for label of each axis.
Here is a short example, which changes font family to Times for title, bottom and left axis.
import sys

import pyqtgraph
from PyQt5.QtGui import QFont
from PyQt5.QtWidgets import QApplication

app = QApplication(sys.argv)

# Define your font
my_font = QFont("Times", 10, QFont.Bold)

graphWidget = pyqtgraph.PlotWidget()
graphWidget.setTitle("My plot")

# Set label for both axes
graphWidget.setLabel('bottom', "My x axis label")
graphWidget.setLabel('left', "My y axis label")

# Set your custom font for both axes
graphWidget.getAxis("bottom").label.setFont(my_font)
graphWidget.getAxis("left").label.setFont(my_font)

graph = graphWidget.getPlotItem()
# Set font for plot title
graph.titleLabel.item.setFont(my_font)

graphWidget.show()
app.exec()


text:
Q: c# How to redirect stdout to new process window? I was creating a Process using the call:
Process.Start(startInfo);
with
startInfo.WindowStyle = ProcessWindowStyle.Normal;
startInfo.FileName = "cmd.exe";
startInfo.UseShellExecute = true;
startInfo.RedirectStandardInput = false;
startInfo.RedirectStandardOutput = false;

when the process runs with these arguments, it outputs to the new process's window fine.
However, when I make UseShellExecute false without redirecting standard output, the process no longer prints to the screen. Is this the expected behavior?
If so, how can i write to the new window that the process starts?
I can manually get the data from the process using StandardOutput.Read(), but I don't know how to write that to the new window.  When I create that window, it appears to have a console by default.
I can use pinvoke to call the C++ function on the new process:
[DllImport("kernel32", SetLastError = true)]
        private static extern bool AttachConsole(int dwProcessId);

I think that I may be able to just write to the console of the new window using the function "writeconsole"
https://msdn.microsoft.com/en-us/library/windows/desktop/ms687401%28v=vs.85%29.aspx
however, i was wondering if it's possible to do this just using .net libraries. I feel like what I want isn't so complicated that this should be necessary.
All I want is to be able to start a new process and redirect the stdout of that process to the new window that is created in that process, while retaining the ability to write to stdin.
edit:
Writing using console.writeline would just write to the main console of the program. My application is a gui app, so to be honest, I don't know exactly where it writes to, but I do know that you can see this output under the tab "output" in visual studio but not in the windows of the program itself. I think that there is a separate buffer allocated by .net for the console.

A: You can redirect stdout and stdin with freopen.
Example:
freopen ("file.txt","w", stdout); //or stdin

EDIT:
You could also use createpipe() and read from the end of the pipe. You can tell the pipe, then, where you would like your data to be read to or stored/displayed. If this is not what you are looking for, please elaborate more in depth with a comment.


text:
Q: Smoothly snap a rotatable object to degree I have been hacking on this problem for a while and can't seem to find a solution (I am not friends with trigonometry).
I am trying to build an element that the user can "grab" and then rotate. I have it working except for one last feature I can't seem to figure out:
http://codepen.io/megakoresh/pen/WbLLzZ?editors=001
(it's long, but I am only asking about how the snapTo() function should work).
What I want is for the object snap to degrees based on the increments value. This means that if snap==true, the code should calculate the closest estimated targets to the point of release of the mouse and based on the direction of rotation smoothly rotate the object to that target rotation:

Since the object is 'grabbed', I calculate the offset at mousedown to object's current rotation, thats where it comes from, so it doesn't just snap to mouse.
So in this case the user rotates the object clockwise and releases the mouse when the objects rotation is between 90° and 45°. Since the direction (identified by the sign of angle variable) was positive, the target will be after the Current rotation.
The task is to calculate that target and then smoothly rotate the object to it.
The function I have written for it is based on by autoSpin() function (executes when spin==false), which takes a flipped time exponent multiplier delta (calculated from the time elapse since mouse was released). delta will decrease along a flipped exponent as time passes and so the angle slows down.
There is spinTo() function, please don't judge me I have a feeling it is very stupid:
function snapTo() {
    var elapsed, delta;
    increments = (typeof increments === 'number') ? Math.floor(increments) : 4;
    var ia = 360 / increments; //increment angle - snapping points should occur "every ia degrees"
    if (Math.abs(angle % ia) > 0) { //if user turned for more than 1 increment
      var a = lastRot % ia; //check the distance from
      if (angle > 0){ //positive direction
        amplitude = 50; //if snapping is on, force amplitude
        target = (lastRot - a) + ia;
      }
      if (angle < 0){ //negative direction
        amplitude = -50;
        target = lastRot - a;
      }
    } else { //cancel the rotation
      target = rotation;
    }
    elapsed = Date.now() - timestamp; //time passed since mouse was released
    delta = -amplitude * Math.exp(-elapsed / timeConstant); //the greater the time from mouse release, the smaller this value
    if (delta > 0.5 || delta < -0.5) { //while delta is decreasing...
      rotate(target - delta - offset);
      snapFrame = requestAnimationFrame(snapTo); //keep rotation
    } else {
      rotate(target - offset); //when enough time passes (based on timeConstant), make one final rotation and stop
    }
  }

What am I doing wrong?

A: *le sigh
Ok well I had to figure it out on my own. If anyone wants to do this kind of thing, here is one way of doing it:
function snapTo() {
    var elapsed, ease, diff;
    increments = (typeof increments === 'number') ? Math.floor(increments) : 4;
    var ia = 360 / increments; //increment angle - this is how large each increment will be
    var a = last % ia; //check the distance from point of mouse release to the previous increment
    if (movement>0) {
      elapsed = Date.now() - timestamp; //time passed since mouse was released
      ease = 1 - Math.exp((-3*elapsed)/timeConstant); //your easing function formula goes here
      if(a > ia/2) { //if halfway through the increment...
        target = (last - a) + ia; //target next increment
      }
      else { //else revert to previous increment to the point of mouse release
        target = last - a;
      }
      diff = target - last; //difference between target and rotation at time of mouse release
      if(ease < 0.95){ //this depends on your easing formula
        rotate(last+diff * ease);
        requestAnimationFrame(snapTo); //don't forget to RAF
      } else { //and for your final frame...
        rotate(last+diff); //make it snappy :P
      }
      console.log(last); //traces of debugging were found in this derelict question...
    }
  }

So in here

*

*elapsed is the time passed since the mouse was released

*increments is the argument provided by user: how many snapping points will be there

*ia is the computed increment in degrees: 360/increments

*last is the angle recorded on mouseup event - "Current rotation" in the diagram. It includes the offset (in my code, its just a "snapshot" of rotation at point of release, that is then also reversed in sign because in DOM the coordinate system is y-flipped and I don't like working with that).

*a is how much bigger the last is than the previous nearest increment point.

*diff is the "target" on the diagram - difference between final rotation and last

*ease is just the value that changes according to your easing function, based on which you either continue calling RAF or finish the animation.

*timeConstant is time in milliseconds for how long the animation will take. You can have this or not, depends on your easing formula

A good resource to read in general: Understanding Easing Functions
Also Desmos graphing calculator is quite good for developing easing formulas.
Oh and: in case anyone is wondering, it doesn't seem possible to pass any kind of non-time-related arguments to RAF callback functions. Seems to break it if I do. So the only solution is to define the increments value elsewhere in the code.
Codepen of the working function
Anyone got a better solution, I am all eyes.


text:
Q: Как правильно убить процесс средствами Winapi/C++? Подскажите как корректно убить процесс средствами с++/winapi ?
По попутно есть так же вопрос можно ли занести список процессов и убить их?
Какой список используется?

A: Убийство процессов считать корректным в принципе нельзя, т.к. Вы нарушаете привычный ход работы того или иного процесса. Но если уж очень нужно, то можно использовать функцию TerminateProcess(). По понятным причинам (C++ не работает с другими процессами) в C++ аналогов нет.
Чтобы уничтожить группу процессов, нужно получить идентификаторы нужных процессов и применить к ним вышеупомянутую функцию.


text:
Q: Point Anaconda to multiple locations for source files Working in an offline Windows 10 environment where I have available a local mirror of conda-forge and an installation of Anaconda3. I need to create an environment with packages of which some are only to be found in conda-forge mirror and some only in local Anaconda3 C:/Users/<user>/AppData/Local/Continuum/anaconda3/pkgs folder. Note that the latter is not a subset of the former (e.g. scipy).
The problem is when I create an environment from an environment.yml that includes packages from both groups, then it fails because conda create --name test --file environment.yml seems to be only searching the channel. On the other hand conda create --name test --offline --file environment.yml is only looking in the above referenced pkgs folder.
How can I point conda create to both repositories?


text:
Q: Can I use IronPython in Linqpad? I love Linqpad and I'm studying IronPython. Can I use Linqpad as my "code scratchpad" when I'm doing some IronPython exercises? Just wondering. :)
Thanks.

Update:
According to Joe Albahari, there's moderate support for adding other languages, so it will probably be added at some stage.
See IronPython/IronRuby support request link for more details.

A: No. You might try asking Joe if there are any plans for it on the linqpad forum. He's a nice chap.


text:
Q: WMI Performance Counters show zero, but Task Manager shows values I thought Task Manager used the WMI performance counters to calculate things like disk usage per process. However, running a PowerShell script that queries Win32_PerfFormattedData_PerfProc_Process, I get the right process and some data filled in--but the relevant values I'm interested in are all zero. (See image.)
What I want to do is simply get (or calculate) the kind of data that Task Manager shows, and then save the data for graphing and/or decision purposes. (e.g. For learning purposes, killing off a program that is using 100% CPU or 16 GB of RAM.)

Running in Windows 10 (Pro). I just tried running as administrator and no difference. Powershell version is 5.1.
Q: So why are these values zero? And, if Task Manager is getting these values... what API is it using if not WMI?


text:
Q: Blueprinter gem - render STI collection I'm trying to use the new alternative for serialization: Blueprinter
How do you handle STI collection where every model is some type of view?
I came up with something like this (saw similar code on AMS github issue):
def serialize_cards(cards)
  cards.group_by(&:type).map do |type, cards|
    case type
    when 'TypeOneCard' then Api::V1::CardBlueprint.render(cards, view: :one)
    when 'TypeTwoCard' then Api::V1::CardBlueprint.render(cards, view: :two)
    else  raise ArgumentError, "Unhandled event type '#{type}'"
    end
  end
end

Why is output in string with backslashes:
[
    "[{\"id\":27566,\"attachment\":null,\"avatar\":null,\"card_comments_count\":0,\"card_likes_count\":0,\"card_publisher\":\"group\",\"created_at\":\"2020-11-18T10:24:42.195+01:00\",\"description\":\"Ted, how many times have I told you to put the lid back on the peanut butter jar?! It's this inconsiderate, immature jackassery that makes me feel like I'm living in The Real World House! And not the early days when they all had jobs and social consciences, I'm talking about Hawaii, and after!\",\"ends_at\":\"2021-02-06T23:55:00.000+01:00\",\"event_attendees_count\":0,\"group_name\":\"Cheeseburger - Herbes de Provence\",\"origin\":\"http://localhost:3000/dorfplatz/3\",\"origin_name\":\"Dardagny - Athenaz (Avusy)\",\"picture\":null,\"starts_at\":\"2020-11-21T00:00:00.718+01:00\",\"title\":\"The Doors\",\"type\":\"EventCard\",\"updated_at\":\"2020-11-19T10:25:49.467+01:00\",\"user_full_name\":\"Carolann Ritchie\"},{\"id\":28163,\"attachment\":null,\"avatar\":null,\"card_comments_count\":0,\"card_likes_count\":0,\"card_publisher\":\"group\",\"created_at\":\"2020-11-14T23:22:42.059+01:00\",\"description\":\"That's life, you know, we never end up where you thought you wanted to be.\",\"ends_at\":\"2020-12-05T23:55:00.000+01:00\",\"event_attendees_count\":0,\"group_name\":\"Cheeseburger - Herbes de Provence\",\"origin\":\"http://localhost:3000/dorfplatz/3\",\"origin_name\":\"Dardagny - Athenaz (Avusy)\",\"picture\":null,\"starts_at\":\"2020-11-14T00:00:00.942+01:00\",\"title\":\"Iron Maiden\",\"type\":\"EventCard\",\"updated_at\":\"2020-11-19T10:25:59.622+01:00\",\"user_full_name\":\"Reuben Kertzmann\"},{\"id\":24658,\"attachment\":null,\"avatar\":null,\"card_comments_count\":0,\"card_likes_count\":0,\"card_publisher\":\"group\",\"created_at\":\"2020-11-14T14:40:45.442+01:00\",\"description\":\"You can't just skip ahead to where you think your life should be.\",\"ends_at\":\"2021-02-04T23:55:00.000+01:00\",\"event_attendees_count\":0,\"group_name\":\"Cheeseburger - Herbes de Provence\",\"origin\":\"http://localhost:3000/dorfplatz/3\",\"origin_name\":\"Dardagny - Athenaz (Avusy)\",\"picture\":null,\"starts_at\":\"2020-11-19T00:00:00.811+01:00\",\"title\":\"Steely Dan\",\"type\":\"EventCard\",\"updated_at\":\"2020-11-19T10:24:58.452+01:00\",\"user_full_name\":\"Reuben Kertzmann\"}]",

A: Use render_to_hash instead of outputting each serializer as JSON
def serialize_cards(cards)
  cards.group_by(&:type).map do |type, cards|
    case type
    when 'TypeOneCard'
      Api::V1::CardBlueprint.render_to_hash(cards, view: :one)
    when 'TypeTwoCard'
      Api::V1::CardBlueprint.render_to_hash(cards, view: :two)
    else
      raise ArgumentError, "Unhandled event type '#{type}'"
    end
  end
end


text:
Q: JVM Perm Gen / System freeze after capturing a function which is generated in an interpreter run I am using Scala dynamically embedded, and I thought I was smart to save re-interpretation of bits by capturing them in a Function0 of the host program. Approximately like this:
object Code
  def intp: IMain = ???

  object Capture {
    private val vr = new ThreadLocal[() => Any]

    def apply[A](thunk: => A) {
      vr.set(() => thunk)
    }

    def result: () => Any = vr.get()
  }

  def capture(code: String): Future[() => Any] = future {
    blocking {
      intp.setExecutionWrapper("Code.Capture")
      intp.interpret(code)
      Capture.result
    }
  }
}

This "somehow" works, but soon after the JVM goes nuts, basically hangs, produces Perm Gen errors etc. So I must be doing something forbidden. If I do not use the capture mechanism, it all runs smoothly (but I have to re-execute the interpret method over and over again instead of keeping the compiled function), so there is nothing wrong on that end.
I tried to run through a step debugger to see if I find anything suspicious, but no. At some point the program just completely freezes. I also isolated the futures case by launching a separate thread for the compilation with an auxiliary Promise on the main capture block that waits for is completion, that didn't change anything.
Any help is appreciated. Perhaps there is a confusion with class loaders and such? (my IMain does override parentClassLoader to be able to access the host classes).

I had a final intuition that perhaps I should serialize the function in the apply method (writeObject), and then deserialise in the host. But the readObject then produces a
java.lang.ClassNotFoundException: $line1.$read$$iw$$iw$$anonfun$1

Hinting perhaps at the problem beneath?


text:
Q: SCRIPT5022: WrongDocumentError appending element on IE Short background: I've been trying to create a newsletter content generator that takes XML feed as a source. To make it work, i must prepare each XML node element to fit my newsletter layout.
I use this method to merge 2 adjacent xml elements into single group node:
element_getter: function(xml) {

var deals = $(xml).find('campaign:eq(0) deal');

    deals = $.map(deals, function(val, index){

        if (index % 2 == 1) return;

        var group = $(document.createElement('group'));

        $(group).append(deals[index]);

            if (deals[index+1])
                $(group).append(deals[index+1]);

            return group;
        });

        return deals;
    }

The problem occurs with IE. When I try to create new node in document  or to append any content into it, I get SCRIPT5022: WrongDocumentError (This does not occur with FF or Chrome)
I've already tried to append this element in different ways (like $.parseXML), but it doesn't do the trick.
Any ideas?
Here is example of XML source:
<ebi-cmp-list version="1">
<campaign id="2">
    <title>Campaign</title>
    <startTime ts="201309090600">2013-09-09 06:00</startTime>
    <endTime ts="201309102359">2013-09-10 23:59</endTime>
    <type id="2">spec_offer</type>
    <deals>
        <deal id="15814">
            <event id="15814">Test Event</event>
            <venue id="429">Arena</venue>
            <city id="20">Berlin</city>
            <category id="73">Shows</category>
            <time ts="201310122000">2013-10-12 20:00</time>
            <price>
                <oldPrice currency="EUR">113.00</oldPrice>
                <newPrice currency="EUR">113.00</newPrice>
            </price>
            <ticketsLeft>26</ticketsLeft>
            <link rel="img">http://www.example.com</link>
            <link rel="event">http://www.example.com</link>
        </deal>
        <deal id="15814">
            <event id="15814">Test Event</event>
            <venue id="429">Arena</venue>
            <city id="20">Berlin</city>
            <category id="73">Shows</category>
            <time ts="201310122000">2013-10-12 20:00</time>
            <price>
                <oldPrice currency="EUR">113.00</oldPrice>
                <newPrice currency="EUR">113.00</newPrice>
            </price>
            <ticketsLeft>26</ticketsLeft>
            <link rel="img">http://www.example.com</link>
            <link rel="event">http://www.example.com</link>
        </deal>
    </deals>
</campaign>

A: I'm surprised the other browsers don't complain, because normally you can not simple append a node that belongs to one document (your XML) to another document (your HTML document) – you should only be able to append nodes into a node that has the same ownerDocument.
Try importing your XML nodes into your HTML document's "scope" with importNode first.


text:
Q: Error comverting date using SimpleDateFormat I want to convert a date in format dd MMM yyyy (23 May 2015) to yyyy-MM-dd.
The code I'm using:
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM dd", Locale.ITALY);
try {
    Date varDate = simpleDateFormat.parse(date);
    simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.ITALY);
    date = simpleDateFormat.format(varDate);
} catch (ParseException e) {
    e.printStackTrace();
}

The variable date before conversion: 23 May 2015
After conversion: 2015-05-23
Unfortunately I'm getting an error:
java.text.ParseException: Unparseable date: "23 May 2015" (at offset 3)

A: I think you will find that in Italian, May is "Maggio".
Note that it says "offset 3" in the exception, which is the fourth character (we are counting from zero). That is the month string.
Also, you have "dd" as the year format instead of "yyyy".

A: At first there's a typo in original format. It should be  "dd MMM yyyy". And secondly the locale is set to Italy and it means input  month should be in Italian, not in English. Or you should change locale parameter.


text:
Q: Why does class not registered error occur when running SSIS packages from ASP.NET? I run ssis package from my asp.net application. When it's running on my local machine (32-bit OS), everything is working fine.
but when I published my site on remote computer (64-bit OS) I was getting run-time error:
Could not load file or assembly 'Microsoft.SqlServer.ManagedDTS, Version=10.0.0.0,
Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The system cannot
find the file specified.

I put Microsoft.SqlServer.ManagedDTS.dll and Microsoft.SqlServer.DTSRuntimeWrap.dll into the bin folder of my web site.
After that I had the next error:
 "An attempt was made to load a program with an incorrect format"

I  turned on " Enable 32-Bit Applications" option on iis for application pool and changed platform target to x86 in the properties of a project.
And now I have the following error:
 Retrieving the COM class factory for component with CLSID {BA785E28-3D7B-47AE-A4F9-4784F61B598A}
 failed due to the following error: 80040154 Class not registered
 (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

Any ideas how to fix that?
OR may be I'm moving in wrong direction?
Any help is appreciated.

A: MSDN reference:
Read the topic Understanding the Differences between Local and Remote Execution on MSDN to understand the concept of running the packages remotely
You can only run a package outside the development environment on a
computer that has Integration Services installed

The server that hosts your package should have Integration Services installed. Please consult Microsoft document on how the licensing model works with respect to Integration Services. Copying only the DLLs to the server where the package should run will not resolve the issue.
You can remotely invoke the package execution but you still need Integration Services on the server hosting the package.
MSDN blog article:
Running SSIS package programmatically Read the point 1 in the article that describes about executing SSIS packages from ASP.NET
Quoted directly from the article:
Run package programmatically using SSIS Object Model. This is discussed in details in Books Online here: http://msdn2.microsoft.com/en-us/library/ms136090.aspx
Benefits: Everything runs in process, it is very easy to set variables or modify package before executing it. You can also get events about package progress or ask it to stop by setting CancelEvent.
Drawbacks: Obviously this is local execution - you need to install SSIS on same machine where your app runs. This method also can't be used from .NET 1.1 application, unless it is moved to .NET 2.0 (which should be very easy to do, and in my experience improves the performance as well).
ASP.NET specific: The impersonation context does not get passed to additional threads SSIS package creates, so the data source connections will not be impersonated. Also, ASP.NET can be configured to recycle the worker process in case it consumes too much memory to improve availability of ASP.NET application. Since SSIS is likely to consume a lot of memory if you have lots of data, it can trigger this recycling and lower reliability of your application.

A: Some Background
This works on your local machine because your SSIS package build version matches the Microsoft.SqlServer.ManagedDTS.dll version you have in ASP.NET project. Now, you need to match the library versions from your SSIS build package to your Microsoft.SqlServer.ManagedDTS.dll versions. The versions must match and the 32-bit versus 64-bit libraries must match as well.
Answer
An easy way to do this is: Add SSIS script task to your package (on your remote server) and click the 'Edit Script' button. Now, look in the SSIS library references and you should see the version that the SSIS package loaded. That is the one you need to compile with ASP.NET project. This Script tasks can be deleted afterwards.


text:
Q: Arcgis JS API 3.x Popup infotemplate (popup) with relationship attributes I've buildt a halfly harcoded popup builder widget, but i don't know how to push fields from relationships into my popup div. I know how to do it in the ObjOriented way, but it's not right for me.
Example:

   var popupTemplate = new PopupTemplate({
     "title": "Beverly Hills Trees By Block",
     "fieldInfos": [{
       "fieldName": "Point_Count",
       "label": "Count of Points",
       "format": {
         "places": 0,
         "digitSeparator": true
       }
     }, {
       "fieldName": "relationships/0/Point_Count_COMMON",
       "label": "Sum of species tree count",
       "format": {
         "places": 0,
         "digitSeparator": true
       },

I show my scructure: first function creates the popup content div, the second calls it, if i want popup.
But i couldnt find the documentation, how to get a graphic's relationships, i can only get the attributes.
Any idea?
     function _getPopupTextContent(graphic) {
       let popupContent = ""
       popupContent += "
" +
       "
" +
       "
"
       console.log(graphic)
       //popupContent +=  "
"+graphic.attributes["relationships/1/FIELD"]+"
" not working //undefined

       for (var property in graphic.attributes){
         console.log((property.toString()).split(/[.]/))
         var dbName = (property.toString()).split(/[.]/)[1]
         if (dbName !== undefined){
          var dbTableName = dbName.split(/[_]/)[3];
         //console.log(maximoTableName)
         var fieldName = (property.toString()).split(/[.]/)[2];
         let value = graphic.attributes["DB.DB_ESRI_V_"+dbTableName+"_TT."+fieldName]

           if(fieldName == 'FIELDNAME1'&& value !== undefined){
             popupContent += "

Label	" +
             value
           }
           if(fieldName == 'FIELDNAME2'&& value !== undefined){
             popupContent += "
Label	" +
             value
           }
           if(fieldName == 'FIELDNAME3'){
             popupContent += "
Label	" +
             value
           }
           if(fieldName == 'FIELDNAME4'&& value !== undefined){
             popupContent += "
Label	" +
             value
           }
       }
           popupContent += "
" +
                           "
" +
                           "
" +
                           "

"
       return popupContent;
     }

     function _joinAndCreateInfoTemplate(){
       var mainLayer = _getWebmapOperationalLayerById(subStationLyrId);

       for(var title in popupSubIdDict){
         var popupName = _removeAccents(title).toLowerCase(); // subLayertitle
         var subId = popupSubIdDict[title]; //sub id

         mainLayer.getLayerObject().then(function (subLyrObj) {

           if (popupName == 'sublayer'){
             popupName = new InfoTemplate();
             popupName.setTitle(title);
             popupName.setContent(_getPopupTextContent);
           }

             subLyrObj.infoTemplates[subId] = {
               infoTemplate: new InfoTemplate(popupName)
             };


text:
Q: How to deploy Django app on Google App Engine and make connection with Postgres instance? Currently I am trying to deploy a Django app on Google App Engine(GAE). All goes well and app is deployed, but when it gets deployed, its connection with Postgres instance lost. I don't know why this happening. following is my settings.py file.
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'dbname',
        'USER': 'username',
        'PASSWORD': 'password',

    }
}
# In the flexible environment, you connect to CloudSQL using a unix socket.
# Locally, you can use the CloudSQL proxy to proxy a localhost connection
# to the instance
DATABASES['default']['HOST'] = '/cloudsql/shopnroar-175407:us-central1:snr-instance1'
if os.getenv('GAE_INSTANCE'):
    pass
else:
    DATABASES['default']['HOST'] = '100.107.126.241'

When i run it locally, it's making connection with google cloud Postgres as i have given ipv4 address to make connection, but as soon as i deploy it on GAE, following error comes while accessing database.
Is the server running locally and accepting
    connections on Unix domain socket "/cloudsql/shopnroar-175407:us-central1:snr-instance1/.s.PGSQL.5432"?

here is my app.yaml
# [START runtime]
runtime: python
env: flex
entrypoint: gunicorn -b :$PORT SNR.wsgi

env_variables:
    # Replace user, password, database, and instance connection name with the values obtained
    # when configuring your Cloud SQL instance.
    SQLALCHEMY_DATABASE_URI: >-
      postgresql+psycopg2://amad.uddin:goingtoin1122@/shopnroar?host=/cloudsql/shopnroar-175407:us-central1:snr-instance1
beta_settings:
    cloud_sql_instances: shopnroar-175407:us-central1:snr-instance1

runtime_config:
  python_version: 2
# [END runtime]

Can anybody tell me how can i make connection with postgres instance after deploying django app on GAE?
Any help or suggestions will be highly appreciated.

A: Actually - forget my old answer - try turning the app.yaml values into strings, that helped me out:
cloud_sql_instances: 'shopnroar-175407:us-central1:snr-instance1'


text:
Q: How to delete all values in MS Project TimeScaleData I'm using the BaselineWork1 timescaledata to contain a time phased calculation of resource work on individual tasks that I perform on a weekly basis. I want to zero out the previous week's calculation before I populate it with this week's calculation. Short of creating a loop to write zeros to the timescale data for each resource on each task is there a way to do this more efficiently? Could I make the beginning date and end date equal to the project's start and end date and time scale = seconds and the value to write equal to zero? For instance:
    For lngCnt1 = 1 To tskCounter.Resources.Count
        tskCounter.Assignments.Item(lngCnt1).TimeScaleData(StartDate:=ActiveProject.ProjectStart, EndDate:=ActiveProject.ProjectFinish, _
        Type:=pjAssignmentTimescaledBaseline1Work, _
        timescalunit:=pjTimescaleMinutes, Count:=1).Item(1).Value = 0
    Next lngCnt1

This doesn't seem to work as it only zeros out the baseline1 work field for the date corresponding to the project start date.

A: To clear time-scaled work from anything but the forecast work field, you do need to loop through every assignment on every task. However, when it comes to the individual time-scale values, you can lump these together by year to reduce the iterations required.
Sub ClearBaseline1Work()

    Dim projStart As Date
    Dim projEnd As Date
    projStart = ActiveProject.ProjectStart
    projEnd = ActiveProject.ProjectFinish

    Dim tsk As Task
    For Each tsk In ActiveProject.Tasks
        Dim asn As Assignment
        For Each asn In tsk.Assignments
            Dim TSValues As TimeScaleValues
            Set TSValues = asn.TimeScaleData(projStart, projEnd, pjAssignmentTimescaledBaseline1Work, pjTimescaleYears)
            Dim tsv As TimeScaleValue
            For Each tsv In TSValues
                tsv.Clear
            Next tsv
            asn.Baseline1Work = 0
        Next asn
        tsk.Baseline1Work = 0
    Next tsk

End Sub

Remember that Baseline1 work values are not automatically updated at the assignment or task level; those values need to be explicitly cleared.