text:
Q: Both iterate and get value with index on a collection in a Lightning Component I have a list of values on which I want both to:

*

*Iterate with aura:iteration

*Get somewhere else in my component specific values based on the index in the list

From what I understand, I can get a specific value with a map, but not iterate over it.
I can iterate over a list but not get a specific value with the index.
As an example, it would looks like something like this:
<aura:component >
    <aura:attribute name="myList" type="List" />

    <!-- What I want 1: iterate -->
    <aura:iteration var="listItem" items="{!v.myList}" indexVar="index">
        {!v.listItem}
    </aura:iteration>

    <!-- What I want 2: Outside of the iteration, get some elements by index -->
    {!v.listItem[2]}

</aura:component>

Is there a way to do this ?
Of course I would like to avoid having 2 attributes with 2 types but the same values in it.

A: Both will work. It seems to me as some syntax errors;
<aura:component >
    <aura:attribute name="myList" type="List" />

    <!-- What I want 1: iterate -->
    <aura:iteration var="listItem" items="{!v.myList}" indexVar="index">
        //{!v.listItem}
        {!listItem}//Change: This is not an attribute. So 'v.' is not required.
    </aura:iteration>

    <!-- What I want 2: Outside of the iteration, get some elements by index -->
    //{!v.listItem[2]}
    {!v.myList[2]}//Change: 'myList' is the original attribute. 'listItem' is just local to 'aura:iteration'(in this case)

</aura:component>


text:
Q: Univariate Representation of Affine Transformation Definition: Let $0\leq i \leq n$ and $A_i,B_i \in \mathbb{E}$. Then we call the polynomial $S(X)=\sum_{i=0}^{n-1}B_i X^{{q}^i}+A$ the univariate representation of the affine transformation $S(X)$.
$\mathbb{E}$ is an extension of $\mathbb{F}$ and $|\mathbb{F}|=q$
My question is Why, in $S(X)$, the elements $X$ have exponent $q^i$, What's mean that?

A: The point is that $X\mapsto X^q$ is linear in $\Bbb E$ (over $\Bbb F$, at least), whereas the other polynomials are not linear, so they couldn't form an affine transformation.

redpajama_set_name: RedPajamaStackExchange


text: Q: Stubbing node.js lambda function that converts a csv to json I have an AWS lambda function that converts CSVs into zipped json files. I was told to write unit tests by making sample input csv files and then checking the json output without making actual calls to AWS. I'm pretty new to Node.js, and am wondering what would be the best way to go about this? I'm using https://github.com/Keyang/node-csvtojson for the conversion. I'm using mocha for testing, I've looked into https://github.com/dwyl/aws-sdk-mock and sinon for stubbing, but haven't gotten them to work. Any ideas would be appreciated.


text:
Q: How to call an application which is located on my desktop through shinyApp? I want to call an application which is installed on my system under c:// drive.
I want to call 'tableau.exe' application by clicking on action button in a shinyApp.
My code:
library(shiny)

ui <- fluidPage(
  actionButton('run','Run executable!')
)

server<- function(input,output)
{
  observeEvent(input$run,
               {
                 system("cmd.exe", input = "tableau.bat")
               })
}

shinyApp(ui,server)

A: In server code: the line "system("cmd.exe", input = "tableau.bat")" would call the tableau.exe file. For any '.exe' file calling through shinyApp require a '.bat' file save in the work space.


text:
Q: Use PyLint to calculate Cyclomatic Complexity I want to calculate Cyclomatic Complexity by using PyLint. I need to have a python script that calculates the complexity of many modules at once.
I have tried using command as well as through python program.
This is the command i'm using:
pylint shortQuestion.py --load-plugins=pylint.extensions.mccabe

This is the code i'm using in python:
import pylint.lint

pylint_opts = ['basics.py','--load-plugins=pylint.extensions.mccabe','--rcfile=~/.pylintrc']

pylint.lint.Run(pylint_opts)

Here is the result i get from the command and code:
Using config file /var/root/.pylintrc
************* Module shortQuestion
W:  5, 0: Found indentation with tabs instead of spaces (mixed-indentation)
W:  6, 0: Found indentation with tabs instead of spaces (mixed-indentation)
W:  7, 0: Found indentation with tabs instead of spaces (mixed-indentation)
W:  8, 0: Found indentation with tabs instead of spaces (mixed-indentation)
C:  1, 0: Module name "shortQuestion" doesn't conform to snake_case naming style (invalid-name)
C:  1, 0: Missing module docstring (missing-docstring)
C:  4, 0: Function name "isContained" doesn't conform to snake_case naming style (invalid-name)
C:  4, 0: Missing function docstring (missing-docstring)
R:  5, 1: Unnecessary "else" after "return" (no-else-return)
W:  4,16: Unused argument 'cls' (unused-argument)

----------------------------------------------------------------------
Your code has been rated at -15.00/10 (previous run: 10.00/10, -25.00)

is the -15.00/10 Cyclomatic Complexity here? If yes, how can i get the output in formatted way? Since i need to calculate this complexity for many python modules at once. If not, how can i calculate this?

A: The score that you are seeing at the end of you output is your overall score of your code quality based on pylint. If you fix all these warnings, the score will go to 10 out of 10.
The message that you should be seeing in case your cyclomatic complexity is too high is this:

R:1: 'function1' is too complex. The McCabe rating is 11 (too-complex)

See also the docs.


text:
Q: Add class to selected ng-repeat list elements Hey I'm looping thru an array using ng-repeat in my template. The list spits out 9 list elements and I would like change the background color of the selected list element but I want to do it in a way where multiple ones can be selected and the color of the selected ones with a different background color. Initially I had passed $event to the click function on the list element and added a class to event.target but that put the class on all the list elements rather than the selected one.

{{card.name}}{{$index + 1}}

HTML:
$(event.target).addClass('active.cards');

JS:
The list that I'm repeating thru unforunately doesn't have a unique ID or I would have passed in the ID and created a condition to check whether the selected items have one and applied the class.

A: It's a much better practice to simply use ng-class for this.

{{card.name}}{{$index + 1}}


text:
Q: Replace string with numbered list Here is the scenario:

*

*Created a numbered list using an Android Markdown app

*Imported list to Emacs

*For some reason, all numbers beyond 174 have a [[tel:INT]] line prefix
172.
173.
174.
[[tel:175][175]].
[[tel:176][176]].
[[tel:177][177]].

I want to find each instance of [[tel:INT]] and replace it with 175, 176, 177, etc.
Question:
Whats the best way to grep/sed/awk this list into order?

A: this should do...
sed -E 's/\[\[.*\[(.*)\]\]/\1/' file

172.
173.
174.
175.
176.
177.

A: Using sed
sed -E 's/\[\[tel:([0-9]+)\]\[[0-9]+\]\]/\1/g' tmp.txt

Output:
172.
173.
174.
175.
176.
177.

A: Since the other answers are sed:
grep -Eo '[0-9]+' input.txt | sort -un

Given input file input.txt:
172.
173.
174.
[[tel:175][175]].
[[tel:176][176]].
[[tel:177][177]].

Then:
grep -Eo '[0-9]+' input.txt | sort -un

Results:
172
173
174
175
176
177


text:
Q: Converting data bind values to strings inside foreach knockout I have this fiddle. All I want to do is , convert the values nested in each object literal to a string.

 function AppViewModel()
{
    var self = this;
    self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
}

ko.applyBindings(new AppViewModel());

I want to use a lookup
like
var valueMap={
    1:"SanJose",
    2:"San Francisco"
}

To get output like
RobbStark SanJose
JohnSnow San Francisco.

How do I convert the observable to a different value inside foreach ?

A: All you have to do is call a javascript function from your text data-binding, passing in the current item ($data) from the for each loop as a parameter.  Example fiddle
Javascript:
var valueMap={
    1:"SanJose",
    2:"San Francisco"
}

 function AppViewModel()
{
    var self = this;

    self.people = ko.observableArray([{"Name":"RobbStark",Id:1}, {"Name":"JohnSnow",Id:2}]);
    self.parsedName = function (item) {
        return item.Name + " " + valueMap[item.Id];
    };
}

ko.applyBindings(new AppViewModel());

HTML

Note #1 under the KnockoutJS documentation contains more information about $data.


text:
Q: What's the easiest and fastest way of messaging 30 objects at the "same" time? I have a UIScrollView where a lot of objects appear (UIImageView's) during scrolling. However, when the user is scrolling, I want to fire messages to all these objects, in order to tell them that they shall not do anything stupid. When the UIScrollView decelerates, some animations happen at the visible objects. When the user moves on fast (pagingEnabled=YES), more and more objects are still animating, which will result in horrible scroll performance.
I want to tell them all to immediately stop and do nothing as soon as the user is scrolling. So, what can I do? A for-loop is bad for performance upon scrolling. It will jerk for a small moment, but that's enough to make the user very very mad.

A: Put them all in an array, and use [NSArray makeObjectsPerformSelector:]. That's the most concise way to do it, but I'm not sure it's any more efficient than using a for loop...
I'm not sure how you're animating your views, but you might want to use the UIScrollView's delegate functions to maintain a subarray of visible items and limit your animations to those. For instance, whenever the visible rectangle changes, you could look at your existing list of visible views and see if any are completely offscreen. You could stop animating those. You could then look for views that were on-screen but not in the list and begin animations on them. I've done something like this before, and it helped improve performance substantially!
Then if you want to freeze all the running animations, you've got an array of the animating ones and it's relatively short.
Hope that helps!

A: Also remember that the computers can only do things in a linear fashion.  So no matter what you do you will have to use some sort of loop control structure.
perhaps kick off a thread that contains the loop.  and the loop will call the
perfomrselectoronmainthread:

selector for each object.  (remember for UI stuff it has to be executed on the main thread.)
and i asume you are using
+ (void)setAnimationsEnabled:(BOOL)enabled

To stop the animation.
if this is still not fast enough you will have to look at Core Animations, these will have extra efficiencies that will allow this to happen.

A: I would use notifications. This has the advantage that you can notify all of your objects passing them all of the information required. It is also a simple, yet powerful mechanism, allowing asynchronous communication.
See Introduction to Notification Programming Topics:
http://developer.apple.com/documentation/Cocoa/Conceptual/Notifications/Introduction/introNotifications.html

A: Try to Perform each message on a different thread. Of course all UI updates have to be on the main thread, but if you can do some work in a background thread, maybe it will reduce some lag. (I can't say how feasible this is for 30+ objects however)


text:
Q: C++ Passing vector to a function that is already passed #include<bits/stdc++.h>
using namespace std;

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}

I want to pass a vector again to other function that has been passed. But this seems to not work. How could I implement something like this

A: You code doesn't compile because func() doesn't know about extra_func(). You either need a function declaration (sometimes called a function prototype) or to rearrange your functions.
void extra_func(vector<int> &); // declaration

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

void extra_func(vector<int> &vect) // definition
{
   vect.push_back(40);
}

or
void extra_func(vector<int> &vect) // now it's visible to func()
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

A: The problem arises as you are calling extra_func without func knowing about it so you must initialize extra_func before func
Your code should be like
#include<bits/stdc++.h>
using namespace std;

void extra_func(vector<int> &vect)
{
   vect.push_back(40);
}

void func(vector<int> &vect)
{
   vect.push_back(30);
   extra_func(vect);
}

int main(){
    vector<int> vect;
    vect.push_back(10);
    vect.push_back(20);

    func(vect);

    for (int i=0; i<vect.size(); i++)
       cout << vect[i] << " ";

    return 0;
}


text:
Q: jQuery eventData undefined when placed in interval/timeout function EDIT: See comments for how I don't know how to use events at a basic level (and the answer)
I feel like this should be an easy fix, but I've been pulling my hair out about it for the past hour.
I have a function that looks like this:
$(document).ready(function() {
    $("#score svg").mousedown(event.data, scoreDrag);
});

Which works perfectly fine, event is defined.
But I don't want the handler to be assigned until some function in a different script (defined before this one) has finished making all the SVGs in #score
So what I've done is define a global variable in the script that makes the SVGs (SVGloaded) that isn't true until it finishes making all the SVGS - a là:
var isSVGloaded;

$(document).ready(function() {
    isSVGloaded = window.setInterval(function() {
        if (SVGloaded) {
            $("#score svg").mousedown(event.data, scoreDrag);
            window.clearInterval(isSVGloaded);
        }
    }, 100);
});

Which, DOESN'T work - event is not defined.
I have the above code inside a module-global function in my actual scripts, but I don't think that has anything to do with it.

A: When you're using event in your first example you're probably referring to window.event, which is assigned in some browsers to the last event that was raised:
http://www.quirksmode.org/js/events_access.html
As mentioned in the comments, you probably shouldn't rely on this because it's non-standard and (IMHO) super-confusing.
Anyway, in your first case window.event will be the ready event that jQuery is responding to, not the click event that you probably want to handle (http://jsfiddle.net/XLhL9/1/).
If you're in a setInterval callback then it looks like window.event is not defined at all, presumably because the browser is not currently handling an event. You can see this in http://jsfiddle.net/ujR5p/.
If you really wanted to access the ready event in your setInterval callback the trick would be to get the value of window.event inside the ready callback, assign it to a variable and then refer to that variable in your timeout callback:
$(document).ready(function() {
    // event is defined here, so assign it to a variable
    var theEvent = event;
    isSVGloaded = window.setInterval(function() {
        if (SVGloaded) {
            // event is no longer defined, but theEvent still is:
            $("#score svg").mousedown(theEvent.data, scoreDrag);
            window.clearInterval(isSVGloaded);
        }
    }, 100);
});

But it sounds like what you really want is the mousedown event. Fortunately jQuery makes this super easy to access:
var scoreDrag = function (eventObject) {
    // jQuery will pass the `mousedown` event in as `eventObject`
    // see http://api.jquery.com/mousedown/#mousedown-handler
    alert('X: ' + eventObject.pageX + ' Y: ' + eventObject.pageY);
};

Could you perhaps avoid this setInterval by executing this code on load instead of ready? Or by raising a custom event?

A: I'm shure that your first script do not work
$(document).ready(function() {
    $("#score svg").mousedown(event.data, scoreDrag);
});

Maybe you mean something like this:
$(document).ready(function() {
    $("#score svg").mousedown(
          function(event){
              alert('Mouse down');
          }
    );
});


text:
Q: GWT: how to attach GAE Blob data to new PDF file I have a PDF file stored in GAE server and I want to display it on the client side. How can I make the new pdf file? I try do this:
String str = toBase64(result.get(1));// result.get(1) has byte[] type
HeadElement headElement = Document.get().createHeadElement();
LinkElement link = Document.get().createLinkElement();
link.setType("application/pdf");
link.setHref("Content-Disposition\", \"attachment;filename=" +  str);
headElement.appendChild(link);

A: You cannot do it on the client. On the client, you simply show a link like
https://myapp.com/file?id=123

if you store blobs by ids, or you can use a blob key, etc. On the server side, you need a servlet /file which will take this id or key, retrieve the blob, and set the correct headers on the response:
response.setHeader("Content-Disposition", "attachment;filename=" + "somename.pdf");
response.setContentType("application/pdf");
OutputStream outputStream = response.getOutputStream();
// document is byte[]
outputStream.write(document);
outputStream.close();

Then a browser would know that the incoming response is a PDF file. So it will ask a user where to save it.


text:
Q: How to tell what Entry has focus (Tkinter) I'm working on a project that has a keypad with the number "0 - 9" + a ".". I'm wanting to update several entry boxes one at a time with whatever combination of numbers that are generated from the buttons. The problem I'm having is trying to figure out how to tell what entry box has focus at that time. I've done some googling and have been able to print out different numbers for the entry box selected using focus_get() but that number changes. In the end, I want to be able to click in a entry box with a name similar to entry_0 and be able to click on a button that will pass an integer to that selected box and then be able to click in another box and pass another integer.
Bellow is some code that I found by googling and is the closest that I've found to being able to do what I want but the numbers it prints are different every time the code is ran.
from Tkinter import *
root=Tk()
e1=Entry(root)
e1.pack()
e2=Entry(root)
e2.pack()
def handleReturn(event):
    print "return: event.widget is",event.widget
    print "focus is:",root.focus_get()

root.bind("<Return>",handleReturn)

root.mainloop()

A: Thanks. With some minor tweaks, I was able to get it working the way I want it to.
from Tkinter import *

root=Tk()
e1=Entry(root)
e1.pack()
e2=Entry(root)
e2.pack()
def handleReturn(event):
    test = root.focus_get()
    print test.get()

root.bind("<Return>",handleReturn)

root.mainloop()


text:
Q: How do I fully characterize these subsets. I'm working through the following,

Exercise 2.1.iv. A functor $F$ defines a subfunctor of $G$ if there is a natural transformation $\alpha: F \Rightarrow G$ whose components are monomorphisms. In the case of $G: C^{op} → \operatorname{Set}$, a subfunctor is given by a collection of subsets $Fc \subset Gc$ so that each $Gf : Gc \longrightarrow Gc'$ restricts to a function $Ff: Fc → Fc'$. Characterize those subsets that assemble into a subfunctor of the representable functor $C(−, c)$.

I am wanting to know how do I fully characterize these subsets they speak of. I saw that this was already asked but it feels incomplete.
The person says that it is a collection of morphisms with codomain $c$ that are closed under precompositions with morphisms in $\textbf{C}$. My question is how do we prove that instead of show it like they did.


text:
Q: Vue.js unexpected data and method behaviour I have a Vue.js component with simple template
<div @click="createTargets(2)">
text
</div>

and script file is
export default {
  name: 'test',
  data() {
    return {
      targets: [],
    };
  },
  methods: {
    createTargets(targetCount) {
      this.targets = [];
      var emptyTarget = {
          id: null,
      };
      for (var i = 0; i < targetCount; i++) {
        var targetToPush = emptyTarget;
        targetToPush.id = i;
        console.log(targetToPush.id);
        this.targets.push(targetToPush);
        console.log(this.targets);
      }
      return {};
    },
  },
}

When I click text, I get output
0
[{"id":1},{"id":1}]
1
[{"id":1},{"id":1}]

I cannot figure out why this is happening.
I would expect
0
[{"id":0}]
1
[{"id":0},{"id":1}]

Any ideas?

A: console.log()

Please be warned that if you log objects in the latest versions of Chrome and Firefox what you get logged on the console is a reference to the object, which is not necessarily the 'value' of the object at the moment in time you call console.log(), but it is the value of the object at the moment you open the console

Don't use console.log(obj), use console.log(JSON.parse(JSON.stringify(obj)))

A: The answer is quite simple really, an object is initialized only once, when it is assigned to a variable. If you assign this variable to a new variable, you are assigning the same object reference to a new variable. Updating Object1 will update Object2 and vice versa.
To circumvent this behavior, you can create a copy of the object when initializing Object2 using the new spread operator:
const targets = [];
const common = { commonProp: 'test' };

for (let i = 1; i <= count; i++) {
  const target = { ...common, id: i };
  targets.push(target);
}

this.targets = targets;

Note that you should avoid mutating your component's state in a loop. Even though the render loop is optimized and won't actually render count times, it's still better to mutate your property only once as per example.
Also note that nested objects behave the same way. The solution above is called a shallow copy, in contrast, a deep copy will recursively crawl your object to copy sub objects/arrays.
const common = {
  commonProp: { a: 1, b: 2 }
};
const object1 = { ...common, id: 1 };
const object2 = { ...common, id: 2 };
object1.commonProp.a = 2;
console.log(object1); // { commonProp: { a: 2, b: 2 } }
console.log(object2); // { commonProp: { a: 2, b: 2 } }

To avoid this issue, you can use a library to deep copy an object/array or create a class or factory function that will return a new object every time it is called.
// factory
const createTarget = id => ({
  commonProp: { a: 1, b: 2 },
  id,
});

// class
class Target {
  constructor(id) {
    this.id = id;
    this.commonProp = { a: 1, b: 2 };
  }
}

for (let i = 1; i <= count; i++) {
  const target = createTarget(i); // or new Target(i);
  targets.push(target);
}

I hope this explanation helped you understand this concept a bit better.
Good luck ;)

A: You might print the array values (not the reference):
for (var i = 0; i < targetCount; i++) {
  var targetToPush = emptyTarget;
  targetToPush.id = i;
  console.log(targetToPush.id);
  this.targets.push(targetToPush);

  // like this (es6 way):
  console.log([...this.targets]);

  // or like this (old way):
  console.log(this.targets.slice());
}

When you console.log(this.targets) you are printing directly the variable reference, and it's values will be chaging in the next loop, so it's also going to be changed in the browser console.
When you console.log([...this.targets]) you are printing the array values (not the reference) of that given loop interaction and they will stay the same, even if the array changes later.

A: the main problem , you are updating the reference variable, so it i will keep always the latest data.
just do like below hope problem will solve
createTargets(targetCount) {
      this.targets = [];
      for (var i = 0; i < targetCount; i++) {
        var targetToPush = {id: null};
        targetToPush.id = i;
        console.log(targetToPush.id);
        this.targets.push(targetToPush);
        console.log(this.targets);
      }
      return {};
    }


text:
Q: how to post image to twitter by using http://upload.twitter.com/1/statuses/update_with_media for below ios 5.0 i'm trying to share image on twitter by using new api statuses/update_with_media. Then i searched and got below code from dev.twitter.com/discussion page. Here the code is below.
enter code here
- (NSString *) _uploadImage:(UIImage *)image requestType:(MGTwitterRequestType)requestType responseType:(MGTwitterResponseType)responseType
{

    NSString *boundary = @"----------------------------991990ee82f7";

    NSURL *finalURL = [NSURL URLWithString:@"http://upload.twitter.com/1/statuses/update_with_media.json"];
    if (!finalURL)
    {
        return nil;
    }

    NSLog(@"-> Open Connection: %@", finalURL);

    OAMutableURLRequest *theRequest = [[OAMutableURLRequest alloc] initWithURL:finalURL
                                                                      consumer:self.consumer
                                                                         token:_accessToken
                                                                         realm: nil
                                                             signatureProvider:nil];

    [theRequest setHTTPMethod:@"POST"];
    [theRequest setHTTPShouldHandleCookies:NO];

    // Set headers for client information, for tracking purposes at Twitter.
    [theRequest setValue:_clientName    forHTTPHeaderField:@"X-Twitter-Client"];
    [theRequest setValue:_clientVersion forHTTPHeaderField:@"X-Twitter-Client-Version"];
    [theRequest setValue:_clientURL     forHTTPHeaderField:@"X-Twitter-Client-URL"];

    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [theRequest setValue:contentType forHTTPHeaderField:@"content-type"];

    NSMutableData *body = [NSMutableData dataWithLength:0];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"media_data[]\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:[UIImageJPEGRepresentation(image, 1.0) base64EncodingWithLineLength:0]] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"status\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithString:@"Honeymoon uploads image\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

    // --------------------------------------------------------------------------------
    // modificaiton from the base clase
    // our version "prepares" the oauth url request
    // --------------------------------------------------------------------------------
    [theRequest prepare];

    [theRequest setHTTPBody:body];

    // Create a connection using this request, with the default timeout and caching policy,
    // and appropriate Twitter request and response types for parsing and error reporting.
    MGTwitterHTTPURLConnection *connection;
    connection = [[MGTwitterHTTPURLConnection alloc] initWithRequest:theRequest
                                                            delegate:self
                                                         requestType:requestType
                                                        responseType:responseType];

    if (!connection)
    {
        return nil;
    }
    else
    {
        [_connections setObject:connection forKey:[connection identifier]];
        //[connection release];
    }

    return [connection identifier];
}

Then i was implemented this code in SA_OAuthtwitterengine because i'm using oauth method for post text or image to twitter because my application deployment target is starting form 3.0(ios,ipod), so i try to this method.
Now my problem is how to create code for send image to twitter with message.
i try to send image to twitter using the below type
[_engine sendupdate:@"http://www.prepare-community.com/ShareFiles/index-fr.jpg"];

i got connection error that means 401 error.
could you please send me how to send image to twitter using above code?

A: Here is the solution for image uploading using new twitter api update_with_media. Using this api you can upload image direct way to twitter account. The above _uploadimage code should be placed first in SA_OAuthtwitter engine .m file and decalred in .h file.
And make a small correct that is where placed filenamed=1.jpg instead of 1.png.
And now just put the below code in MGTwitterengine.m class. here the code is below
    - (NSString *)_uploadImage:(UIImage *)image withStatus:(NSString *)status
{
     return [self _uploadImage:image withStatus:status requestType:MGTwitterImageRequest responseType:MGTwitterStatuses];
}

And then we use this code for upload image to twitter. that is,
[_engine _uploadImage:yourpicture withStatus:yourstatus];
Hope it will work for you....


text:
Q: libmosquittopp - loop_start() returned error code 10 (0xA) I'm trying to create my MQTT client(pub/sub) with "MQTTWrapper" class.
I tested connect_async() and loop_start() functions.
But loop_start() returned error code 10. I think it means "MOSQ_ERR_NOT_SUPPORTED".
I'm testing MQTT version 2.0.7.
Anyone who can help me?
mqtt_client.h
class mqtt_client : public mosqpp::mosquittopp
{
public:
    mqtt_client (const char* id, const char* topic, const char* host, int port, int keepalive, int qos);
    ~mqtt_client();

    void on_connect(int rc);
    void on_disconnect(int rc);

    int afx_connect();
    int afx_disconnect();
    int afx_publish(const char* msg);
};

mqtt_client.cpp
int mqtt_client::afx_connect()
{
    int rc = connect_async(host_, port_, keepalive_);
    if (rc != MOSQ_ERR_SUCCESS) {
        CLog::WriteLog(_T("connect_async() failed. Code %d"), rc);
        return rc;
    }

    //Start a thread and call mosquitto_loop() continuously in the thread to process network information
    rc = loop_start();
    if (rc != MOSQ_ERR_SUCCESS) {
        CLog::WriteLog(_T("loop_start() failed. Code %d"), rc);
        return rc;
    }

    return MOSQ_ERR_SUCCESS;
}


text:
Q: Creating a large array of objects Objective-C I need to display a list of items from a database in an "A to Z" fashion. This list of items is > 1200. My question is: can I simply use NSArray? Or would it be better to use something like an NSDictionary? Any suggestions would be greatly appreciated.

A: There isn't sufficient information in your question to know whether to use an array or a dictionary (or a set). Everything depends on how you want to access these things. If by keyword, it's a dictionary. If by index number, it's an array. And so on.
Certainly the number of elements (which appears in your question) is irrelevant to the choice. A collection of 1200 things is a collection of 1200 things, no matter what kind of collection it is. And 1200 is tiny. If it were 12000, or 120000, you might start thinking of keeping a real database on disk - and no kind of collection in memory.

A: The key hint I see in your question is "In A to Z fashion." Arrays save an ordered collection of objects. To present a collection of things in A to Z order, they need to be ordered.
Sets and dictionaries are unordered collections.
There is a small amount of overhead in using objects to save data instead of using simple memory structures. If you were dealing with hundreds of thousands -or millions- of things, that overhead could become a consideration. But with a 4-digit number of items, it is not a concern.
NSArrays store objects. If you are already saving your things in objets, NSArray/NSMutableArray is an excellent choice for organizing your objects.
As the other poster said, if you're dealing with very large numbers of objects, you should think about using a database system like sql, but at your current scale, an in-memory solution should be fine.

A: If you can have duplicates and you want to iterate over your collection, you should use NSArray.
Choose your data structure thinking how are you going to use and access the information stored in it.


text:
Q: How Can My Win32 App Steal Focus From My UWP App? I've tried the following code:
[DllImport("user32.dll")]
private static extern int ShowWindow(IntPtr hwnd, int nCmdShow);

[DllImport("user32.dll")]
private static extern bool SetForegroundWindow(IntPtr hWnd);

[DllImport("user32.dll")]
private static extern IntPtr SetFocus(IntPtr hwnd);

void TakeFocus()
{
    var process = Process.GetProcessesByName("myProcess").FirstOrDefault();
    if (process != null)
    {
        // Tried each of the following:
        ShowWindow(process.MainWindowHandle, 1);
        ShowWindow(process.MainWindowHandle, 3);
        ShowWindow(process.MainWindowHandle, 9);
        ShowWindow(process.MainWindowHandle, 5);
        SetFocus(process.MainWindowHandle);
        SetForegroundWindow(process.MainWindowHandle);
    }
}

I have a WPF companion app which runs in the background while a UWP app is running in the foreground.  They communicate via WebSocket.  I'm trying to create a method in the WPF app so it (or any other window) can steal focus from an activated UWP app, sending it into suspended state.  Nothing I try seems to work, and there's no way to programatically make a UWP app suspend itself AFAIK without using the Launcher class (not an option for me, unless there's a way to call it without actually launching something-I haven't been able to do this). Normally I would assume it can't be done but I've seen programs that do it.  Steam Big Picture Mode, for example, will steal focus from a UWP app when it is launched from a background process.

A: The supported way of suspending a UWP programmatically is available in the Spring 2018 update for Windows 10. It's already available in Insider builds/SDKs. This is the API to call:
https://learn.microsoft.com/en-us/uwp/api/windows.system.appresourcegroupinfo.startsuspendasync#Windows_System_AppResourceGroupInfo_StartSuspendAsync
IList<AppDiagnosticInfo> infos = await AppDiagnosticInfo.RequestInfoForAppAsync();
IList<AppResourceGroupInfo> resourceInfos = infos[0].GetResourceGroups();
await resourceInfos[0].StartSuspendAsync();

Here is a trivial sample app:
https://1drv.ms/u/s!AovTwKUMywTNoYQ3PrmBfZIGXmbULA


text:
Q: Inconsistent behaviours between VS2010 and GCC4.8.1 when preallocating a 2D vector? I normally use the following declaration to preallocate a 2d vector, and it works fine in both VS2010 and GCC4.8.1
vector<vector<int> > k(2, vector<int>(3, 0));

However, I have recently noticed that another simpler statement:
vector<vector<int> > k(2, 3);

also achieves the same effect (i.e. defines a 2d vector k where k.size() == 2 and k[i].size() == 3 for i = 0 to 1) in VS2010. However, when I try this declaration with GCC4.8.1 (through Dev C++, with ISO C++ 11 support switched on), the compiler reports an error:

62    31  D:\Dev-Cpp\Projects\TestProg\main.cpp [Error] no matching function for call to 'std::vector < std::vector < int > >::vector(int, int)'

If I switch the 'Language Standard' flag from 'ISO C++ 11' to 'ISO C++', then it reports an error in stl_vector.h:

1166  59  d:\orwelldevcpp\mingw64\lib\gcc\x86_64-w64-mingw32\4.8.1\include\c++\bits\stl_vector.h  [Error]
  no matching function for call to 'std::vector < std::vector < int > > ::_M_fill_initialize(std::vector < std::vector < int > > ::size_type, int&)'

I also traced the execution of this confusing constructor call in VS2010, and apparently VS matches it to the 'range' constructor:
template<class _Iter>
    vector(_Iter _First, _Iter _Last)
    : _Mybase()
    {   // construct from [_First, _Last)
    _Construct(_First, _Last, _Iter_cat(_First));
    }

The function call that throws an error in GCC without C++11 standard (_M_fill_initialize) is also called by the range constructor. So I think it means GCC also matches the constructor call to the range constructor, but somehow cannot finish the initialization.

So I am very confused at this point:
1: Why is this function matched to the range constructor?
2: Why does C++ 11 seem to disallow such a match?
3: Why does VS accept this usage while GCC fails on it, even without the C++11 flag?

Thank you very much for your help!

A: This is an MSVC bug that has been fixed in VS2012.
In the statement
vector<vector<int> > k(2, 3);

you're attempting to construct a 2 element vector, and construct a vector::value_type (i.e. vector<int>) instance with the argument 3. However, the vector<int> constructor that takes a count is explicit, which causes the construction to fail.
C++03 states that if the constructor
template< class InputIt >
vector(InputIt first, InputIt last, const Allocator& alloc = Allocator());

is called with integral types for InputIt, the call should behave as if the constructor that takes a count and value_type instance was called.
From the C++03 standard 23.1.1/9 [lib.sequence.reqmts]

For every sequence defined in this clause and in clause 21:
  — the constructor
 template <class InputIterator>
 X(InputIterator f, InputIterator l, const Allocator& a = Allocator())

shall have the same effect as:
 X(static_cast<typename X::size_type>(f),
   static_cast<typename X::value_type>(l), a)

if InputIterator is an integral type.

This proves that the VS2010 behavior is a bug.

The gcc error messages differ between the C++03 and C++11 standards because C++11 changed the wording of the requirement quoted above.
From N3337 §23.2.3/14 [sequence.reqmts]

For every sequence container defined in this Clause and in Clause 21:
  — If the constructor
 template <class InputIterator>
 X(InputIterator first, InputIterator last,
   const allocator_type& alloc = allocator_type())

is called with a type InputIterator that does not qualify as an input iterator, then the constructor shall not participate in overload resolution.

C++11 doesn't require that the constructor taking count and value be matched, hence the gcc error message states that, given the two integral arguments, no matching constructor was found (because the second argument cannot be implicitly converted to vector<int>).


text:
Q: R Generate counts from vector with 0 for values that do not exist My data is of the following form in R
data<-list(list(Name= "Value1",corresponding_set=c(1,2,3)), list(Name="AnotherKey",corresponding_set=c(4,5,3,4)))

What I am trying to obtain is data frame of format
            1 2 3 4 5
Key         1 1 1 0 0
AnotherKey  0 0 1 2 1

I tried the following:
myfunc<-function(x){
  currValue<-x$corresponding_Set
  for(i in 1:5){
    print(c(i,sum(currValue==i))
  }
 }
sapply(data,myfunc)

The above code does print the value I need but in the following format
1 1
2 1
3 1
4 0
5 1
1 0
2 0
3 0
4 2
5 1

My questions is

*

*For the type of data used is the structure of "data" appropriate? if not how should it be designed. Currently this data is static and I would like to keep it this way for now

*I am not able to form an idea how to convert the vectors that I print to a grid format (data frame or matrix)

Any help appreciated!

A: You can get the result you're looking for by converting the nested lists into data.frames, binding them together and then calling table.
data <- list(list(Name = "Value1",
                  corresponding_set = c(1, 2, 3)),
             list(Name = "AnotherKey",
                  corresponding_set = c(4, 5, 3, 4)))

# Convert each list element to a data.frame
dfs <- lapply(data, as.data.frame)
dfs
# [[1]]
#     Name corresponding_set
# 1 Value1                 1
# 2 Value1                 2
# 3 Value1                 3
#
# [[2]]
#         Name corresponding_set
# 1 AnotherKey                 4
# 2 AnotherKey                 5
# 3 AnotherKey                 3
# 4 AnotherKey                 4

# bind the two data.frames together
df <- do.call(rbind, dfs)
df
#         Name corresponding_set
# 1     Value1                 1
# 2     Value1                 2
# 3     Value1                 3
# 4 AnotherKey                 4
# 5 AnotherKey                 5
# 6 AnotherKey                 3
# 7 AnotherKey                 4

# build a table
table(df)
#             corresponding_set
# Name         1 2 3 4 5
#   AnotherKey 0 0 1 2 1
#   Value1     1 1 1 0 0


text:
Q: Failed to convert property value of 'java.util.Arraylist' to required type 'java.util.List' I am getting this error for the definition below.
<property name="configurationFiles">
   <list>
      <value>classpath:${common.dir}/abc.xml</value>
   </list>
</property>

Later on it goes to state that abc.xml cannot be reolved to absolute file path because it does not reside in the file system.
What I am not getting is that the file is present and the common.dir also resolves to the correct directory name. What may be the issue?


text:
Q: Issues while deserializing exception/throwable using Jackson in Java I am facing issues while deserializing Exception and Throwable instances using Jackson (version 2.2.1). Consider the following snippet:
public static void main(String[] args) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure(SerializationFeature.INDENT_OUTPUT, true);
    objectMapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    objectMapper.enableDefaultTyping(DefaultTyping.NON_FINAL, As.PROPERTY);

    try {
        Integer.parseInt("String");
    }
    catch (NumberFormatException e) {
        RuntimeException runtimeException = new RuntimeException(e);
        String serializedException = objectMapper.writeValueAsString(runtimeException);
        System.out.println(serializedException);
        Throwable throwable = objectMapper.readValue(serializedException, Throwable.class);
        throwable.printStackTrace();
    }
}

The output of System.out.println in the catch block is:
{
  "@class" : "java.lang.RuntimeException",
  "detailMessage" : "java.lang.NumberFormatException: For input string: \"String\"",
  "cause" : {
    "@class" : "java.lang.NumberFormatException",
    "detailMessage" : "For input string: \"String\"",
    "cause" : null,
    "stackTrace" : [ {
      "declaringClass" : "java.lang.NumberFormatException",
      "methodName" : "forInputString",
      "fileName" : "NumberFormatException.java",
      "lineNumber" : 65
    }, {
      "declaringClass" : "java.lang.Integer",
      "methodName" : "parseInt",
      "fileName" : "Integer.java",
      "lineNumber" : 492
    }, {
      "declaringClass" : "java.lang.Integer",
      "methodName" : "parseInt",
      "fileName" : "Integer.java",
      "lineNumber" : 527
    }, {
      "declaringClass" : "test.jackson.JacksonTest",
      "methodName" : "main",
      "fileName" : "JacksonTest.java",
      "lineNumber" : 26
    } ],
    "suppressedExceptions" : [ "java.util.ArrayList", [ ] ]
  },
  "stackTrace" : [ {
    "declaringClass" : "test.jackson.JacksonTest",
    "methodName" : "main",
    "fileName" : "JacksonTest.java",
    "lineNumber" : 29
  } ],
  "suppressedExceptions" : [ "java.util.ArrayList", [ ] ]
}

which seems fine. But when I attempt to deserialize this using objectMapper.readValue(), I get the following exception:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "declaringClass" (class java.lang.StackTraceElement), not marked as ignorable
 at [Source: java.io.StringReader@3c5ebd39; line: 9, column: 27] (through reference chain: java.lang.StackTraceElement["declaringClass"])
    at com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException.from(UnrecognizedPropertyException.java:79)
    at com.fasterxml.jackson.databind.DeserializationContext.reportUnknownProperty(DeserializationContext.java:555)
    at com.fasterxml.jackson.databind.deser.std.StdDeserializer.handleUnknownProperty(StdDeserializer.java:708)
    at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer.deserialize(JdkDeserializers.java:414)
    at com.fasterxml.jackson.databind.deser.std.JdkDeserializers$StackTraceElementDeserializer.deserialize(JdkDeserializers.java:380)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:151)
...

I then tried using mix-in annotations, to ignore declaringClass in java.lang.StackTraceElement, but now the deserialized Exception doesn't contain the declaring class in its stack trace:
java.lang.RuntimeException: java.lang.NumberFormatException: For input string: "String"
    at .main(JacksonTest.java:33)
Caused by: java.lang.NumberFormatException: For input string: "String"
    at .forInputString(NumberFormatException.java:65)
    at .parseInt(Integer.java:492)
    at .parseInt(Integer.java:527)
    at .main(JacksonTest.java:30)

Am I missing anything? Any help is greatly appreciated.

A: There seems to be a Jackson JIRA entry for this here. Jackson doesn't seem to be able to handle the declaringClass in java.lang.StackTraceElement, since the getter corresponding to this field is called getClassName().
I fixed this issue by using a custom wrapper around StackTraceElement as suggested in the JIRA entry mentioned above. The custom wrapper (CustomStackTraceElement) will have the fields declaringClass, methodName, fileName, and lineNumber and the corresponding getters and setters in it. I modified the catch block (mentioned in the question) to be as follows:
catch (NumberFormatException e) {
    RuntimeException runtimeException = new RuntimeException(e);
    e.printStackTrace();
    String serializedException = objectMapper.writeValueAsString(runtimeException);
    System.out.println(serializedException);

    String serializedStackTrace = objectMapper.writeValueAsString(transformStackTrace(runtimeException));
    String serializedStackTraceForCause = objectMapper.writeValueAsString(transformStackTrace(runtimeException.getCause()));

    Throwable throwable = objectMapper.readValue(serializedException, Throwable.class);
    List<CustomStackTraceElement> customStackTraceElementList = objectMapper.readValue(serializedStackTrace, List.class);
    List<CustomStackTraceElement> customStackTraceElementListForCause = objectMapper.readValue(serializedStackTraceForCause, List.class);

    throwable.setStackTrace(reverseTransformStackTrace(customStackTraceElementList));
    throwable.getCause().setStackTrace(reverseTransformStackTrace(customStackTraceElementListForCause));
    throwable.printStackTrace();
}

The StackTraceElement[] will be converted into List<CustomStackTraceElement> by the following method during serialization:
private static List<CustomStackTraceElement> transformStackTrace(Throwable throwable)
{
    List<CustomStackTraceElement> list = new ArrayList<>();
    for (StackTraceElement stackTraceElement : throwable.getStackTrace()) {
        CustomStackTraceElement customStackTraceElement =
            new CustomStackTraceElement(stackTraceElement.getClassName(),
                                        stackTraceElement.getMethodName(),
                                        stackTraceElement.getFileName(),
                                        stackTraceElement.getLineNumber());

        list.add(customStackTraceElement);
    }

    return list;
}

... and the reverse transformation will be done during deserialization:
private static StackTraceElement[] reverseTransformStackTrace(List<CustomStackTraceElement> customStackTraceElementList)
{
    StackTraceElement[] stackTraceElementArray = new StackTraceElement[customStackTraceElementList.size()];
    for (int i = 0; i < customStackTraceElementList.size(); i++) {
        CustomStackTraceElement customStackTraceElement = customStackTraceElementList.get(i);
        StackTraceElement stackTraceElement =
            new StackTraceElement(customStackTraceElement.getDeclaringClass(),
                                  customStackTraceElement.getMethodName(),
                                  customStackTraceElement.getFileName(),
                                  customStackTraceElement.getLineNumber());

        stackTraceElementArray[i] = stackTraceElement;
    }

    return stackTraceElementArray;
}

Now, after deserialization, the Throwable object has the expected stack trace in it.

A: It seems that the output you get in version 2.2.1 is not the same as I get with version 2.2.0 (which according to the website is the latest 2.x version). Besides the latest available 2.x version on the Maven Repository is 2.2.2. So I would try to either downgrade it to 2.2.0 or to upgrade it to 2.2.2. If any of the changes brings you the expected result, I would go further with that version and open a BUG in Jackson's JIRA.
And of course don't forget
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

from Michael's answer.

A: Add this:
objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

And make out of the deserialized exception the same way, as for the first time:
System.out.println( objectMapper.writeValueAsString( throwable ) );

I used the following code:
public static void main( String[] args ) throws IOException
{
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.configure( SerializationFeature.INDENT_OUTPUT, true );
    objectMapper.configure( DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    objectMapper.setVisibility( PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY );
    objectMapper.enableDefaultTyping( ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY );

    try
    {
        Integer.parseInt( "String" );
    }
    catch( NumberFormatException e )
    {
        Throwable throwable = objectMapper.readValue( objectMapper.writeValueAsString( e ), Throwable.class );
        System.out.println( objectMapper.writeValueAsString( throwable ) );
    }
}

Added this jars: jackson-annotations-2.2.0.jar, jackson-core-2.2.0.jar and jackson-databind-2.2.0.jar.
After execution, the following is printed:
{
"@class" : "java.lang.NumberFormatException",
"detailMessage" : "For input string: \"String\"",
"cause" : null,
"stackTrace" : [ {
    "declaringClass" : "java.lang.NumberFormatException",
    "methodName" : "forInputString",
    "fileName" : "NumberFormatException.java",
    "lineNumber" : 48,
    "className" : "java.lang.NumberFormatException",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.Integer",
    "methodName" : "parseInt",
    "fileName" : "Integer.java",
    "lineNumber" : 449,
    "className" : "java.lang.Integer",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.Integer",
    "methodName" : "parseInt",
    "fileName" : "Integer.java",
    "lineNumber" : 499,
    "className" : "java.lang.Integer",
    "nativeMethod" : false
}, {
    "declaringClass" : "com.sample.bla.Main",
    "methodName" : "main",
    "fileName" : "Main.java",
    "lineNumber" : 24,
    "className" : "com.sample.bla.Main",
    "nativeMethod" : false
}, {
    "declaringClass" : "sun.reflect.NativeMethodAccessorImpl",
    "methodName" : "invoke0",
    "fileName" : "NativeMethodAccessorImpl.java",
    "lineNumber" : -2,
    "className" : "sun.reflect.NativeMethodAccessorImpl",
    "nativeMethod" : true
}, {
    "declaringClass" : "sun.reflect.NativeMethodAccessorImpl",
    "methodName" : "invoke",
    "fileName" : "NativeMethodAccessorImpl.java",
    "lineNumber" : 39,
    "className" : "sun.reflect.NativeMethodAccessorImpl",
    "nativeMethod" : false
}, {
    "declaringClass" : "sun.reflect.DelegatingMethodAccessorImpl",
    "methodName" : "invoke",
    "fileName" : "DelegatingMethodAccessorImpl.java",
    "lineNumber" : 25,
    "className" : "sun.reflect.DelegatingMethodAccessorImpl",
    "nativeMethod" : false
}, {
    "declaringClass" : "java.lang.reflect.Method",
    "methodName" : "invoke",
    "fileName" : "Method.java",
    "lineNumber" : 597,
    "className" : "java.lang.reflect.Method",
    "nativeMethod" : false
}, {
    "declaringClass" : "com.intellij.rt.execution.application.AppMain",
    "methodName" : "main",
    "fileName" : "AppMain.java",
    "lineNumber" : 120,
    "className" : "com.intellij.rt.execution.application.AppMain",
    "nativeMethod" : false
    } ],
    "message" : "For input string: \"String\"",
    "localizedMessage" : "For input string: \"String\""
}

A: I've had a similar issue. I'm using this code now, and it allows me to serialize and deserialize exceptions with proper types (i.e. a RuntimeException will be a RuntimeException again :)):
public static ObjectMapper createObjectMapper() {
    ObjectMapper mapper = new ObjectMapper(null, null, new DefaultDeserializationContext.Impl(
            new BeanDeserializerFactory(new DeserializerFactoryConfig()) {
                private static final long serialVersionUID = 1L;

                @Override
                public JsonDeserializer<Object> buildThrowableDeserializer(
                        DeserializationContext ctxt, JavaType type, BeanDescription beanDesc)
                        throws JsonMappingException {
                    return super.buildBeanDeserializer(ctxt, type, beanDesc);
                }

            }));

    mapper.setVisibility(PropertyAccessor.ALL, Visibility.NONE);
    mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY);
    mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

    mapper.addMixIn(Throwable.class, ThrowableMixin.class);
    mapper.addMixIn(StackTraceElement.class, StackTraceElementMixin.class);

    return mapper;
}

@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "@class")
@JsonAutoDetect(fieldVisibility = Visibility.ANY)
@JsonIgnoreProperties({ "message", "localizedMessage", "suppressed" })
abstract class ThrowableMixin {

    @JsonIdentityInfo(generator = ObjectIdGenerators.IntSequenceGenerator.class, property = "$id")
    private Throwable cause;
}

abstract class StackTraceElementMixin {

    @JsonProperty("className")
    private String declaringClass;

}

I'm manipulating the BeanDeserializerFactory to make buildThrowableDeserializer not treat Throwable any special but just like any other Object. Then using Mixins to define the "special" handling of Throwable and StackTraceElement to my liking.

A: Try using polymorphism so that jackson deserializer knows what kind of Throwable to create:
/**
 * Jackson module to serialize / deserialize Throwable
 */
public class ThrowableModule extends SimpleModule {
  public ThrowableModule() {
    super("Throwable", new Version(1, 0, 0, null, null, null));
  }

  @Override
  public void setupModule(SetupContext context) {
    context.setMixInAnnotations(Throwable.class, ThrowableAnnotations.class);
  }

  /**
   * Add annotation to Throwable so that the class name is serialized with the instance data.
   */
  @JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY, property = "class")
  static abstract class ThrowableAnnotations {
  }
}

A: Is it so necessary to use json serialization? Looks liks there are some bugs with throwables. Why not use system api:
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(  );
ObjectOutputStream objectOutputStream = new ObjectOutputStream( byteArrayOutputStream );
objectOutputStream.writeObject( e );

ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream( byteArrayOutputStream.toByteArray() );
ObjectInputStream objectInputStream = new ObjectInputStream( byteArrayInputStream );
Throwable t = (Throwable) objectInputStream.readObject();


text:
Q: Do there exist polynomials $f,g$ such that $\mathbb{C}[a,b,c]\le\mathbb{C}[f,g]$ for $a,b,c$ given polynomials? I want to prove something bigger than the problem in the title and I want to create a lemma that is useful for the solution of the problem. But I am unable to prove (or give a counterexample) the "lemma":

Suppose that $a,b,c$ are given polynomials in $\mathbb{C}[x]$ such that $\mathbb{C}[a,b,c] \subsetneq \mathbb{C}[x]$. There exist polynomials $f,g \in \mathbb{C}[x]$ such that $\mathbb{C}[a,b,c]\le\mathbb{C}[f,g]$ where $\mathbb{C}[f,g]\subsetneq \mathbb{C}[x]$? (The symbol $\le$ obviously means subring.)

Does anyone have any idea to prove this if it is true? Or give a counterexample if it is false?

A: Consider the set of proper sub algebras $\mathcal{O}$ of $\mathbf{C}[x]$ which contain $a$, $b$, and $c$. Since the codimension of $\mathbf{C}[a, b, c]$ in $\mathbf{C}[x]$ is finite, we can choose $\mathcal{O}$ a proper sub algebra maximal with respect to inclusion.
Claim: any maximal proper sub algebra $\mathcal{O}$ is isomorphic as a $\mathbf{C}$-algebra to either $\{f \in \mathbf{C}[x] \mid f(0) = f(1)\}$ or to $\mathbf{C}[x^2, x^3]$.
You can probably prove this claim with elementary methods. (Hint: show that the codimension of $\mathcal{O}$ in $\mathbf{C}[x]$ is $1$ and then analyze what this means).
However, I would prove this by looking at the singularities of $\text{Spec}(\mathcal{O})$. If there are two singular points, then we can normalize one of them and we see that $\mathcal{O}$ is not maximal. If the $\delta$-invariant of the singularity is $> 1$, then we can add a local function without smoothing $\text{Spec}(\mathcal{O})$. Finally, if $C$ is an affine algebraic curve with a unique singular point of $\delta$-invariant $1$ and normalization equal to the affine line $\mathbf{A}^1 = \text{Spec}(\mathbf{C}[x])$, then it is isomorphic to the spectrum of one of the two rings in the claim.
This answers the question positively as the two example algebras can be generated by two elements as $\mathbf{C}$-algebras.


text:
Q: Localstack AWS endpoint in application I would like to run the functional tests for my application which tries to publish a message to AWS SNS. I tried LocalStack and found that it does everything I need to mock and publish messages locally. But my application uses amazon sdk client for java and when I run it locally it still tries to post requests to amazon region instead of the LocalStack
What is the configuration required to make sure that the application interacts with the local stack instead of the AWS URL? Can we specify the endpoint URL in AWS config? I found this to be a open issue in AWS CLI https://github.com/aws/aws-cli/issues/1270
Is there any workaround that anyone has implemented for this?

A: To use your localstack, you have to set your EndpointConfiguration.
AmazonSNS amazonSNS = AmazonSNSClientBuilder.standard()
  .withEndpointConfiguration(new EndpointConfiguration("http://localhost:4575", "eu-west-1"))
  .build();

You should also use localstack/localstack instead of atlassian/localstack (no longer actively maintained).

A: If you're using JUnit 5 for the tests, let me recommend you JUnit 5 extensions for AWS, a few JUnit 5 extensions that could be useful for testing AWS-related code. These extensions can be used to inject clients for AWS service clients provided by tools like localstack (or the real ones). Both AWS Java SDK v 2.x and v 1.x are supported:
public static class Endpoint implements AWSEndpoint {
    @Override
    public String url() { return "http://localhost:4575"; }

    @Override
    public String region() { return "us-east-1"; }

    @Override
    public String accessKey() { return ""; }

    @Override
    public String secretKey() { return ""; }
}

@ExtendWith(SNS.class)
class AmazonDynamoDBInjectionTest {
    @AWSClient(endpoint = Endpoint.class)
    private AmazonSNS client;

    @Test
    void test() throws Exception {
        Assertions.assertNotNull(client);

        …
    }
}


text:
Q: expectation of geometric distribution question Suppose there are 21 cards, 3 of them are printed with A,B and C respectively, and others are printed with numbers. Now I want to draw the 3 letter cards, what is the expectation of it?
I think it should be a geometric distribution question, with $P=1/7$ at the beginning, but what happens after drawing one of the 3 cards? How to calculate the expectation of it?

A: It can be easily tackled using linearity of expectation, which operates even when the random variables are not independent
Call the alphabet cards $A$ and the number cards $N$
Let $X_i$ be an indicator r.v. that is equal to $1$ if the $i_{th} N$ card is drawn before all the  $A$ cards are drawn, and $0$ otherwise.
Consider $(3+1)$ items including the $3\,A$  cards and the $i_{th}\,N$  card.
Since all $N$ cards have equal chance of thus being placed,
$P(X_i) = \frac{3}{4}$
Now the expectation of an indicator variable is just the probability of the event it indicates, thus $\Bbb E[X_i] = \frac{3}{4}$
and by linearity of expectation,
$\Bbb E[X] = \Bbb E[X_1] +\Bbb E[X_2] + ... +\Bbb E[X_{18}] = 18\times \frac3 4$
Finally, as this only represents the expected number of picks of number cards before all alphabet cards are drawn, the expected number of picks to get $A,B,C$ out $= 3 + \frac{54}{4 } = 16 \frac12$
_______________________________-
Added
An intuitive way to understand the above is that on an average (which is what expectation is about), $A,B,C$ divide the range into $4$ equal parts of $\frac{18}4$ numbers
$ \boxed{\frac{18}4\; numbers}\,A\,\boxed{\frac{18}4\; numbers}\,B\,\boxed{\frac{18}4\; numbers}\,C\,\boxed{\frac{18}4\; numbers}$

A: Hint (almost solution).
If the probibility is changing at some step then it's not  geometric distribution. It's more convenient to use another way.
Let's number the cards so that cards A, B and C are numbered 1, 2, 3, and the rest of the cards are numbered 4 to 21. Suppose we draw all 21 cards in a row and get a sequence of numbers $(i_1, \ldots, i_n)$ where $n=21$.
Denote by $\tau$ the first moment when we got all $3$ letters.
$$\mathbf{P} (\tau \le k) = \mathbf{P}( (i_1, \ldots, i_n) | \{1,2,3\} \subset \{i_1, \ldots, i_k\})
$$
It not very hard to find the number of $(i_1, \ldots, i_n)$ such that $\{1,2,3\} \subset \{i_1, \ldots, i_k\}$ hence we may find $\mathbf{P} (\tau \le k) $.
Further, $$\mathbf{E} \tau = \sum_{k=1}^{n} k \mathbf{P} (\tau = k) =  \sum_{k=1}^{n} \mathbf{P} (\tau \ge k) =\sum_{k=1}^{n} ( 1 - \mathbf{P} (\tau < k)) =\sum_{j=0}^{n-1} ( 1 - \mathbf{P} (\tau \le j)).$$
Addition (hint): the number of $(i_1, \ldots, i_n)$ such that $\{1,2,3\} \subset \{i_1, \ldots, i_k\}$ can be found if we will take numbers $1,2,3$ and some other $k-3$ numbers from $\{1, 2, \ldots, n\}$ and put these $k$ numbers in some order.


text:
Q: Node js if condition is not working properly I want to initialize global variable with body of json object. But in my code if is not being executed instead of if, else part of code executes, if console.log(typeof ticker) I get undefined. What appears to be the problem.
var ticker;
request({
    method: 'POST',
    url: 'xyz'
}, (err, res, body) => {

    if (typeof ticker === undefined) {
        ticker = body;
    } else {

        console.log(ticker)
    }
})

A: Your condition will always evaluate to false. typeof operator returns a string. So your if condition should be:
typeof ticker === 'undefined'

or
 ticker === undefined

A: Marco's answer above is the correct answer. What I'm addressing is the following statement and how you can verify it for yourself:

if condition is not working properly

You can use the debugger to understand your program. Since you're using node, you can verify this right from the command line.

*

*Place a debugger statement above the line of code you're interested in. This sets a breakpoint.

*run node inspect <filename>

*A REPL opens up in the command shell, starting from line 1 of your file. To arrive at your breakpoint, simply type c or cont into the command line

You're now here:
> 3 debugger
  4 if (typeof ticker === undefined) {
  5 ticker = body
debug> _

*You can now run expressions right in the REPL to see how node will evaluate them at runtime:
debug> typeof ticker
'undefined'               // aha, there's our programming error
 debug> typeof ticker === undefined
 false
 debug> typeof ticker === 'undefined'  // it works
 true

*To further verify the flow of your program, enternext in the REPL to see line-by-line where the program flows.
Optionally, you can utilize chrome's interface to debug:

*

*run node --inspect-brk <filename>

*open chrome to chrome://inspect

*click Open dedicated devTools for node
Chrome's interface allows you to highlight or hover over variables and expressions to see their value.


text:
Q: using apache tika for scanning documents on servers using sftp I have a tika code in a server. I want to create an SFTP session with another server with files and run Apache tika on that server. I am using python as back end. Will this work ? is my approach correct ?
Thanks

A: So, what I was planning to do was not ideal . .
Apache Tika requires to scan physical files to fetch metadata. I made a bridge and started from sessions pulling files to the server Tika code was hosted.


text:
Q: Setting the color of the TabItem header's foreground when the tab is clicked and not clicked I have this TabControl in my application:
<TabControl Width="100" Height="100">
    <TabControl.Resources>
        <Style TargetType="{x:Type TabItem}" x:Key="TabItemStyle">
            <Setter Property="VerticalContentAlignment" Value="Stretch"/>
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TabItem}">
                        <Border x:Name="Chrome"
                                BorderBrush="Blue"
                                Background="Transparent">
                            <ContentPresenter ContentSource="Header"
                                              Margin="0,0,0,3"
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
                        </Border>
                        <ControlTemplate.Triggers>
                            <Trigger Property="Selector.IsSelected" Value="True">
                                <Setter TargetName="Chrome" Property="BorderThickness" Value="0,0,0,3"/>
                            </Trigger>
                            <Trigger Property="Selector.IsSelected" Value="False">
                                <Setter TargetName="Chrome" Property="BorderThickness" Value="0,0,0,0"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </TabControl.Resources>

    <TabItem Style="{DynamicResource TabItemStyle}">
        <TabItem.Header>
             <Label Content="Tab 1" />
        </TabItem.Header>
    </TabItem>

    <TabItem Style="{DynamicResource TabItemStyle}">
        <TabItem.Header>
             <Label Content="Tab 2" />
        </TabItem.Header>
    </TabItem>
</TabControl>

When I click a tab in the TabControl, a blue line is displayed below the tab header. This is beside the point, but I'm sure the style I have will be useful.
In the tab headers there are labels.
I would like to change the foreground of labels according to:

*

*When the tab is clicked, the label's foreground should be Red.

*When the tab is not clicked, the label's foreground should be Gray.

I assume I can use the trigger I already have in the ControlTemplate to determine when the tab was clicked or not.
But I don't know what I need to do to set the labels foreground accordingly in the style.

A: You could create a DataTemplate as HeaderTemplate and use a DataTrigger that sets the Foreground color of the Labels depending on the selection state of the containing TabItems, which is bound using a RelativeSource. The separate header template also reduces the redundancy in your TabItems, because you do not have to define the Label in each time again.
<TabControl Width="100"
            Height="100">
   <TabControl.Resources>
      <Style TargetType="{x:Type TabItem}"
             x:Key="TabItemStyle">
         <Setter Property="VerticalContentAlignment"
                 Value="Stretch" />
         <Setter Property="HorizontalContentAlignment"
                 Value="Stretch" />
         <Setter Property="HeaderTemplate">
            <Setter.Value>
               <DataTemplate>
                  <Label x:Name="TabItemHeaderLabel" Foreground="Gray" Content="{Binding}" />
                  <DataTemplate.Triggers>
                     <DataTrigger Binding="{Binding IsSelected, RelativeSource={RelativeSource AncestorType={x:Type TabItem}}}" Value="True">
                        <Setter TargetName="TabItemHeaderLabel" Property="Foreground" Value="Red"/>
                     </DataTrigger>
                  </DataTemplate.Triggers>
               </DataTemplate>
            </Setter.Value>
         </Setter>
         <Setter Property="Template">
            <Setter.Value>
               <ControlTemplate TargetType="{x:Type TabItem}">
                  <Border x:Name="Chrome"
                          BorderBrush="Blue"
                          Background="Transparent">
                     <ContentPresenter ContentSource="Header"
                                       Margin="0,0,0,3"
                                       HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                       VerticalAlignment="{TemplateBinding VerticalContentAlignment}" />
                  </Border>
                  <ControlTemplate.Triggers>
                     <Trigger Property="Selector.IsSelected"
                              Value="True">
                        <Setter TargetName="Chrome"
                                Property="BorderThickness"
                                Value="0,0,0,3" />
                     </Trigger>
                     <Trigger Property="Selector.IsSelected"
                              Value="False">
                        <Setter TargetName="Chrome"
                                Property="BorderThickness"
                                Value="0,0,0,0" />
                     </Trigger>
                  </ControlTemplate.Triggers>
               </ControlTemplate>
            </Setter.Value>
         </Setter>
      </Style>
   </TabControl.Resources>

   <TabItem Style="{DynamicResource TabItemStyle}"
            Header="Tab 1"/>

   <TabItem Style="{DynamicResource TabItemStyle}"
            Header="Tab 2"/>
</TabControl>


text:
Q: Width of container fluid not changing I am creating a table like this(m using bootstrap):
div class="container-fluid" style="margin-top:220px;">

content of results i am setting in javacript file
The problem I a facing is the table width is very less. it has 7 columns, but it appears in the center of the page in very less ares , less width.
How should i change the width of table,
because like this all columns appear very contracted.

A: you write open < triangular ahead of first div and run code.

A: I solved it. It should have been span12, not span 7


text:
Q: Extract substring before = sign using awk Say I have some file with a bunch of lines in the form
someString=someMoreCharacters
anotherString.blah=foo=bar
blah.blah.blah=foo.bar.=foobar

Desired output
someString
anotherString.blah
blah.blah.blah

I want to use awk to extract the substring that starts at the beginning of the line and goes up until, but not including the first equals sign. I want to be able to pipe this output to xargs.

A: In Awk:
awk '{sub(/=.*/, ""); print}' filename

But, I think Rob's solution is easier:
sed 's/=.*//' filename


text:
Q: Apache rewrite relative URL to application I have web application running on localhost and listening on port 5050.
I would like to have this web application under URL with relative path domain.tld/page/app
I tried to use mod_rewrite:
    <Location /page/app>
        RewriteEngine on
        RewriteRule .*$ http://127.0.0.1:5050/$1 [P,QSA,NE]
    </Location>

This rewrites domain.tld/page/app to domain.tld/login which is not a valid URL on my server.
Is it possible to reverse the rewrite?
I can't use ProxyPassReverse because I need to remove relative path from URL when I proxy the request to the application.

A: This is a textbook case with mod_proxy.
ProxyPass         "/page/app/" "http://127.0.0.1:5050/"
ProxyPassReverse  "/page/app/" "http://127.0.0.1:5050/"

Notice that with this syntax you don't use this inside a <Location>.


text:
Q: org.powermock.reflect.exceptions.FieldNotFoundException Good day I've got class with 2 methods: first is public GetLeadRequestsList - I want to test it, and second is private LeadRequestListResponse - used by first method. I mocked second method and called first one. Code of my test is here. When I run testGetLeadRequestsList, I catched
org.powermock.reflect.exceptions.FieldNotFoundException: No static field of type "org.mockito.internal.progress.MockingProgress" could be found in the class hierarchy of org.mockito.Mockito.
at org.powermock.reflect.internal.matcherstrategies.FieldTypeMatcherStrategy.notFound(FieldTypeMatcherStrategy.java:40)
at org.powermock.reflect.internal.WhiteboxImpl.findSingleFieldUsingStrategy(WhiteboxImpl.java:502)
at org.powermock.reflect.internal.WhiteboxImpl.findFieldInHierarchy(WhiteboxImpl.java:455)
at org.powermock.reflect.internal.WhiteboxImpl.getInternalState(WhiteboxImpl.java:576)
at org.powermock.reflect.Whitebox.getInternalState(Whitebox.java:347)
at org.powermock.api.mockito.internal.PowerMockitoCore.getMockingProgress(PowerMockitoCore.java:45)
at org.powermock.api.mockito.internal.PowerMockitoCore.doAnswer(PowerMockitoCore.java:36)
at org.powermock.api.mockito.PowerMockito.doReturn(PowerMockito.java:790)
at ru.sbrf.sbi.ufs.business.rest.api.LeadRequestsControllerImplTest.setUp(LeadRequestsControllerImplTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:86)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:514)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:215)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:589)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:820)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1128)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:782)
at org.testng.TestRunner.run(TestRunner.java:632)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1244)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1169)
at org.testng.TestNG.run(TestNG.java:1064)
at com.intellij.rt.testng.IDEARemoteTestNG.run(IDEARemoteTestNG.java:66)
at com.intellij.rt.testng.RemoteTestNGStarter.main(RemoteTestNGStarter.java:110)

error in testclass is in the String:
doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
import org.codehaus.jackson.map.ObjectMapper;
import org.junit.runner.RunWith;
import org.mockito.*;

import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.core.classloader.annotations.SuppressStaticInitializationFor;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import ru.sbrf.sbi.ufs.poi.vo.ErrorMessage;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestData;
import ru.sbrf.sbi.ufs.poi.vo.LeadRequestListResponse;
import ru.sbrf.sbi.ufs.poi.vo.ResponseStatus;

import java.util.ArrayList;

import static org.powermock.api.mockito.PowerMockito.*;
import static org.testng.Assert.*;

public class LeadRequestsControllerImplTest {

    @Spy
    LeadRequestsControllerImpl mock = new LeadRequestsControllerImpl();

    LeadRequestListResponse leadRequestsResponse;

    @BeforeMethod
    public void setUp() throws Exception {
        leadRequestsResponse = new LeadRequestListResponse();
        leadRequestsResponse.setResponseStatus(new ResponseStatus().withStatusCode(200L));
        ArrayList<LeadRequestData> requests = new ArrayList<>();
        requests.add(LeadRequestData.builder()
                .companyName("НПО Помощь")
                .lastName("Помоги")
                .firstName("Себе")
                .secondName("Сам")
                .build());
        leadRequestsResponse.setRequests(requests);
        doReturn(leadRequestsResponse).when(mock, "LeadRequestListResponse", ArgumentMatchers.anyBoolean());
    }

    @Test
    public void testGetLeadRequestsList() {
        try {
            String result = mock.getLeadRequestsList();
            ObjectMapper mapper = new ObjectMapper();
            String expect = mapper.writeValueAsString(leadRequestsResponse);
            assertEquals(expect, result,"GetLeadRequestsList isn't correct.");
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}

Maybe, anybody know how to check with Error.
Thank's in advance

A: I suppose you use not correct versions of mockito-core and powermock-api-mockito. Because FieldNotFoundException could be if using not compatible versions of these libraries. Please use support versions chart - https://github.com/powermock/powermock/wiki/Mockito#supported-versions
So you need check your versions and correct it.
Also you should do next things:

*

*Add @RunWith(PowerMockRunner.class) and @PrepareForTest(LeadRequestsControllerImpl.class) before LeadRequestsControllerImplTest

*Change from TestNG @BeforeMethod to JUnit annotations (for example  @BeforeClass) because you can't mixed it.


text:
Q: Problem with connecting IPSec IKEv2 from Ubuntu 18.04 There is a computer with Ubuntu 18.04 it is located behind the NAT router and receives the address in the subnet 192.168.1.0/24. For example 192.168.1.11
I connect from this computer to the VPN server using the IPSec IKEv2 protocol but neither systemctl start strongswan nor ipsec start do not raise the connection, I'm can connect in only one way:
sudo charon-cmd --cert ca-cert.pem --host vpn_domain_or_IP --identity your_username

After connecting I get the address from the NAT subnet on the VPN server 10.10.10.0/24 for example 10.10.10.11 VPN works and all traffic goes through the tunnel. But the connection to the local network completely disappears, requests from subnet 192.168.1.0/24 to address 192.168.1.11 and from my computer to any of the subnet addresses 192.168.1.0/24 do not pass
Output ip a:
3: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
    link/ether 18:d6:c7:14:ff:04 brd ff:ff:ff:ff:ff:ff
    inet 192.168.1.11/24 brd 192.168.1.255 scope global dynamic noprefixroute eth0
        valid_lft 562sec preferred_lft 562sec
15: ipsec0: <POINTOPOINT,MULTICAST,NOARP,UP,LOWER_UP> mtu 1400 qdisc fq_codel state UNKNOWN group default qlen 500
    link/none
    inet 10.10.10.11/32 scope global ipsec0
        valid_lft forever preferred_lft forever
    inet6 fe80::5b2:78:42:d7/64 scope link stable-privacy
        valid_lft forever preferred_lft forever

Ping
:~# ping 192.168.1.11
PING 192.168.1.11 (192.168.1.11) 56(84) bytes of data.
64 bytes from 192.168.1.11: icmp_seq=1 ttl=64 time=0.071 ms
64 bytes from 192.168.1.11: icmp_seq=2 ttl=64 time=0.070 ms
64 bytes from 192.168.1.11: icmp_seq=3 ttl=64 time=0.069 ms
64 bytes from 192.168.1.11: icmp_seq=4 ttl=64 time=0.072 ms
64 bytes from 192.168.1.11: icmp_seq=5 ttl=64 time=0.067 ms
^C
--- 192.168.1.11 ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4075ms
rtt min/avg/max/mdev = 0.067/0.069/0.072/0.010 ms

:~# ping 192.168.1.1
PING 192.168.1.1 (192.168.1.1) 56(84) bytes of data.
^C
--- 192.168.1.1 ping statistics ---
6 packets transmitted, 0 received, 100% packet loss, time 5105ms

All configurations are identical to this resource.

A: The referred resource has leftsubnet=0.0.0.0/0 set. That causes the VPN connection to default to route everything through the VPN. So simplest is if You can change that. I also want to do this (so add all public-ranges in that list and omit private ranges, maybe besides a special private range to reach the servers LAN). Otherwise You have to manage Your local routing on connecting client "manually". (If both sides use strongwan it should be possible to narrow it on eighter side without breaking the SA completely, but not certain whether specifying multiple subnets works with IKEv1 between strongswan client and server or whether You would need to define multiple SAs then.)
Regarding "only way to establish connection"... I'm wondering whether that means You really have the example confiuration (ike2-rw in ipsec.conf) and started daemon and it is not working - but the example is working on server. I had problems with the Strongswan on Ubuntu 18.04 server side (the VPN gateway), it was connecting but connection came not up. The client I did not try. But I found the Ubuntu 18.04 package is broken (or was back then, a few monmth ago) and upgraded my Ubuntu. With 19.04 it works like a charm. (What is Your journal for the strongswan service saying and syslog - or better the /var/log/charon.log when You try to bring up the client as per documentation?)


text:
Q: Zend Framework Class Displaying Code I have a Zend Framework application running on a local web server.  I've run into an issue where it displays the code for certain classes.  It looks like the autoloader isn't working.  Whenever it tries to use a class that should have been autoloaded, it crashes saying it can't find the class, and prints the contents of the php file containing the class it was looking for.
Here's my autoloader
protected function _initAutoload()
{
    echo "in autoload";
    // Set up autoload.
    $obj_loader = Zend_Loader_Autoloader::getInstance();
    $obj_loader->setFallbackAutoloader(true);

    $obj_loader->registerNamespace('Gutterbling_');

    return $obj_loader;
}

The class that can't be found is Gutterbling_Acl.  It doesn't say the file can't be found, just the class.

A: Warning : dirty quick answer.
A look in one of my Zend app and I've seen this line just before the return statement (and I don't have the call to setFallbackAutoloader) :
$obj_loader = new Zend_Application_Module_Autoloader(array(
  'namespace' => '',
  'basePath' => APPLICATION_PATH));

Add it and test.

A: Ok... Sorry to waste everyone's time.  The problem was, the remote server has php short tags enabled.  The local server does not.  The files that aren't working start with

Again, sorry about that.  Hopefully this helps someone with the same problem.


text:
Q: Search a string in multiple fields of a table I have a table User which has the fields (id, first_name, middle_name, last_name).
I want to write a query to find a user by his name. The name may be first name, middle name or last name.
$sql = "SELECT * FROM user
        WHERE first_name like '%$name%' OR
              middle_name like '%$name%' OR
              last_name like '%$name%'";

Is it efficient query?
(Leave the security issue for the time being.)

A: Alter table and add composite Fulltext index on First_name,second_name,last_name then use this query
select *
from table_name
where match (`First_name`,`second_name`,`last_name`) against('name')

It's pretty much faster then your query.

A: As soon as you have a LIKE '%something%' in your WHERE clause, you force a table scan.  So yes, it is inefficient, but one or three LIKE statements will make little difference.
The table scan is the big performance hit.
Consider looking at MySQL's Full Text Search capability.  It is designed to answer this type of query much more efficiently.

A: If you need to search for a pattern in more than one fields, and if you have the permission to change table schema, i would suggest implementing FULL-TEXT SEARCH.
Hope it helps :)


text:
Q: WebSocket to Binance: Connection closed error I am trying trying to create a WebSocket and connect to Binance.
public static void main(String[] args){

    WebSocketClient client = new StandardWebSocketClient();

    WebSocketStompClient stompClient = new WebSocketStompClient(client);
    stompClient.setMessageConverter(new MappingJackson2MessageConverter());

    StompSessionHandler sessionHandler = new MyWebSocketHandler();
    stompClient.connect("wss://stream.binance.com:9443/ws", sessionHandler);

    new Scanner(System.in).nextLine(); // Don't close immediately.

}

private static class MyWebSocketHandler implements StompSessionHandler {

    @Override
    public void afterConnected(StompSession stompSession, StompHeaders stompHeaders) {
        System.out.println("connected");
        stompSession.send(stompHeaders, "{\"method\": \"SUBSCRIBE\", \"params\":[\"btcusdt@trade\"], \"id\": 1}");
    }

    @Override
    public void handleException(StompSession stompSession, StompCommand stompCommand, StompHeaders stompHeaders, byte[] bytes, Throwable throwable) {
        throwable.printStackTrace();
    }

    @Override
    public void handleTransportError(StompSession stompSession, Throwable throwable) {
        throwable.printStackTrace();
    }

    @Override
    public Type getPayloadType(StompHeaders stompHeaders) {
        return null;
    }

    @Override
    public void handleFrame(StompHeaders stompHeaders, Object o) {
        System.out.println(o);
    }
}

When I run this code, I get Connection closed:
org.springframework.messaging.simp.stomp.ConnectionLostException: Connection closed
    at org.springframework.messaging.simp.stomp.DefaultStompSession.afterConnectionClosed(DefaultStompSession.java:523)
    at org.springframework.web.socket.messaging.WebSocketStompClient$WebSocketTcpConnectionHandlerAdapter.afterConnectionClosed(WebSocketStompClient.java:352)
    at org.springframework.web.socket.handler.WebSocketHandlerDecorator.afterConnectionClosed(WebSocketHandlerDecorator.java:85)
    at org.springframework.web.socket.handler.LoggingWebSocketHandlerDecorator.afterConnectionClosed(LoggingWebSocketHandlerDecorator.java:72)
    at org.springframework.web.socket.adapter.standard.StandardWebSocketHandlerAdapter.onClose(StandardWebSocketHandlerAdapter.java:145)
    at org.glassfish.tyrus.core.TyrusEndpointWrapper.onClose(TyrusEndpointWrapper.java:1190)
    at org.glassfish.tyrus.core.TyrusWebSocket.onClose(TyrusWebSocket.java:126)
    at org.glassfish.tyrus.core.frame.CloseFrame.respond(CloseFrame.java:131)
    at org.glassfish.tyrus.core.ProtocolHandler.process(ProtocolHandler.java:658)
    at org.glassfish.tyrus.client.TyrusClientEngine$TyrusReadHandler.handle(TyrusClientEngine.java:668)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter$ProcessTask.execute(GrizzlyClientFilter.java:472)
    at org.glassfish.tyrus.container.grizzly.client.TaskProcessor.processTask(TaskProcessor.java:114)
    at org.glassfish.tyrus.container.grizzly.client.TaskProcessor.processTask(TaskProcessor.java:91)
    at org.glassfish.tyrus.container.grizzly.client.GrizzlyClientFilter.handleRead(GrizzlyClientFilter.java:270)
    at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:284)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:201)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:133)
    at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:112)
    at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
    at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:561)
    at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:112)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:117)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:56)
    at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:137)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:565)
    at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:545)
    at java.base/java.lang.Thread.run(Thread.java:844)

I also observed in logger this message: closed with CloseStatus[code=1008, reason=Invalid request]
My imports are these:
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-websocket</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-messaging</artifactId>
    <version>5.2.2.RELEASE</version>
</dependency>
<dependency>
    <groupId>org.glassfish.tyrus.bundles</groupId>
    <artifactId>tyrus-standalone-client</artifactId>
    <version>1.9</version>
</dependency>

How to fix it?

A: You have missed a step. You have to request a listen-key first, which is then used to register/connect to the websocket.
https://binance-docs.github.io/apidocs/spot/en/#listen-key-spot
POST /api/v3/userDataStream


text:
Q: Invalid argument JavaScript exception in IE 8 issue with ExtJS in moveItem function Below is a code snippet from the file ext-all-dev.js.  The JavaScript exception below only happens in Internet Explorer 8 (IE).  I have not tried any other versions of Internet Explorer.  When I place a break-point on this line of code when running my application, the browser freezes in IE.  So I don't have a way to troubleshoot this in IE.  Is there an easy way to tell what code might be calling this line?  I'm getting a sense that some drag and drop functionality may be causing this (because of the function comment), but that's a guess.  My only option right now is to start tracing backwards using Google Chrome or Mozilla Firefox.  I'm just looking for advice on troubleshooting unless you know what might cause this.
/**
 * Moves Component to the provided target instead.
 * @private
 */
moveItem : function(item, target, position) {
        target = target.dom || target;
        if (typeof position == 'number') {
            position = target.childNodes[position];
        }
        target.insertBefore(item.el.dom, position || null);  // line 51942
        item.container = Ext.get(target);
        this.configureItem(item);
    },

Exception:
Invalid argument.
ext-all-dev.js line 51942 character 9

A: Placed the tree drag and drop plugin fully qualified class name into the requires config.


text:
Q: Prevent continuously adding columns by postgres json data type I wanted to ask, if there may be a different and better approach than mine.
I have a model entity that can have an arbitrary amount of hyperparameters. Depending on the specific model I want to insert as row into the model table, I may have specific hyperparameters. I do not want to continuously add new columns to my model table for new hyperparameters that I encounter when trying out new models (+ I don't like having a lot of columns that are null for many rows). I also want to easily filter models on specific hyperparameter values, e.g. "select * from models where model.hyperparameter_x.value < 0.5". So, an n-to-n relationship to a hyperparameter table comes to mind. The issue is, that the datatype for hyperparameters can be different, so I cannot define a general value column on the relationship table, with a datatype, that's easily comparable across different models.
So my idea is, to define a json type "value" column in the relationship table to support different value datatypes (float, array, string, ...). What I don't like about that idea and what was legitimately critizised by colleagues is that this can result in chaos within the value column pretty fast, e.g. people inserting data with very different json structures for the same hyperparameters. To mitigate this issue, I would introduce a "json_regex_template" column in the hyperparameter table, so that on API level I can easily validate wheter the json for a value for hyperparameter x is correctly defined by the user. An additional "json_example" column in the hyperaparameter table would further help the user on the other side of the API make correct requests.
This solution would still not guarentee non-chaos on database request level (even though no User should directly insert data without using the API, so I don't think thats a very big deal). And the solution still feels a bit hacky. I would believe, that I'm not the first person with this problem and maybe there is a best practice to solve it?
Is my aversion against continuously adding columns reasonable? It's about probl. 3-5 new columns per month, may saturate at some point to a lower number, but thats speculative.
I'm aware of this post (Storing JSON in database vs. having a new column for each key), but it's pretty old, so my hope is that there may be new stuff I could use. The model-hyperparameter thing is of course just a small part of my full database model. Changing to a non-relational database is not an option.

Opinions are much appreciated


text:
Q: Recognize when a database connection happens in shiny app I have the shiny app below which consists of app.r and global.r. The global file includes the code that enables a database connection. This connenction is enabled via a big number of passwords which are known only from the database admin. So I want every time the user gives a wrong password a message to be displayed. For this question I just used a random password in order to create the if else statement but as I said above the connection happens with many different passwords so instead of setting all of those manually I would just like to recognize if the connection con happens.
app.r
library(shiny)
library(shinydashboard)
library(shinydashboardPlus)
library(shinyjs)
mytitle <- paste0("Life, Death & Statins")
dbHeader <- dashboardHeaderPlus(
  titleWidth = "0px"
)

shinyApp(
  ui = dashboardPagePlus(
    header = dbHeader,
    sidebar = dashboardSidebar(width = "0px"
    ),
    body = dashboardBody(

      useShinyjs(),
      tags$script(HTML("$('body').addClass('fixed');")),

      tags$head(tags$style(".skin-blue .main-header .logo { padding: 0px;}")),
      passwordInput("pwd",label = "",value = "",width = "100%" ),
      actionButton('button', "Continue"),
      uiOutput("error")
    )

  ),
  server<-shinyServer(function(input, output,session) {
    hide(selector = "body > div > header > nav > a")
    observeEvent(input$button, {

      if(input$pwd==""){
        return(NULL)
      }
      else if(input$pwd=="qh2gt1"){
        return(NULL)
      }
      else{
        output$error<-renderUI({
          "Please re-enter database browser password"
        })
      }

    })
  }
  )
)

global.r
library(odbc)
con<- dbConnect(odbc(),
                driver   = "SQL Server",
                database = "databasename",
                server   = svr,
                port     = 1433,
                UID      = "uid",
                PWD      = input$pwd)

A: You can encapsulate the dbConnect inside a try :
con <- try( dbConnect( odbc(),
                       driver   = "SQL Server",
                       database = "databasename",
                       server   = svr,
                       port     = 1433,
                       UID      = "uid",
                       PWD      = input$pwd))

Then check its class:
if( class(con) != "try-error" )
  # OK code
else
  # Error code