text:
Q: Is there a way to count the channels inside of a category in discord.js? I'm trying to write a bot that will tell me the number of channels in a specific category.
if (strMessage === "!outline") {
  var outlineSize;

  message.reply("There are " + outlineSize + " outlines currently hidden away. Type '?outline' to learn more about them.");
}

I'm trying to set outlineSize to the number of channels in the category (the category is always the same, hence the specific variable name). For example, if there are two channels I want outlineSize to equal 2.
I know that it has something to do with CategoryChannelChildManager in discord.js v14. However, I've found nothing that's been able to teach me how to use it. To be fair, I'm new to programming and JavaScript which is where I expect the main part of the problem lies.
Also note: There are a few similar questions on this site that pertain to this, but due to the always-changing nature of Discord's API I don't believe they've been accurate for over a year now and give me nothing but errors when I try them.

A: You can fetch the category channel by its ID and grab its children property. As you've mentioned it's a CategoryChannelChildManager so you will need to access its cache that returns a Collection. And finally, Collections have a size property that returns the number of items in the given collection. That's what you'll need:
let CATEGORY_ID = '813845582854001392';
let category = await client.channels.fetch(CATEGORY_ID);
let outlineSize = category.children.cache.size;

message.reply(`There are ${outlineSize} outlines currently hidden away. Type '?outline' to learn more about them.`);


text:
Q: VS2008 - Project Out of Date, not a line of code changed I am having a very strange problem with Visual Studio 2008. I searched here on SO for similar problems with the "Project Out of Date" dialog, but their problem was that either they were using a header file that is deprecated/no longer exists, or their problem was occuring while building a multi-project solution or it had other dependencies.
My project is a Win32 Console application, I went to File->New->Project...->Win32 Console Application. I used the default settings (precompiled header is checked), and I didn't change a single line of code in the project, as soon as the project created I pressed the debug button (though I get the exact same problem when I set the build target to Release).
[main.cpp]
#include "stdafx.h"

int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

^ Very standard source file, right? Well, no matter what I build in any project VS2008 tells me it is out of date. Why? This problem may not prevent me from building the project, but I would very much like everything to be in order and never have to see this dialog again. Again, I looked at similar questions, but their solutions involve removing some extra dependency or something of the sort, none of which applies to my situation.
Why might VS2008 be nit-picking on its own project template?

A: If a source file (including include files) somehow got a date time some time in the future, then the compiler will think the object files are always out of date.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why must (), [], ->, and = be overloaded only as member functions? I tried to analyse why some of the operators ((), [], ->, =) should be overloaded as member functions only. I failed and I tried to search on internet but of no use. Can any one please help me to understand this restriction?

A: Certain forms of operators require access to the "this" pointer of an instance of a class in order to operate directly on that instance as they only take a single argument to the same type.
class A{
public:

    int x;

    // only takes a reference to another 'A' type, so we need the 'this' pointer
    A& operator=(const A& other){
        this->x = other.x;
        return *this;
    }
};

A: Although maybe not very satisfying, here's what the standard has to say about it:
(emphasis is mine)
§3.5.3 Assignment

An assignment operator shall be implemented by a non-static member function with exactly one parameter.

§3.5.4 Function call

operator() shall be a non-static member function with an arbitrary number of parameters.

§3.5.5 Subscripting

operator[] shall be a non-static member function with exactly one parameter.

§3.5.6 Class member acess

operator-> shall be a non-static member function taking no parameters.

I can't speak to the reasoning behind these requirements, so I will leave that aspect to those that are more familiar with how compilers are designed.

A: I think this is most likely why that portion of the standard was written that way.
but if it is not forbidden, the friend version would never be called, in my testing code ,when
 Complex operator+(const Complex &other);

is defined as private, the compiler would
give error message
'Complex Complex::operator+(const Complex&)' is private
 Complex Complex::operator+(const Complex &other)

instead of using the friend version
refer to Why cannot a non-member function be used for overloading the assignment operator?
Because the default operator= provided by the compiler (the memberwise copy one) would always take precedence. I.e. your friend operator= would never be called.
(If the assignment was performed inside a class method, because of the lookup rules, the member function (in this case generated by the compiler) would take precedence)
I try to using operator + for test. it prove the precedence
it outputs:
member function called
7+11i

testing code:
#include<iostream>
using namespace std;
class Complex
{
public:
    Complex(int real, int imag);
    Complex(void);
    ~Complex(void);

    Complex &Add(const Complex &other);

    void Display() const;

    Complex operator+(const Complex &other);

    friend Complex operator+(const Complex &c1, const Complex &c2);

private:
    int real_;
    int imag_;
};
Complex::Complex(int real, int imag): imag_(imag), real_(real)
{

}
Complex::Complex(void)
{
}

Complex::~Complex(void)
{
}

Complex &Complex::Add(const Complex &other)
{
    real_ += other.real_;
    imag_ += other.imag_;
    return *this;
}

void Complex::Display() const
{
    cout << real_ << "+" << imag_ << "i" << endl;
}

Complex Complex::operator+(const Complex &other)
{
    int r = real_ + other.real_;
    int i = imag_ + other.imag_;
    std::cout << "member function called"<< std::endl;
    return Complex(r, i);
}

Complex operator+(const Complex &c1, const Complex &c2)
{
    int r = c1.real_ + c2.real_;
    int i = c1.imag_ + c2.imag_;
    std::cout << "friend function called"<<std::endl;
    return Complex(r, i);
}

int main(void)
{
    Complex c1(3, 5);
    Complex c2(4, 6);

    Complex c3 = c1 + c2;

    c3.Display();

    return 0;
}


text:
Q: RxJava compile error on the following case I would like to try the very simple RxJava code like the following
 int[] test = {1,2,3,4};
 Observable<Integer> findAverage = Observable.fromArray(test);
 averageInteger(findAverage).subscribe(System.out::println);

First I met a compile error(incompitible bounds) for the Observeable.fromArray(test),
Second, it seems severageInteger can no longer be found. I am using 2.0.8 version of RxJava.

A: It is because of the wrong type of findAverage:
It should be:
Observable<int[]> observable = Observable.fromArray(array);

A full example with following Gradle-package: 'com.github.akarnokd:rxjava2-extensions:0.16.4'
List<Integer> integers = Arrays.asList(1, 2, 3, 4);

Observable<Integer> integerObservable = Observable.fromIterable(integers);

Observable<Double> doubleObservable = MathObservable.averageDouble(integerObservable);

doubleObservable.subscribe(System.out::println);

Implement as Operator:
@Test
public void averageDoubleOperator() throws Exception {
    List<Integer> integers = Arrays.asList(1, 2, 3, 4);

    Observable<Integer> integerObservable = Observable.fromIterable(integers);

    integerObservable.lift(new AvgOperator())
            .test()
            .assertResult(2.5);
}

@Test
public void averageDoubleOperator_empty() throws Exception {
    List<Integer> integers = Collections.emptyList();

    Observable<Integer> integerObservable = Observable.fromIterable(integers);

    integerObservable.lift(new AvgOperator())
            .test()
            .assertTerminated()
            .assertError(IllegalStateException.class);
}

class Avg {
    long count;
    int sum;

    Avg(long count, int sum) {
        this.count = count;
        this.sum = sum;
    }
}

class AvgOperator implements ObservableOperator<Double, Integer> {
    @Override
    public Observer<? super Integer> apply(Observer<? super Double> observer) throws Exception {
        return new Operation(observer);
    }

    class Operation implements Observer<Integer> {
        private final Observer<? super Double> observer;
        private Subscription s;
        private long sum;
        private int count;

        Operation(Observer<? super Double> observer) {
            this.observer = observer;
        }

        @Override
        public void onSubscribe(Disposable d) {
            observer.onSubscribe(d);
        }

        @Override
        public void onNext(Integer integer) {
            ++count;
            sum = sum + integer;
        }

        @Override
        public void onError(Throwable t) {
            this.observer.onError(t);
        }

        @Override
        public void onComplete() {
            if (count == 0) {
                this.onError(new IllegalStateException("Average is not defined for 0 values."));
                return;
            }
            this.observer.onNext(sum / (double) count);
            this.observer.onComplete();
        }
    }
}


text:
Q: What is a "Year" According to Starfleet? We've all heard about the famous "five year mission" to explore strange new worlds and so on.  And this question is asked with the thought that there might be issues with time dilation in warp drive or at high impulse speeds.
In chat, we were discussing this and one point came up: It's likely a "5 year mission" was based on 5 years according to Starfleet time.  But every planet has a different year, different days, and months are basically culturally defined (if they're defined at all in some cultures).
So what is a Starfleet year?  Is it an Earth standard year?  An Earth leap year?  A Vulcan year?  When someone in Starfleet talks about a day or year, what is the basis for that measurement of elapsed time?

Note: I am not referring to dealing with issues of time dilation.  I mean what constitutes a year according to Starfleet?  Is it the time it takes Earth to complete an orbit around Sol?  Is it an average between Earth's year and Vulcan's year?  How long is a standard year in Starfleet, assuming no time dilation?  If I am on a planet and won't be leaving it and start timing it NOW, will a Starfleet year last as long as an Earth year?  As long as a Vulcan year?  A Martian year?

A: The warp drive is an Alcubierre drive, so it does not suffer from the effects of time dilation.
It probably means five years as in five earth years.
I can't understand the starddate system as it is explained here, there does not seem to be any sort of algorithm that is used, and is explained away as a "complex relationship had been established between stardates and the gregorian calender."

A: Due to a series of retcons and reversed retcons, I now believe a Starfleet year is roughly 3 Earth years.
I've bolded the important parts below:
Star Trek Guide for TOS

We invented "Stardate" to avoid continually mentioning Star Trek's
  century (actually, about two hundred years from now), and getting into
  arguments about whether this or that would have developed by then.
  Pick any combination of four numbers plus a percentage point, use it
  as your story's stardate. For example, 1313.5 is twelve o'clock noon
  of one day and 1314.5 would be noon of the next day. Each percentage
  point is roughly equivalent to one-tenth of one day. The progression
  of stardates in your script should remain constant but don't worry
  about whether or not there is a progression from other scripts.
  Stardates are a mathematical formula which varies depending on
  location in the galaxy, velocity of travel, and other factors, can
  vary widely from episode to episode.

Star Trek: The Next Generation Writer's/Director's Guide of March 23, 1987

A stardate is a five-digit number followed by a decimal point and one
  more digit. Example: "41254.7." The first two digits of the stardate
  are always "41." The 4 stands for 24th century, the 1 indicates first
  season. The additional three leading digits will progress unevenly
  during the course of the season from 000 to 999. The digit following
  the decimal point is generally regarded as a day counter.

And a note just below it:

Under this system, 1,000 stardate units were equal to approximately
  one year, since that is the normal timespan between two TV seasons.
  The value of the century digit nine seasons later was clarified as
  early as TNG: "Future Imperfect", where the imaginary Jean-Luc Riker
  asks the computer to display his birthday party of stardate 58416,
  less than sixteen years in the future according to the episode. The
  relation to the 24th century could only be symbolic.

Different systems, you say?  Not so!  One user has done research into how the decimal point really is a fraction of a day.  The TOS-era fraction matches up perfectly in TNG 2x11, 2x13, 4x17, 4x18, 5x07, and 6x05 - all various times a fractional stardate has appeared on the screen at the same time as a time of day.
So, to summarize the above:

*

*Future Imperfect takes place on Stardate 44286, and Jean-Luc Riker shows Will Riker his birthday party on Stardate 58416, less than 16 years into the future.  Just over 14000 Stardate unites, to be precise - so 1000 Stardate units is very close to 1 year.

*As noted by the user who looked into times, 1 Stardate unit correlates exactly to 1 day, in both TOS and TNG (and because it does in TNG, DS9 and VOY should as well - they used the same system).

*Finally, TOS 3x24 featured the Stardate 5928.5, and VOY contained 56947.0 - by these, we know the day counter doesn't just hit 365 and reset.  One year contains at least 947 days.

There is an additional note on here and Stardates not exactly coinciding with the 1000 = 1 year conversion:

The relation to the 24th century could only be symbolic. The writers
  of the Star Trek Chronology further developed the system by having a
  calendar year start at 000 and end at 999, although this does not fit
  all references in the show, such as a Diwali celebration around
  stardate 44390, too early in the year according to the simplified
  system. (TNG: "Data's Day") Stardate 41986.0 was in 2364 according to
  TNG: "The Neutral Zone", hence the simplified system assumes that
  stardates 41xxx.x covered the entire year 2364, stardates 42xxx.x the
  entire year 2365 and so forth.

This can be explained away if a Stardate year isn't exactly 1000 Stardate units, simply very close to it.  And it makes sense - one year on Earth is around 365.2425 days.  Gene Roddenberry did also state that Stardates do have some natural basis, just like Earth years are based on the sun:

Stardates are a mathematical formula which varies depending on
  location in the galaxy, velocity of travel, and other factors, can
  vary widely from episode to episode.

EDIT
Yes, if Jean-Luc Riker was 16 Starfleet years old, that would make him about 48 Earth years old, which is definitely wrong.  So, I feel I made a mistake somewhere...  Or, Stardates and "years" are just plain inconsistent  ;)

A: You will never know the full truth about Star Trek years, stardates, and chronology until I write and publish my book on the subject.
My researches show that in the era of TNG it is impossible for there to be a consistent relationship between the number of years alleged to be between two events and the number of stardate units between them.
Either 1) the temporal length of a stardate unit is variable and all time differences are expressed in the same type of years with identical lengths, or  else 2) the temporal length of a stardate unit is constant and people use different types of years with different lengths to express time differences between events.
It is my belief that the second possibility is correct and in the era of TNG, DS9, and Voyager stardates have a constant unchanging temporal duration and that people express time differences using years of different length.
It is my belief that the length of a stardate unit was chosen and then people began to talk of 1,000 stardate units as being a "stardate year".  Thus seasons in the tNG era are a stardate year long, which is not the year of any planet.
People in the era of TNG tend to express time in either the years of their home planets or the official Federation Year which seems to be much longer than an Earth year if Data used Federation Years in "Where no One has Gone Before".  I expect that the ages of Earth Humans are given in Earth years.


text:
Q: How to iterate an ArrayList to get the contents ArrayList testdata_1 = new ArrayList<>();
    for (int i = 0; i < testdata_1.size(); i++) {

        System.out.println(testdata_1.get(i));
    }

My output is
[]
[[Username,Password], [user_1, Test@100]]

I want to delete the first blank value ,iterate the arraylist, identify the key as username,fetch the value "user_1" and assign to a local string variable "username"
Datatable
    | Username   | user_1   |
    | Password   | Test@100 |
List> data = new ArrayList<>();
        if(step.getRows()!=null)
            step.getRows().forEach(row -> data.add(row.getCells()));

A: Resolved. Used data encapsulation to resolve this


text:
Q: C#: Adding invisible character to a string I have a Windows form that has a drop down of value "Main Area". I take this value and embed it into a string.
But the third party application that we use does not like spaces in the string. Is there a way that I can add an invisible character using C# so that it doesn't seem like an empty space?
I tried string.replace(" ", " ");, string.replace(" ", "%20") etc..etc.. but doesn't work.


text:
Q: Importing a module in Python as part of a package *as well* as in a way that works stand-alone Note: This is Python 3.5
Given some project thing such that:
   thing/
       top.py (imports bar)
       utils/
           __init__.py (empty)
           bar.py (imports foo; has some functions and variables)
           foo.py (has some functions and variables)

I can import utils.bar in top.py, and when running top.py the file bar.py must contain import utils.foo to get to foo.py's code.
To run bar.py directly though, bar.py must have import foo instead (import utils.foo fails). If I make that change then top.py no longer works.
How can I run top.py or bar.py and still use the same import construct in bar.py for both use cases? I feel like I'm missing some simple step or construct, but perhaps expecting bar.py to work independently in this way is asking too much (short of conditional imports or such).
Edit: I've accepted the proper answer, but if you still insist on doing this with some contortions, the following worked for me:
In bar.py
try:
    import foo
except ImportError as err:
    from . import foo

Then you can run bar.py directly (in my case, as I develop bar.py I'm using some experimental code in an if __main__ block at the bottom of the file). Once my code is well-integrated I remove the conditional and the main part (since it's not meant to run standalone).

A: Its typical to have all your entrypoints outside the module, than all imports can be relative.
For example
thing/
    app.py
    thing/
        __init__.py
        top.py
        utils/
            __init__.py
            bar.py
            foo.py

And app.py can look like
from thing import app
if __name__ == '__main__':
    app.main()

Than in top.py you have
from .utils import bar

And in bar you have
from . import foo

Or
from thing.utils import foo

Or
from ..utils import foo

So if you need two entrypoints, you can either make app take a command line argument for the second entry point, or you can make another file like app that imports bar

A: https://docs.python.org/2.5/whatsnew/pep-328.html try to use import .foo and for python 3 see Relative imports in Python 3


text:
Q: dart add data class in function parameter i have three methods like these:
func1() async {
 ...
 var list = (response['contents'] as List).map((i) => Quotation.fromJson(i)).toList();
 ...
} // has 20 lines

func2() async {
 ...
 var list = (response['contents'] as List).map((i) => Delivery.fromJson(i)).toList();
 ...
} // has 20 lines

func3() async {
 ...
 var list = (response['contents'] as List).map((i) => Discovery.fromJson(i)).toList();
 ...
} // has 20 lines

now i would like to add a parameter to generalize the SomeClass.fromJson(i)
so the code would be like this
generalFunc( someType SomeClass ) async {
 ...
 var list = (response['contents'] as List).map((i) => SomeClass.fromJson(i)).toList();
 ...
}

... call generalFunc(Quotation) // reduce 19 lines
... call generalFunc(Delivery) // reduce 19 lines
... call generalFunc(Discovery) //reduce 19 lines

how do i accomplish this? thank you..

A: When you declare a parameter someType SomeClass you are expecting an object of SomeClass. if that is what you want, you can declare a parameter of type dynamic.
See the code below:
generalFunc( generic SomeClassObject ) async {
 ...
 var list = (response['contents'] as List).map((i) => SomeClassObject.fromJson(i)).toList();
 ...
}

... call generalFunc(quotationObject) // reduce 19 lines
... call generalFunc(deliveryObject) // reduce 19 lines
... call generalFunc(discoveryObject) //reduce 19 lines

But, if you want to pass a class... well that is impossible. but you can work it out by making the parameter as a selector for the class.
See the code below:
enum SomeClass {
  Quotation,
  Delivery,
  Discovery
}

generalFunc({ SomeClass someClass }) async {
  ...
  var list;
  if(someClass == SomeClass.Quotation){
    list = (response['contents'] as List).map((i) => Quotation.fromJson(i)).toList();
  }
  else if(someClass == SomeClass.Discovery) {
    list = (response['contents'] as List).map((i) => Discovery.fromJson(i)).toList();
  }
  else if(someClass == SomeClass.Delivery) {
    list = (response['contents'] as List).map((i) => Delivery.fromJson(i)).toList();
  }
  ...
}

... call generalFunc(someClass: SomeClass.Delivery);
... call generalFunc(someClass: SomeClass.Discovery);
... call generalFunc(someClass: SomeClass.Qoutation);


text:
Q: Setting a "statical" running of MS DHCP server I am trying to setup a MS DHCP server that runs in some kind of "statical assignment" mode.
The goal is that prevent clients automatically receiving IP configuration from DHCP. I want them only receiving configuration, after DHCP reservation set for their devices. The key should be somehow the MAC address of the authorization.
I tried some solutions, such as adding exclusion range that is same as the distribution range, but I don't think that is much "practical".
I also tried to make NPS or scope level policies, but without any success.
MAC address filtering could be also a solution, but I want to rather stick with something that is involved with DHCP reservation.
So, any suggestions what could be the best solution for this?
Thanks in advance.


text:
Q: Instantiate TinyMCE via JS ( rather than PHP/wp_editor ) Once a page has loaded, how do I create a TinyMCE editor?
Putting a wp_editor call in an AJAX request then displaying it gives this:

Visual and text tabs are nonfunctional, no toolbar, no active TinyMCE instance, just the html markup. I need to instantiate the JS component of TinyMCE, but how?
I've also tried making a call in my AJAX response PHP to _WP_Editors::editor_js();, and I can see the response in the console using console.log and I see the JS script there, but it is not inserted into the DOM and it is never executed

A: Updated for TinyMCE 4
I've made some progress
Load a wp_editor in the initial page load in a hidden div, then do the AJAX call to grab the editor markup.
While in PHP, you will need to retrieve the IDs of the editors created via wp_editor calls. Unfortunately, the variables on the _WP_Editors class are private, but wecan get around this by using filters. To do this we start by calling the editor_js hook inside an output buffer. It will attempt to generate the needed settings and output the required JS, although this JS will not work when sent back via AJAX and inserted.
At the end of this call, the _WP_Editors class pases the mcesettings array through a filter, which we will use to make a copy that we can pull the editor IDs out of:
add_action( 'after_wp_tiny_mce', array( $this, 'steal_away_mcesettings' ) );

function steal_away_mcesettings( $mcesettings ) {
    $this->mcesettings = $mcesettings;
}

So after we've added this filter, we call out editor_js function:
ob_start();
_WP_Editors::editor_js();
ob_end_clean();

We can now use our $mcesettings copy to fill in a list of IDs:
$ids = array();

foreach ( $this->mcesettings as $editor_id => $init ) {
    $ids[] = $editor_id;
}

The ids array can now be sent back in the AJAX response along with the html.
Once in the browser, we can insert the html into the page, and then using our editor_ids, we can instantiate the TinyMCE instances like this:
function tinyMCE_bulk_init( editor_ids ) {
    var init, ed, qt, first_init, DOM, el, i;

    if ( typeof(tinymce) == 'object' ) {

        var editor;
        for ( e in tinyMCEPreInit.mceInit ) {
            editor = e;
            break;
        }
        for ( i in editor_ids ) {
            var ed_id = editor_ids[i];
            tinyMCEPreInit.mceInit[ed_id] = tinyMCEPreInit.mceInit[editor];
            tinyMCEPreInit.mceInit[ed_id]['elements'] = ed_id;
            tinyMCEPreInit.mceInit[ed_id]['body_class'] = ed_id;
            tinyMCEPreInit.mceInit[ed_id]['succesful'] =  false;
        }

        for ( ed in tinyMCEPreInit.mceInit ) {
            // check if there is an adjacent span with the class mceEditor
            if ( ! jQuery('#'+ed).next().hasClass('mceEditor') ) {
                init = tinyMCEPreInit.mceInit[ed];
                try {
                    tinymce.init(init);
                    tinymce.execCommand( 'mceAddEditor', true, ed_id );
                } catch(e){
                    console.log('failed');
                    console.log( e );
                }
            }
        }

    }
}

Because we don't have the ability to generate the necessary TinyMCE settings ourselves to match the WordPress style, we instead steal them from the instance we created in the initial page load, and make copies. We then modify the copies to use the correct element IDs and proceed as usual, checking that the elements dont already have an instance.

Issues

*

*The tabs for plain text vs visual content do not work

*No quick tags on the plaintext view

*The extra weight of the initial TinyMCE instance

*No Media uploader button

*Adding 2 TinyMCE instances or more in an AJAX request leads to one working instance, and the others being broken. I'm not sure why this is the case, yet 2 AJAX requests with 1 instance each, gives you 2 working instances.

*The JS could be modified to not modify the TinyMCEPreInit structure, and pass the copy straight into the initialiser, removing a DOM traversal in the process


text:
Q: [Spring-Cloud][Maven][Docker]Should Feign interfaces be put in FeignClients or EurekaClients? EurekaServer: register/expose services
EurekaClients: provide services
FeignClients: consume services and provide APIs
I'm using Feign for service consumption. I wonder if feign interfaces (interfaces that annotated with @FeignClient) should be put in EurekaClients or FeignClients?

*

*If Feign interfaces are put in EurekaClients.

GOOD: I only need to write only one copy of Feign interfaces, and implement it in the EurekaClients. For any FeignClients that need to use this service, import these interfaces from EurekaClients and just use it.
BAD: Module dependencies could be easily set, but it is hard to do mvn package or using docker for production. As the problem I stated HERE.

*If Feign interfaces are put in FeignClients(almost every examples I can find on the internet do like this).

GOOD: Easy to build.
BAD: A lot of duplicated code. Because for every FeignClient I need to re-write @FeignClient annotated interfaces. If there are a lot of nested FeighClients and EurekaClients, it would be too difficult to maintain.
So any suggestions for a good practice of Where should I put Feigh interfaces ?

A: Here is the pattern we followed in our projects. Each service has two projects, e.g., :
Service A
  model
  service

All the controllers and other business related classes, e.g, DAOs, service, Repository classes are kept in the service project. While the models used by the controller and exposed to the outside world are kept in the model project. The controller also implements an interface which exposes the REST API. This interface is kept in the model project also.
public interface AuthorService {

    @RequestMapping(method = RequestMethod.GET, produces = {
        MediaType.APPLICATION_JSON_VALUE}, value = "/authors/{id}")
    @ResponseBody
    Author getAuthor(@PathVariable("id") Integer id);
}

The AuthorService interface and the model, Author are kept in the model project. The controller, AuthorController which implements the AuthorService is kept in the_service_ project.
Let's say ServiceB uses ServiceA, then the former import's the latter's model project. In ServiceA's service, we create a Feign interface, e.g.,
@FeignClient(name = "author", fallback =
    AuthorServiceFallbackClient.class)
public interface AuthorServiceClient extends AuthorService {
}

This pattern helped us to reduce quite a bit of code duplication.


text:
Q: Jquery combine click and change Is it possible listen click and change for one code?
$(document).on("click", "button.options_buy",function(event) {

//   same code
}

$(document).on("change", "select.options_buy",function(event) {

//   same code
}

I try this
$(document).on("click change", "button.options_buy,select.options_buy",function(event) { }

It works but I want 'click' only for 'button.options_buy' and 'change' for 'select.options_buy'
is it possible?

A: Best way to do it is to have two event handlers as you have, but only have a common function that is called from each:
$(document).on("click", "button.options_buy",function(event) {
  commonFunction();
})

$(document).on("change", "select.options_buy",function(event) {
    commonFunction();
})

function commonFunction(){
//common function code
}

A: I would like to extend your code.
$(document).on("click change", "button.options_buy,select.options_buy",function(event) {
  if(event.type=="click"){
        someFunction();
  } else if(event.type=="change"){
        someFunction();
  }

}

A: You can use .on() to bind a function to multiple events:
  $('#foo').on('keypress click change', function(e) {
        //
    });

OR declare a function and call it for each event
$('#foo')
    .change(myFunction)
    .click(myFunction)
    .blur(myFunction)

jQuery .bind()
$( "#foo" ).bind({
  click: function() {
    // Do something on click
  },
  mouseenter: function() {
    // Do something on mouseenter
  }
});

OR
$( "#foo" ).bind( "mouseenter mouseleave", function() {
  $( this ).toggleClass( "entered" );
});


text:
Q: Worklight cannot login to application protected behind ltpatoken sso While trying to test my worklight LTPA sso configuration, I cannot login to my application.  I can however login to a protected worklight console through LTPA (without being prompted for a username/password), so I know that the LTPA token is getting validated correctly.
When I use the worklight console to access my protected application, I get 500 errorsfrom the common/init and common/login call because I am being challenged by the worklight server for authentication.
This is on worklight 6.1.0.2.  I have attached the a wireshark trace of the worklight server's response here:
Unauthorized
X-Powered-By: Servlet/3.0
P3P: policyref="/w3c/p3p.xml", CP="CAO DSP COR CURa ADMa DEVa OUR IND PHY     ONL UNI COM NAV INT DEM PRE"
WWW-Authenticate: WL-Composite-Challenge
Content-Type: application/json; charset=UTF-8
Cache-Control: no-cache, no-store, must-revalidate
Expires: Sat, 26 Jul 1997 05:00:00 GMT
Content-Length: 96
Content-Language: en-US
Connection: Close
Date: Fri, 05 Jun 2015 21:23:48 GMT

/*-secure-
{"challenges":{"wl_antiXSRFRealm":{"WL-Instance-Id":"kp3k4l8812ubp1d3ir6oeub9t2"}}}*/

Here's my authenticationConfig.xml
<staticResources>
    <resource id="worklightConsole" securityTest="CustomAdapter-securityTest">
        <urlPatterns>/console*</urlPatterns>
    </resource>
</staticResources>

<securityTests>

    <customSecurityTest name="CustomAdapter-securityTest">
        <test isInternalUserID="true" realm="CustomAuthenticationRealm"/>
    </customSecurityTest>

</securityTests>
<realms>
    <realm loginModule="CustomLoginModule" name="CustomAuthenticationRealm">
      <className>com.worklight.core.auth.ext.WebSphereFormBasedAuthenticator</className>
        <parameter name="login-page" value="/login.html"/>
        <parameter name="error-page" value="/loginError.html"/>
        <parameter name="cookie-name" value="LtpaToken2"/>
    </realm>
</realms>

<loginModules>
<loginModule name="CustomLoginModule">
        <className>com.worklight.core.auth.ext.WebSphereLoginModule
        </className>
        <parameter name="httponly-cookie" value="true" />
        <parameter name="cookie-name" value="LtpaToken2" />
</loginModule>
</loginModules>

In case you want it, here's the wireshark of the request being sent to the Worklight common/init (with my LTPAToken removed for security)
POST /AnywhereWorkManager/apps/services/api/WorkExecution/common/init HTTP/1.1
accept: text/javascript, text/html, application/xml, text/xml, */*
accept-language: en-US
connection: close
content-length: 65
content-type: application/x-www-form-urlencoded; charset=UTF-8
host: <the internal host>
referer: https://<the external host>/AnywhereWorkManager/apps/services/preview/WorkExecution/common/0/default/index.html
user-agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.81 Safari/537.36
via: HTTP/1.1 <the external host>
x-wl-app-version: 1.0
origin: https://<the external host>
iv_server_name: reverseproxy-webseald-<the external host>
x-wl-platform-version: 6.1.0.01.20140311-2356
x-requested-with: XMLHttpRequest
Cookie: LtpaToken2=<mytoken>; JSESSIONID=<mysessionid>; testcookie=oreo

skin=&skinLoaderChecksum=&isAjaxRequest=true&x=0.8017935899551958

A: There was a setting on the webseal junction that I had to set to get webseal to
ignore the 401 and pass it through to the user.  From the the worklight sso guide documented here..
http://www-01.ibm.com/support/docview.wss?uid=swg24034222
The HTTP Basic Authentication Header: Ignore (-b ignore) option is necessary to
accommodate an additional device authentication handshake exchange between the
Worklight client and server. IBM Security Access Manager handles the 401 error and
return this to the client, which prevents further processing in the application. The use of
HTTP Basic Authentication Header: Ignore resolves the 401 error processing.
The Include session cookie (-k) option causes WebSEAL to forward the user session
cookie to the junctioned server. This allows the retrieval of the WebSEAL session cookie
from the request headers which can be used to provide SSO to junctioned systems
accessed within Worklight Adapters.


text:
Q: $f$ is continuous at $c$ $\implies$ $f$ has a limit at $c$. True? Further to Another simple/conceptual limit question where I was questioning David Brannan's assertion in his A First Course in Mathematical Analysis that $f(x)=\sqrt x,x\geq 0$ has no limit at $0$ (Example 2c if you type in page 184 in the box on http://www.scribd.com/doc/74564079/Mathematical-Analysis), I just noticed that in an earlier section he asserted that the same function is continuous on its domain i.e. including at $0$ (Example 3 if you type in page 148 in the box).
Does this not violate the well-known theorem (Thm 2 if you type in page 185 in the box) implying that if $f$ is continuous at $c$, then $f$ has a limit at $c$ ? Is David Brannan contradicting himself (by setting up his definition of limits badly)?
EDIT:  Thanks, Wisefool. It turns out that there is no contradiction in Brannan's assertions (that the square root function is continuous at 0 yet has no limit at 0) after all, but only because of his peculiar definition of "limit" and his analogously peculiar statement of the theorem relating continuity at a point to the limit at that point.

A: It is a simple matter of terminology: in that example (or in that section/chapter/book) a limit is understood to be a two-sided limit.
$f$ has limit $l$ in $x_0$ if:

*

*$f$ is defined in a (puntcured) neighborhood of $x_0$

*for every $\epsilon>0$ there exists $\delta>0$ such that if $|x-x_0|<\delta$ then $|f(x)-l|<\epsilon$.

In that example, it is the first condition which fails.
This isn't exactly standard and personally I would have said that the function had a limit for $x\to 0$, but I can see the book's point...
EDIT: moreover, Thm2 on page 185 speaks about a point $c$ contained in an open interval $I$ where the function is defined. There is no open interval of the real line containing $0$ where the function $\sqrt{x}$ is defined.


text:
Q: query result array in loop for another query I Queried Database Table 'users' for 'user_id'. and get an array of ids.
$sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = @mysqli_query ($dbcon, $sel);

Then i inserted values into another table income for all those user ids.
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount)  VALUES ('$row', '100')";
$giv = @mysqli_query ($dbcon, $ins);
}

Notice: Array to string conversion in E:\xampp\htdocs\project\t.php on line 109
Can anyone help me resolve this issue.

A: $sel = "SELECT user_id FROM users WHERE status='Approved'";
$result = @mysqli_query ($dbcon, $sel);

while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$ins = "INSERT INTO income (user_id, income_amount)  VALUES ('" . $row['user_id'] . "', '100')";
$giv = @mysqli_query ($dbcon, $ins);
}

A: First , Check if  $results is in array ..you can put some error handling checked is_array($result).
If it is fine then pass it to mysqli_fetch_array().
Do't add suppress @ error ,while developing.

A: i would like to suggest you a single query for that so after that you need not to use while loop to insert your data in income table:
Just try it :
INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved';

You can use it like that way :
$sel = "INSERT INTO income (user_id,income_amount) SELECT user_id,'100' AS income_amount FROM users WHERE status = 'Approved'";
$result = @mysqli_query ($dbcon, $sel);


text:
Q: Cursor position not good I looked for solutions to this problem for a long time, found some and I thought I understand but apparently I don't. I'd like to make a canvas that ppl can use to sign to confirm a booking. But I can't get the line to follow the user's cursor. My code looks like this:
HTML:
<!doctype html>

    <meta charset="utf-8">
    <title>Signature Test</title>
    <link rel="stylesheet" href="../css/test.css">

        <canvas id="signaturePad">DSorry your browser is rubbish</canvas>

CSS:
body
{
  margin: 0;
  padding: 0;
}

header
{
  border: 1px solid black;
  width: 100%;
  height: 50px;
}

#content
{
  border: 1px solid blue;
  width: 100%;
  height: 300px;
  position: relative;
}

#content #signaturePad
{
  border: 1px solid red;
  width: 200px;
  height: 200px;
  position: absolute;
  left: calc(50% - 100px);
  top: calc(50% - 100px);
}

footer
{
  border: 1px solid black;
  width: 100%;
  height: 50px;
}

And finally the JS:
var canvas = document.getElementById("signaturePad");
var context = canvas.getContext("2d");
var radius = 1;
var dragging = false;
context.lineWidth = 2*radius;

function displayMousePosition(mouseX, mouseY) {
    var header = document.getElementById("header");
    header.innerHTML = "X : " + mouseX + "
Y : " + mouseY;
}

function getMousePosition(e) {
    var mouseX = 0,
        mouseY = 0,
        elmX = 0,
        elmY = 0,
        obj = this;
    //get mouse position on document crossbrowser
    if (!e){e = window.event;}
    if (e.pageX || e.pageY){
        mouseX= e.pageX;
        mouseY = e.pageY;
    } else if (e.clientX || e.clientY){
        mouseX = e.clientX + document.body.scrollLeft
                 + document.documentElement.scrollLeft;
        mouseY = e.clientY + document.body.scrollTop
                 + document.documentElement.scrollTop;
    }
    //get parent element position in document
    if (obj.offsetParent){
        do{
            elmX += obj.offsetLeft;
            elmY += obj.offsetTop;
        } while (obj = obj.offsetParent);
    }

    displayMousePosition(mouseX, mouseY);
    return [mouseX, mouseY];
}

var putPoint = function(e) {
    if(dragging) {
        var offset = $("#signaturePad").offset();
        var mouseX = getMousePosition(e)[0];
        var mouseY = getMousePosition(e)[1];
        context.lineTo(mouseX, mouseY);
        context.stroke();
        context.beginPath();
        context.arc(mouseX, mouseY, radius, 0, Math.PI*2);
        context.fill();
        context.beginPath();
        context.moveTo(mouseX, mouseY);
    }
}

$(document).on("mousedown", "#signaturePad", function(e) {
    dragging = true;
    putPoint(e);
});

$(document).on("mouseup", "#signaturePad", function() {
    dragging = false;
    context.beginPath();
});

$(document).on("mousemove", "#signaturePad", function(e) {
    putPoint(e);
});

And the fiddle if you wanna see it live: https://jsfiddle.net/Cellendhyll/yxguemf0/7/


text:
Q: Работа с регулярными выражениями в vert.x Решил попробовать как vert.x web использует регулярные выражения.Нашел в документации следующее:
You can also capture path parameters when using regular expressions, here's an example:

Route route = router.routeWithRegex(".*foo");

// This regular expression matches paths that start with something like:
// "/foo/bar" - where the "foo" is captured into param0 and the "bar" is captured into
// param1
route.pathRegex("\\/([^\\/]+)\\/([^\\/]+)").handler(routingContext -> {

  String productType = routingContext.request().getParam("param0");
  String productID = routingContext.request().getParam("param1");

  // Do something with them...
});
In the above example, if a request is made to path: /tools/drill123/ then the route will match and productType will receive the value tools and productID will receive the value drill123.

Captures are denoted in regular expressions with capture groups (i.e. surrounding the capture with round brackets)

Не совсем понятны разъяснения разработчиков, а именно 2 метода:
routeWithRegex(".*foo") -что передается данному методу?часть адреса,общая для всех рутов?к примеру у нас есть руты foo/authentification/username/

foo/authentification/accountname/
значит в данный метод передается общая часть рута-foo?
далее pathRegex("\\/([^\\/]+)\\/([^\\/]+)") -этот метод принимает шаблон, по которому будет сопоставлять,что пользователь вводит после foo?
и после
String productType = routingContext.request().getParam("param0");
      String productID = routingContext.request().getParam("param1");

в данном случае,если использовать foo/authentification/username/  то productType=authentification; а productID=username;
я верно понимаю?Потому что эти метода не работают...подскажите пожалуйста кто понял,что в них происходит.


text:
Q: RegOpenKeyEx returning Error 87 aka "INVALID_PARAMETER" I am implementing a recursive registry delete using RegOpenKeyEx, RegDeleteKey and RegEnumKey.
Problem:: Though the code works perfectly fine for Vista x86/x64 and Win 7 x86/x64 but fails on XP for some keys in HKCR
Problem Area:: HKCR\Installer\Products\SomeKey
Error Code:: 87 (INVALID_PARAMETER)
Weird Behaviour:: Deletes the key the moment I open the key using REGEDIT.
Code::
static BOOL RcrsvRegDel( HKEY hKey, LPTSTR lpszSub )
{
BOOL    bRet = TRUE ;
LONG    lRet ;
DWORD   dwSize = MAX_PATH ;
TCHAR   szName[MAX_PATH] ;
TCHAR   szFullKey[MAX_PATH * 2] ;
HKEY    hKeySub = NULL ;
HRESULT hr = NULL ;

do{
    lRet = RegOpenKeyEx( hKey, lpszSub, 0, KEY_ENUMERATE_SUB_KEYS | DELETE, &hKeySub ) ;
    printf("RegOpenKey:: %S :: lRet = %ld\n", lpszSub, lRet) ;
    if( lRet != ERROR_SUCCESS )
    {
        if( lRet == ERROR_FILE_NOT_FOUND )
        {
            bRet = TRUE ;
            break ;
        }
        else
        {
            bRet = FALSE ;
            break ;
        }
    }

    while( ERROR_NO_MORE_ITEMS != (lRet = RegEnumKeyEx(hKeySub, 0, szName, &dwSize, NULL, NULL, NULL, NULL)) )
    {
        bRet = RcrsvRegDel( hKeySub, szName) ;
        if( bRet == FALSE )
            break ;
    }

    if( hKeySub != NULL )
    {
        RegCloseKey(hKeySub) ;
        hKeySub = NULL ;
    }

    lRet = RegDeleteKey( hKey, lpszSub ) ;
    printf("RegDelKey:: %S :: lRet = %ld\n", lpszSub, lRet) ;
    if( lRet == ERROR_SUCCESS )
    {
        bRet = TRUE ;
        break ;
    }
}while(0) ;
return bRet ;
}

Any idea whats goin on?
UPDATE::
I have also tried the samDesired Parameter with following flags
-KEY_READ
-KEY_READ | KEY_WRITE
-KEY_ENUMERATE_SUB_KEYS
-KEY_ENUMERATE_SUB_KEYS | DELETE
Neither of the above flag works :-(

A: Because you can not use RegDeleteKey with handle was opened with flag KEY_WOW64_32KEY.
see http://msdn.microsoft.com/en-us/library/aa384129(v=vs.85).aspx for info.
You have to use RegDeleteKeyEx with same keys.

A: You cannot use RegDeleteKey() to delete a 32-bit key on a 64-bit system.  The documentation says as much:

The RegDeleteKey function cannot be used to access an alternate registry view.

You must use RegDeleteKeyEx() instead.
Try something like this:
typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS)(HANDLE, PBOOL);
extern LPFN_ISWOW64PROCESS fnIsWow64Process;

typedef LONG (WINAPI *LPFN_REGDELETEKEYEX)(HKEY, LPCTSTR, REGSAM, DWORD);
extern LPFN_REGDELETEKEYEX fnRegDeleteKeyEx;

.
BOOL WINAPI IsWow64Process_Impl(HANDLE hHandle, PBOOL Wow64Process);
{
    *Wow64Process = FALSE;
    return TRUE;
}

BOOL WINAPI IsWow64Process_Stub(HANDLE hProcess, PBOOL Wow64Process)
{
    fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress(GetModuleHandle(TEXT("kernel32")), "IsWow64Process");

    if ( NULL == fnIsWow64Process )
        fnIsWow64Process = &IsWow64Process_Impl;

    return fnIsWow64Process(hProcess, Wow64Process);
}

LONG WINAPI RegDeleteKeyEx_Impl(HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, DWORD dwReserved)
{
    return RegDeleteKey( hKey, lpSubKey );
}

LONG WINAPI RegDeleteKeyEx_Stub(HKEY hKey, LPCTSTR lpSubKey, REGSAM samDesired, DWORD dwReserved)
{
    fnRegDeleteKeyEx = (LPFN_REGDELETEKEYEX) GetProcAddress(GetModuleHandle(TEXT("advapi32")),
        #ifdef UNICODE
        "RegDeleteKeyExW"
        #else
        "RegDeleteKeyExA"
        #endif
    );

    if ( NULL == fnRegDeleteKeyEx )
        fnRegDeleteKeyEx = &RegDeleteKeyEx_Impl;

    return fnRegDeleteKeyEx( hKey, lpSubKey, samDesired, dwReserved );
}

LPFN_ISWOW64PROCESS fnIsWow64Process = &IsWow64Process_Stub;
LPFN_REGDELETEKEYEX fnRegDeleteKeyEx = &RegDeleteKeyEx_Stub;

.
BOOL IsWin64()
{
    #if defined(_WIN64)
    return FALSE;  // 64-bit programs run only on Win64
    #elif defined(_WIN32)
    // 32-bit programs run on both 32-bit and 64-bit Windows so must sniff
    BOOL f64 = FALSE;
    return fnIsWow64Process(GetCurrentProcess(), &f64) && f64;
    #else
    return FALSE; // Win64 does not support Win16
    #endif
}

.
static BOOL RcrsvRegDel( HKEY hKey, LPTSTR lpszSub )
{
    BOOL    bRet = TRUE;
    LONG    lRet;
    DWORD   dwSize;
    TCHAR   szName[MAX_PATH+1];
    HKEY    hKeySub = NULL;

    REGSAM Wow64Flag = (IsWin64()) ? KEY_WOW64_32KEY : 0;

    lRet = RegOpenKeyEx( hKey, lpszSub, 0, KEY_ENUMERATE_SUB_KEYS | KEY_SET_VALUE | DELETE | Wow64Flag, &hKeySub ) ;
    printf("RegOpenKey:: %S :: lRet = %ld\n", lpszSub, lRet) ;

    if( lRet != ERROR_SUCCESS )
    {
        if ( lRet != ERROR_FILE_NOT_FOUND )
            bRet = FALSE;
    }
    else
    {
        do
        {
            dwSize = MAX_PATH;
            lRet = RegEnumKeyEx( hKeySub, 0, szName, &dwSize, NULL, NULL, NULL, NULL );

            if ( lRet != ERROR_SUCCESS )
            {
                if ( lRet != ERROR_NO_MORE_ITEMS )
                    bRet = FALSE;

                break;
            }

            bRet = RcrsvRegDel( hKeySub, szName );
            if ( !bRet )
                break;
        }
        while (1);

        RegCloseKey(hKeySub);

        if ( bRet )
        {
            if ( Wow64Flag != 0 )
                lRet = fnRegDeleteKeyEx( hKey, lpszSub, Wow64Flag, 0 );
            else
                lRet = RegDeleteKey( hKey, lpszSub );
            printf("RegDelKey:: %S :: lRet = %ld\n", lpszSub, lRet) ;

            if ( lRet != ERROR_SUCCESS )
                bRet = FALSE;
        }
    }

    return bRet;
}

With that said, consider using RegDeleteTree() or SHDeleteKey() instead.  Let them do the recursion for you.

A: You can do like this. Take the flag as input parameter and pass one flag for the RegOpenKeyEx and again a set of flags when calling the recursive function. I have tried your code and it is working perfectly now, though it is not sure as to what was it that was causing the problem.
static BOOL RcrsvRegDel( HKEY hKey, LPTSTR lpszSub, DWORD dwOpenFlags )
{
    BOOL    bRet = TRUE ;
    LONG    lRet ;
    DWORD   dwSize = MAX_PATH ;
    TCHAR   szName[MAX_PATH] ;
    HKEY    hKeySub = NULL ;
    HRESULT hr = NULL ;
    HANDLE  hProcess = NULL ;
    HANDLE  hToken = NULL ;

    do{
        bRet = SetPrivilege( SE_BACKUP_NAME, TRUE ) ;
        if( bRet == FALSE )
        {
            bRet = FALSE ;
            break ;
        }

        lRet = RegOpenKeyEx( hKey, lpszSub, 0, dwOpenFlags, &hKeySub ) ;
        if( lRet != ERROR_SUCCESS )
        {
            bRet = FALSE ;
            break ;
        }

        while( ERROR_NO_MORE_ITEMS != (lRet = RegEnumKeyEx(hKeySub, 0, szName, &dwSize, NULL,
            NULL, NULL, NULL)) )
            if( !RcrsvRegDel(hKeySub, szName, dwOpenFlags) )
            {
                bRet = FALSE ;
                break ;
            }

        lRet = RegDeleteKey( hKey, lpszSub ) ;
        printf("RegDelKey:: %S :: lRet = %ld\n", lpszSub, lRet) ;
        if( lRet != ERROR_SUCCESS )
        {
            bRet = FALSE ;
            break ;
        }

        if( hKeySub != NULL )
        {
            RegCloseKey(hKeySub) ;
            hKeySub = NULL ;
        }
    }while(0) ;
    return bRet ;
}

static BOOL SetPrivilege( LPCTSTR lpszPrivilege, BOOL bEnablePrivilege )
{
    LUID    luid ;
    BOOL    bRet = TRUE ;
    HANDLE  hToken = NULL ;
    HANDLE  hProcess = NULL ;
    TOKEN_PRIVILEGES tp ;

    do{
        hProcess = GetCurrentProcess() ;
        if( 0 == OpenProcessToken(hProcess, TOKEN_ADJUST_PRIVILEGES, &hToken) )
        {
            bRet = FALSE ;
            break ;
        }

        if( !LookupPrivilegeValue(NULL, lpszPrivilege, &luid) )
        {
            bRet = FALSE ;
            break ;
        }

        tp.PrivilegeCount = 1 ;
        tp.Privileges[0].Luid = luid ;

        if( bEnablePrivilege )
            tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED ;
        else
            tp.Privileges[0].Attributes = 0 ;

        if( !AdjustTokenPrivileges(hToken, FALSE, &tp, sizeof(TOKEN_PRIVILEGES), (PTOKEN_PRIVILEGES)NULL,
            (PDWORD)NULL) )
        {
            bRet = FALSE ;
            break ;
        }

        if( ERROR_NOT_ALL_ASSIGNED == GetLastError() )
        {
            bRet = FALSE ;
            break ;
        }
    }while(0) ;
    if( hToken != NULL ) CloseHandle( hToken ) ;
    return bRet ;
}


text:
Q: Upgrading from Intellij 2020.1.2 to IntelliJ 2021.2.3 Issue when use with Java Play 2.2 I am upgrading my IDE from IntelliJ 2020.1.2 to IntelliJ 2021.2.3.
My project uses a pretty old Java Play library, play_2.10-2.2.0.jar, which by default, it will retrieve messages from its own jar. The below image captures what is present in the play jar, where messages is placed in the root directory.

And when I started to run the application using IntelliJ, instead of retrieving the messages file correctly from .m2 play folder as specified in pom.xml, it gets the IntelliJ runtime jar as shown below.

Which of course, creates the issue. This is an issue previous IDE does not have.
And it seems there is a crash of classpath here.
How can I ensure play jar classpath as always override intellij one? [Though I believe other exception may arise in case if IntelliJ cannot found the message folder properly.
When I use java command, I can always ensure the order by specifying -classpath order. How can I do the same in IntelliJ? Specifying it in Project Structure modules may not be helpful, as it seems IntelliJ runtime jar is never present here.
Is there any solution for solving the issue?
Thanks.

A: After some research, I found that by setting bin/idea.properties in IntelliJ setting.
idea.no.launcher=true

The code work as expected.
Solution are found in Running ScalaTest in IntelliJ removes everything but idea_rt.jar from classpath.
This solution solves the solution as it prevents IntelliJ runtime jar to be executed in IntelliJ executed java program.


text:
Q: How to change the date spacing in pgfcalendar? I did not find any option to change the date spacing in pgfcalendar tutorial can somebody suggest me how do i change the spacing between dates. Here is MWE
 \documentclass[border=4.9mm, multi={tikzpicture}]{standalone}
 %\usepackage[hmargin=2cm,bmargin=3cm,tmargin=4.5cm,centering,a4paper]{geometry}
 \usepackage[utf8]{inputenc}
 \usepackage{xcolor}

 %%in preamble:
 %
 \usepackage{tikz}
 \usetikzlibrary{positioning,calendar}
 \usetikzlibrary{decorations.markings}

 \newcommand{\calrow}[1]{\node[anchor=base east](Mon){\rotatebox{0}{M}};
 \node[base right=of Mon](Tue){\rotatebox{0}{T}}; \node[base right=of Tue](Wed){W};
 \node[base right=of Wed](Thu){T}; \node[base right=of Thu](Fri){F};
 \node[base right=of Fri](Sat){S}; \node[base right=of Sat](Sun){\color{red}S};
 \node[darkgreen,above=of Wed]{\textbf{#1}};}

 \newcommand{\calperiod}[1]{\calendar[dates=\the\year-#1-01 to \the\year-#1-last]
 if(Sunday) [red] \holidays;}

 \newcommand{\holidays}{% holidays in Italy
 if (equals=01-01) [black!50]%
 if (equals=01-06) [black!50]%
 if (equals=04-04) [black!50]%
 if (equals=04-05) [black!50]%
 if (equals=04-25) [black!50]%
 if (equals=05-01) [black!50]%
 if (equals=05-01) [black!50]%
 if (equals=06-02) [black!50]%
 if (equals=08-15) [black!50]%
 if (equals=11-01) [black!50]%
 if (equals=12-08) [black!50]%
 if (equals=12-25) [black!50]%
 if (equals=12-26) [black!50]%
 }

 \colorlet{darkgreen}{green!50!black}
 \year=2017
 \begin{document}
 %%in document:
 %
 \begin{tikzpicture}[every calendar/.style={week list}]
 \sffamily
 \matrix[%
 row 1/.style={darkgreen,node distance=.3ex},%
 row 3/.style={darkgreen,node distance=.3ex},
 row 5/.style={darkgreen,node distance=.3ex},
 row 7/.style={darkgreen,node distance=.3ex},
 column sep=1ex,%
 draw=darkgreen,thick, rectangle=9.5pt,%
 postaction={decorate,decoration={markings,mark=at position 0.61 with
 {\node[fill=white,text=blue,font={\bfseries\Large}] (year) {\the\year};}
 }},
 % year on frame: decorations.markings library
 ]{%

 % first row: week day and month
 \calrow{\color{blue}Arkoi} & \calrow{\color{blue}Thangthang} & \calrow{\color{blue}Therepo} \\
 \calperiod{01} & \calperiod{02} & \calperiod{03} \\[1ex]

 % second row: calendar
 \calrow{\color{blue}Jangmi} & \calrow{\color{blue}Aru} & \calrow{\color{blue}Vosik} \\
 \calperiod{04} & \calperiod{05} & \calperiod{06} \\[1ex]

 % third row: week day and month
 \calrow{\color{blue}Jakhong} & \calrow{\color{blue}Paipai} & \calrow{\color{blue}Chiti} \\
 \calperiod{07} & \calperiod{08} & \calperiod{09} \\[1ex]

 % forth row: calendar
 \calrow{\color{blue}Phere} & \calrow{\color{blue}Phaikuni} & \calrow{\color{blue}Matijong} \\
 \calperiod{10} & \calperiod{11} & \calperiod{12} \\
 };

 \end{tikzpicture}

 \end{document}

A: In section 45 of the PGF manual you'll find your answers. The interesting line in your code is the following:
\begin{tikzpicture}[every calendar/.style={week list}]

You could add some style options there. For example concerning day spacing as day xshift and day yshift (set to 1pt for the following picture).

Or maybe you want to adjust the shifting between months. Use month xshift and month yshift (xshift 10em for the following picture).

Just mess around with it


text:
Q: Integral $ \int_{-\infty}^\infty \frac{e^{ikx}}{x^{3/2}}dx$ Hi I'm trying to solve this integral Fourier Transform
$$
\int_{-\infty}^\infty \frac{e^{ikx}}{x^{3/2}}dx=\sqrt{2\pi|k|}(1+i)  (-1+\text{sgn}(k))
$$
where sgn(k)$=1$ for k>1 and $-1$ for k<1.
I am trying to use residues.  Thanks there is a singularity at $x=0$.  We can try and write
$$
e^{ikx}=\cos x+i\sin x
$$
but I don't think it will help.  IT will be nice to use a contour with $e^{ikx}$ instead.  Thanks

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left( #1 \right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\vphantom{\large A}\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
With $\ds{s \equiv \ic x\quad\imp\quad x = -\ic s = \expo{3\ic\pi/2}s}$:
\begin{align}
\int_{-\infty + \ic 0^{+}}^{\infty + \ic 0^{+}}
{\expo{\ic kx} \over x^{3/2}}\,\dd x&=
\Theta\pars{-k}\int_{-0^{+} - \ic\infty}^{-0^{+} + \ic\infty}
{\expo{\ic k\pars{-\ic s}} \over \pars{\expo{3\ic\pi/2}s}^{3/2}}\,\pars{-\ic\,\dd s}
\\[3mm]&=
\Theta\pars{-k}\pars{-\ic\expo{-9\ic\pi/4}}
\int_{0^{+} -\ic\infty}^{0^{+} + \ic\infty}{\expo{\verts{k}s} \over \expo{-3\ic\pi/2}s^{3/2}}\,\dd s
\\[3mm]&=\Theta\pars{-k}{\root{2} \over 2}\pars{-1 + i}
\int_{0^{+} -\ic\infty}^{0^{+} + \ic\infty}s^{-3/2}\expo{\verts{k}s}\,\dd s\tag{1}
\end{align}

$$
\int_{0^{+} - \ic\infty}^{0^{+} + \ic\infty}s^{-3/2}\expo{\verts{k}s}\,\dd s
=\lim_{\epsilon \to 0^{+}}\pars{%
{\cal I}_{+} + {\cal I}_{-}}\tag{2}
$$

\begin{align}
{\cal I}_{+}&=-\int_{-\infty + \ic\epsilon}^{\ic\epsilon}
\pars{-x}^{-3/2}\expo{-3\ic\pi/2}\expo{\verts{k}x}\,\dd x=
-\ic\int_{-\ic\epsilon}^{\infty - \ic\epsilon}x^{-3/2}\expo{-\verts{k}x}\,\dd x
\\[3mm]&=-2\ic\pars{-\ic\epsilon}^{-1/2}
+ 2\ic\verts{k}\int_{-\ic\epsilon}^{\infty - \ic\epsilon}x^{-1/2}\expo{-\verts{k}x}\,\dd x
\\[3mm]&=\root{2}\pars{-1 + i}\epsilon^{-1/2}
+ 2\ic\verts{k}\int_{-\ic\epsilon}^{\infty - \ic\epsilon}x^{-1/2}\expo{-\verts{k}x}\,\dd x\tag{3}
\end{align}

\begin{align}
{\cal I}_{-}&=-\int_{-\ic\epsilon}^{-\infty - \ic\epsilon}
\pars{-x}^{-3/2}\expo{3\ic\pi/2}\expo{\verts{k}x}\,\dd x=
-\ic\int_{\ic\epsilon}^{\infty + \ic\epsilon}x^{-3/2}\expo{-\verts{k}x}\,\dd x
\\[3mm]&=-2\ic\pars{\ic\epsilon}^{-1/2}
+2\ic\verts{k}\int_{\ic\epsilon}^{\infty + \ic\epsilon}x^{-1/2}\expo{-\verts{k}kx}\,\dd x
\\[3mm]&=\root{2}\pars{1 - i}\epsilon^{-1/2}
+ 2\ic\verts{k}\int_{\ic\epsilon}^{\infty + \ic\epsilon}x^{-1/2}\expo{-\verts{k}x}\,\dd x\tag{4}
\end{align}

We replace $\pars{3}$ and $\pars{4}$ in $\pars{2}$. In the limit
$\epsilon \to 0^{+}$:
\begin{align}
\Theta\pars{-k}\int_{0^{+} - \ic\infty}^{0^{+} + \ic\infty}s^{3/2}\expo{\verts{k}s}\,\dd s
&=\Theta\pars{-k}\bracks{4\ic\verts{k}\int_{0}^{\infty}x^{-1/2}\expo{-\verts{k}x}\,\dd x}
\\[3mm]&=4\ic\root{\verts{k}}\Theta\pars{-k}\
\underbrace{\int_{0}^{\infty}x^{-1/2}\expo{-x}\,\dd x}
_{\ds{\Gamma\pars{1/2} = \root{\pi}}}
\\[3mm]&=\Theta\pars{-k}\bracks{4\ic\root{\pi\verts{k}}}
=-2\ic\bracks{-1 + \sgn\pars{k}}\,\root{\pi\verts{k}}\tag{5}
\end{align}

We'll replace $\pars{5}$ in $\pars{1}$:
  \begin{align}
\color{#00f}{\large\int_{-\infty}^{\infty}{\expo{\ic kx} \over x^{3/2}}\,\dd x}&=
{\root{2} \over 2}\pars{-1 + i}\braces{%
-2\ic\bracks{-1 + \sgn\pars{k}}\,\root{\pi\verts{k}}}
\\[3mm]&=\color{#00f}{\large\root{2\pi\verts{k}}\pars{1 + i}\bracks{-1 + \sgn\pars{k}}}
\end{align}


text:
Q: Graphing sets that contain logical connectives The task it to graph:
$\{(x, y) \in\ \mathbb R^2 | (x^2+y^2 > 1) \implies [(x^2+y^2 \le 2) \land (\lnot (xy=0) \implies |y|=|x|] ) ] \}$
I managed to solve a problem that was similar to this but simpler, I did it by considering all the cases but this one is more complicated and I'm not sure how I should tackle it.

A: As $p \Rightarrow q$ is the same as $\neg p \vee q$ we can write the set as
$$
S = \{(x, y) \in\ \mathbb R^2 \mid (x^2+y^2 \le 1) \vee [(x^2+y^2 \le 2) \land (xy=0 \vee |y|=|x|)] \} \\
= B(1) \cup (B(2) \cap (C_+ \cup C_\times ))
$$
where $B(r)$ is the closed disc with origin $0$ and radius $r$,
$C_+$ are the lines $x=0$ and $y=0$ (the axis cross) and
$C_\times$ are the lines $y = x$ and $y = -x$.


text:
Q: We need PHP for redirects but host is not supported; can Ruby handle PHP URLs? We have recently had to move our charity website to a new (shared) host (www.networksolutions.com/web-hosting/hosting-package-comparison.jsp).
The website specs are: WINDOWS OPERATING SYSTEM, MS SQL 2005, ASP.NET FRAMEWORK 2.0.
We had created URL redirects from our old site which was written in PHP to our new site in ASP which were working fine. Unfortunately the new hosting company does not have PHP as part of the Windows Hosting Package so now none of the redirects work. The Windows hosting does have Ruby on Rails.
Is there any way we can use Ruby to deal with the old PHP URLs so they are redirected to the new pages? Or could there be another way of doing it?
An example of the redirects we had were from:
pfaf.org/leaflets/edible_uses.php TO www.pfaf.org/user/edibleuses.aspx

Any help would be much appreciated

A: If you have a static list of URLs to redirect then no programming language should be needed. You can do redirects in your web server configuration. Both Apache HTTP server and IIS support this.
http://en.wikipedia.org/wiki/URL_redirection#Using_.htaccess_for_redirection
http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/6b855a7a-0884-4508-ba95-079f38c77017.mspx?mfr=true

A: You can't do this. You need a service provider that supports PHP.  PHP pages are processed by the server before they are sent out to the browser.  In order to properly send the PHP pages to the browser, you need a hosting provider that supports PHP.


text:
Q: Converting Byte to Bitmap image I am getting the byte in database but I cannot convert it to bitmap, I got an exception in Parameter. This is what I've done so far.
con.ConnectionString = MyConnectionString;
con.Open();
OdbcCommand cmds = new OdbcCommand("Select ID from try where kalabaw = 5", con);
OdbcDataAdapter da = new OdbcDataAdapter(cmds);
byte[] image = (byte[])cmds.ExecuteScalar();
TypeConverter tc = TypeDescriptor.GetConverter(typeof(Bitmap));
Bitmap bitmap = (Bitmap)tc.ConvertFrom(image);
pictureBox2.Image = bitmap;
con.Close();

A: I totally stole this answer from convert array of bytes to bitmapimage
public BitmapImage ToImage(byte[] array)
{
    using (var ms = new System.IO.MemoryStream(array))
    {
        var image = new BitmapImage();
        image.BeginInit();
        image.CacheOption = BitmapCacheOption.OnLoad; // here
        image.StreamSource = ms;
        image.EndInit();
        return image;
    }
}

A: try the below.  I expect it should work.
byte[] bytes = GetBytesArrayFromDatabase();
using (MemoryStream ms = new MemoryStream(bytes))
{
    ms.Position = 0;
    Bitmap obj = new Bitmap(ms);

    // use the Bitmap object `obj` here
}


text:
Q: How to make summation from 0 to infinity in python? import math
k = 0
def factorial(k):
    if k == 0:
        return 1
    else:
        return k * factorial(k - 1)

formula = (((factorial(4 * k)) * (1103 + 26390 * k)) / ((factorial(k) ** 4)) * (396 ** (4 * k)))

    while k > (1e − 15):
        for k in range ():
        if k == 0:
            return k
        else:
            return k + formula
        print(summation(k, formula))

value_wanted = ((2* math.sqrt(2)) / 9801) * summation(k)
print('1/pi equals' , value_wanted )

This is a code where it tries to make a formula that approximates the value of pi. It gives me an error in the line 'while k > 1e - 15 ' , and I don't know why. I want the code to return the sum of the formula I wrote in the formula variable, with each time changing the k value by 1 until the last term is less than 1e - 15.

A: You can't create a range to infinity -
To keep the computer counting on and on, you could use a while loop:
k = 0
while True:
    k += 1
    ...

However, as you can see, this code has the downside it will  never end, since the computer will be busy counting on and on:
normal numeric methods can't count to "infinity" -  you should take a look on the math concepts of infinity before proceeding with your experiments.
If you want numeric calculations, just choose a "big enough" number. For an algebraic resolution which can_ take infinity into account , check the sympy package.


text:
Q: Property "CDbCriteria.0" is not defined in yii Below is my controller code having the following function;
 public function actionUpdateJob($id)
    {

         if(isset($_GET['id']))
        {
            $id=$_GET['id'];
        }
         var_dump($id);

     $model= UpdateJob::model()->find (array(
                                             'select'=>'posted_by','title','key_skills','condition'=>'id="$id',
                                             'limit'=>1,));
  $params = array('model' => $model,'id' => $id);

  $this->render('update',$params);

    }

While executing, I am getting error
Property "CDbCriteria.0" is not defined .

A: I think your select => has to be array with ['posted_by', 'title', 'key_skills']
And your condition is wrong. Use
id=:id and in params add: ..., ':id' => $id

A: Change:
'condition'=>'id="$id',

To:
'condition'=>'id="$id"',

You have missed quotation mark.


text:
Q: Is the number of possible N-Dimensional subspaces always 1 when working in N-Dimensional ambient space? For instance, if I have two or more $2$D vectors in $2$D ambient space, will their subspace always be defined as the entire cartesian plane given that none of the vectors are colinear nor zero vectors?
Additionally, if I had $N$ or more ND vectors in ND ambient space, would the number of possible subspaces still only remain 1, that being the entire ambient space, again, given that none of the vectors are colinear or zeros


text:
Q: How does UIWebView implement pagination? I need to make some customization of my ePub book. And I wonder is it possible to understand how does UIWebView divides itself on pages? I know ho to make this programmatically I wonder how it is implemented inside UIWebView.
Perhaps it adds some tags ("div" or may be smth else) to achieve such effect?
I know that it is not the open source component but I only nead any suggestions to make my further decisions.
Hear I put an image what I mean.

A: arrHtmlPage=[[NSMutableArray alloc] initWithObjects:@"2",@"3",@"5",@"6",@"8",@"9",@"11",@"13",nil];

NSBundle *bundle = [NSBundle mainBundle];

NSString *htmlTemplateLink = [bundle pathForResource:@"2" ofType:@"htm"];

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:htmlTemplateLink]];

wview=[[UIWebView alloc]initWithFrame:CGRectMake(0, 0, 768, 940)];
wview.scalesPageToFit = YES;
[wview loadRequest:request];
wview.delegate=self;

wview.userInteractionEnabled=YES;

[self.view addSubview:wview];

And do this also
typedef NS_ENUM(NSInteger, UIWebPaginationMode) {
UIWebPaginationModeUnpaginated,
UIWebPaginationModeLeftToRight,
UIWebPaginationModeTopToBottom,
UIWebPaginationModeBottomToTop,
UIWebPaginationModeRightToLeft
}


text:
Q: if timestamp is expired by comparing that to current timestamp I have a column(cradit_end_date) that it specifies a product is expire or not.
this column have two states :
0000-00-00 00:00:0 <= this means this product has no expiration date.
A date (ex: 2014-10-24 10:00:00) <= this means this product has a expiration date (here almost a month later).
now, how can I get products that are both no expiration date and is not expired ?
Is it possible with PHP or SQL?
(I am using mysql).
$result_coupons = mysql_query("select id,title,pic,price,off,fake_sell,cradit_end_date from coupons  where
confirm=2 and status=1 and
shop_id=$row->id ORDER BY id DESC limit 1");

A: You could check for multiple states in the single column using an OR operator.
 ...
 WHERE (cradit_end_date = '0000-00-00 00:00:00' OR cradit_end_date > NOW())
 ...


text:
Q: Getting name from hibernate for class I have a project with supporting XML-config. Now we wanna add hibernate config for entities via annotation. Seems it possible and works (correct me if I am mistaken). The issue is that our system
private String entityName() {
    String name = null;
    try {
        String longName = getDaoFactory().getSessionFactory().getClassMetadata(entityClass).getEntityName();
        name = longName.substring(longName.lastIndexOf(".") + 1);
    } catch (Exception ex) {
        log.error("Exception getting name from hibernate for class: " + entityClass);
        name = null;
    }
    return name;
}

This method works well for entities with xml-config, but how to get a name for an entity which is configurated by annotation?
Thank you in advance for any recommendation and suggestion :)
UPD:
from init session factory method:
Configuration configuration = new Configuration();
configuration.addResource("resources/administrator/queries.hbm.xml");
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration
        .getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
setSessionFactory(sessionFactory);
return configuration;

A: I created a session Factory like this.
public static SessionFactory buildSessionFactoryFromAnnotatedClasses(){
    StandardServiceRegistry standardRegistry =
        new StandardServiceRegistryBuilder().applySettings(// pass org.hibernate.cfg.Configuration object here)
            .getProperties()).build(); // Configuration object has properties

    MetadataSources sources = new MetadataSources(standardRegistry);
    sources.addAnnotatedClass(MyClass.class);// MyClass is your java annotated class
    Metadata metaData = sources.getMetadataBuilder().build();
    return metaData.getSessionFactoryBuilder().build();
  }


text:
Q: Linq To XML delete document from xml file I have an xml file. Here is a short part:
<?xml version="1.0" encoding="utf-8" standalone="yes"?>
<documents>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1001</nr>
        </head>
        <body>
            <name>Mark Sweden</name>
            <cf>AAABBBCCC</cf>
        </body>
    </document>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1002</nr>
        </head>
        <body>
            <name>John Car</name>
            <cf>AAABBBVVV</cf>
        </body>
    </document>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1004</nr>
        </head>
        <body>
            <name>Mark Sweden</name>
            <cf>AAABBBCCC</cf>
        </body>
    </document>
</documents>

I would like to delete, using Linq to XML, every single document that has a particular "cf" value.
For example if "cf" value is AAABBBCCC first and third documents would be deleted.
Thank you.
UPDATE
My problem was to get the documents to delete (the linq query I wrote was wrong). Robert McKee pointed me to the right direction.
My solution is:
var Delete = (from x in doc.Descendants(document)
where x.Descendants("cf").First().Value = "AAABBBCCC"
select x);

Delete.Remove();

A: Try this code: it should be almost auto-explicative, but let me know any doubts
var root = XElement.Load(myPath);
List<XElement> deleteMe = new List<XElement>();
foreach (var item in root.Elements())
{
    if (item.Element("body").Element("cf").Value.Equals(myCf))
    {
        deleteMe.Add(item);
    }
}
Console.WriteLine("Deleting: " + String.Join(",",deleteMe.Select(x => x.Element("head").Element("nr").Value)));
Console.ReadKey();
foreach (var item in deleteMe)
{
    item.Remove();
}
root.Save(myPath2);

A: Using XDocument, you can generate a copy of your document without the undesired elements, and then overwrite the original file:
string documentPath;
string undesiredPattern = "AAABBBCCC";
XDocument xdoc = XDocument.Load(documentPath);
//Or, if your document is already loaded on a string, use XDocument.Parse(string)
XElement root = xdoc.Root;

IEnumerable<XElement> desiredElements =
 root.
 Elements().
 Where(x=>!x.Element("body").Element("cf").Value.Equals(undesiredPattern));

XDocument newDoc = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
XElement newRoot = new XElement("documents");
foreach(XElement xe in desiredElements)
{
  newRoot.Add(xe);
}
newDoc.Add(newRoot);
newDoc.Save(documentPath);

Edit:
Other way, more direct (if you want to load from file, instead of XDocument.Parse use the XDocument.Load and XDocument.Save to save afterwards, as the piece above):
string document = "your xml";
string undesiredPattern = "AAABBBCCC";
XDocument xdoc = XDocument.Parse(document);

xdoc.Root.Elements().Where(x=>
  x.Element("body").
  Element("cf").Value.
  Equals(undesiredPattern)).Remove();

A: var xml=@"<?xml version=""1.0"" encoding=""utf-8"" standalone=""yes""?>
<documents>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1001</nr>
        </head>
        <body>
            <name>Mark Sweden</name>
            <cf>AAABBBCCC</cf>
        </body>
    </document>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1002</nr>
        </head>
        <body>
            <name>John Car</name>
            <cf>AAABBBVVV</cf>
        </body>
    </document>
    <document>
        <head>
            <date>01/01/2015</date>
            <nr>1004</nr>
        </head>
        <body>
            <name>Mark Sweden</name>
            <cf>AAABBBCCC</cf>
        </body>
    </document>
</documents>";
var doc = XDocument.Parse(xml);
foreach(var node in var node in doc.Descendants("document").Where(d=>d.Descendants("cf").First().Value=="AAABBBCCC").ToArray())
{
    node.Remove();
}


text:
Q: Unnexpected Behaviour From Software UART On ATtiny84A AVR I am trying to implement a software UART for the ATtiny84A, as it does not come with a UART out of the box.
The following is an example of the UART TX:
DDRB  |= (1 << DDB0); // Set the pin on Port B0 to be an output for UART TX.
PORTB |= (1 << PORTB0); // Default the pin to HIGH for the idle high of the UART

void uart_tx(uint8_t *transmit_data)
{
    uint8_t string_length = strlen(transmit_data);
    for (uint_8t character = 0; character < string_length; character++) // Separate the string into characters.
    {
        PORTB &=~ (1 << PORTB0); // Send a start bit by bringing the UART TX low.
        timer_delay(); // Extra function that generates a delay to generate the appropriate baudrate.

        for (uint8_t character_bit = 0; character_bit < 8; character_bit++) // Separate the character into bits.
        {
            if ((1 << character_bit) & transmit_data[character]) //
            {
                PORTB |= (1 << PORTB0); // Transmit a logical one
                timer_delay(); // Aforementioned delay
            } else {
                PORTB &=~ (1 << PORTB0); // Transmit a logical 0
                timer_delay(); // Aforementioned delay
            }
        }
        PORTB |= (1 << PORTB0); // Transmit a stop bit by bringing UART tx High.
        timer_delay(); // Aforementioned delay
    }
}

uart_tx("ab");

What I would expect as an output is
0100001101 0010001101

however, what I am actually getting is shown in the following

which in terms of bits is
00001000011010010001101...

Taken as a whole, it has little meaning, but upon closer inspection, parts of it are correct. What is wrong about it is the 000 inserted at the beginning, so a more accurate way of looking at it is
?...000 0100001101 0010001101
    ^ start bit?

More specifically: The last two frames are accurate, but mystery data is being inserted at the beginning.
What is very strange, is that If I implement this in a regular C program, it works as I would expect:
#include <stdio.h>
#include <string.h>

void uart_tx(unsigned char *transmit_data)
{
    for (unsigned char character = 0; character < strlen(transmit_data); character++)
    {
        printf("0");
        for (unsigned char character_bit = 0; character_bit < 8; character_bit++)
        {
            if ((1 << character_bit) & transmit_data[character])
            {
                printf("1");
            } else
              {
                printf("0");
            }
        }
        printf("1");
        printf(" ");
    }
}

uart_tx("ab");

outputs
0100001101 0010001101

as expected, so I am very perplexed as to what is going on here.
EDIT: Here is the delay related code
// Initializing the timer
TCCR0A  |=  (1 << WGM01);
TIMSK0  |=  (1 << OCIE0A);
OCR0A   =   52;

// timer function
void timer_delay(void)
{
    TCNT0   =   0;  // Reset the time
    TCCR0B  |=  (1 << CS01); // start the timer with /8 prescaler.
    while (!(TIFR0 & (1 << OCF0A)));    // Wait until the compare interrupt flag is set
    TIFR0   &=~ (1 << OCF0A);   // Reset the Compare flag
    TCCR0B  &=~ (1 << CS01);    // Stop the timer.
}
```

A: The timer interrupt-flag is reset incorrectly. An interrupt flag is reset by writing a 1 to it, and not a 0.
TIFR0 &=~ (1 << OCF0A);
       ^ Incorrect

It should be
TIFR0 |= (1 << OCF0A);

See Section 11.9.7 of the ATtiny24A/44A/84A datasheet (2020 version - Revision A) listed here

...OCF0A is cleared by hardware when executing the cor-
responding interrupt handling vector. Alternatively, OCF0A is cleared by writing a logic one to
the flag...


text:
Q: Insert Data from a Table in another DataBase - Sql Server INSERT INTO CustomersNew (CustomerName, Country)
SELECT CustomerName, Country FROM CustomersOld
WHERE status='N';

In above case we can insert customer data to the table "CustomersNew" which are exist in the table CustomersOld.
These two tables are in the same database
How to perform the same operation if these tables resides in two databases.
ex
table "CustomersNew" is in DB_new.
table "CustomersOld" is in DB_old.
These two databases are in two different locations....
how we access with security..(data bases have passwords......)

A: INSERT INTO DB_new.dbo.CustomersNew(CustomerName, Country)
SELECT CustomerName, Country FROM DB_old.dbo.CustomersOld WHERE status='N'


text:
Q: TextView text not properly displayed I use auto layout. I have a TextView with other views. When keyboard appears, part of the TextView is hidden behind keyboard. So, I decrease its height by decreasing its bottom constraint(with its superview's bottom) so that user can scroll and see whole text.
But issue is when keyboard disappears, only half of the TextView's text are visible . But when I tap on it, it shows whole text.
How it looks normally :

How it looks when keyboard has appeared :

How it looks when keyboard has disappeared :

Now, if I tap on TextView it looks same as first image. i.e. Complete text is visible :

Code : self.messageView is TextView.
// Called when keyboard is going to be displayed
- (void)keyboardWillShow:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];

    // get animation info from userInfo
    NSTimeInterval animationDuration;
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];

    // Save constant to set back later
    self.bottomConstant = self.noticeMessageBottom.constant;

    // Change bottom space constraint's constant
    self.noticeMessageBottom.constant = keyboardFrame.size.height + 8.0f;

    [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        [self.messageView setNeedsLayout];
        [self.messageView layoutIfNeeded];

        [self.view setNeedsLayout];
        [self.view layoutIfNeeded];
    } completion:nil];

    [self.messageView flashScrollIndicators];
}

// Called when keyboard is going to be hidden
- (void)keyboardWillHide:(NSNotification*)aNotification
{
    NSDictionary* info = [aNotification userInfo];

    // get animation info from userInfo
    NSTimeInterval animationDuration;
    CGRect keyboardFrame;
    [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&animationDuration];
    [[info objectForKey:UIKeyboardFrameBeginUserInfoKey] getValue:&keyboardFrame];

    // Reset contentOffset
    self.messageView.contentOffset = CGPointZero;

    // Change bottom space constraint's constant
    self.noticeMessageBottom.constant = self.bottomConstant;

    [UIView animateWithDuration:animationDuration delay:0.0 options:UIViewAnimationOptionCurveEaseOut animations:^{

        [self.messageView setNeedsLayout];
        [self.messageView layoutIfNeeded];

        [self.view setNeedsLayout];
        [self.view layoutIfNeeded];
    } completion:nil];
}

Note : This happens only if TextView's contentOffset is (0,0).i.e user has not scrolled it or scrolled back to top. If user has scrolled it and contentOffset is not (0,0) then it works fine.

A: I just unchecked scroll enabled property of TextView in storyboard and its not giving that issue any more.


text:
Q: The value of the variable changes after onSaveInstanceState is called As far as I know onSaveInstanceState is called every time the app goes to background. If so then the app might still execute some code while it is in the background. So, I'm wondering what will happen if the state of variable x will be saved during onSaveInstanceState, the app will still continue execution in the background and will change the value of the variable x. A little bit later the process will be killed and the activity will be recreated (when the user will come back to app).
So, what would be the value of x? It seems that it will have an old value(saved during onSaveInstanceState), but what will happen to the new value, will it be lost?

A: First of all the variables as you call them are not automatically saved you need to put them in a Bundle, similar to when you add Extras to an Intent.
And retrieve those values taking them out of the Bundle in the method onRestoreInstanceState. So the value of a certain variable, when restored would be the one you set in the Bundle if you later change that value and not put it on the Bundle it will be lost.
Also please take into account that this background execution as you called it, it is not so. It is just a minimal code execution to save the state of your activity not an actual background execution


text:
Q: Bootstrap Image Sizing and Centering I am new to bootstrap and I am having an issue trying to position an Image on the page.  I am trying to use bootstrap grid to position the image in the center of the page.  I am familiar with html5 and I know there are other ways of centering the image;however,I was wondering if this can be done using bootstrap's grid system.  The reason for this example, is that I have other image position things I would like to use bootstrap for.
When I run the example below on a Windows 8 desktop or iPad the image is extremely small(i.e. almost like an icon) and resides in the upper left corner; however, when I run this on my Nexus 5 the image is sized correctly and is centered. I have included some sample html code of what I am using.
Again, I am some what new to bootstrap so it could be something simple.  Any input or advice is greatly appreciated
Thanks in advance for your help
<!DOCTYPE html>

<meta charset="utf-8">
<title>Autoroute Login</title>
<meta name="viewport" content="width=device-width,
 height=device-height,initial-scale=1.0">
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/
       3.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="http://twitter.github.com/bootstrap/assets/
         css/bootstrap-responsive.css">

A: Bootstrap's column system is laid out on a base of twelve. For example, if you wanted two columns of equal width,  you would have them both be .col-sm-6 because two columns with widths of 6 equals twelve. Likewise, you could have three equal .col-md-4 columns.
Bootstrap floats columns to the left by default, but also allows you to offset them by a specific number of columns: .col-md-offset-4
So, if you would like to have a Bootstrap div that is always centered, you can do that by setting it's width to any even number, subtracting that number from 12, and setting the offset to that number. So for a centered .col-2, you would give an offset of 5 because 5+5+2=12. For a centered .col-4, you would give an offset of 4 because 4+4+4=12. You need to account for the left (empty) columns, the center div with x columns width, and the right (empty) columns.
JSFiddle


text:
Q: Postscript driver for Android? I am looking to program an Android app which is simply a print driver that converts a file to postscript and/or PCL and then sends it to a network printer.  My first concern is printing pdf files.  Do any of you know of a Java (or I guess I could use C/C++ and JNI) library for converting pdf to PS/PCL?  The key issue here is that I can't use any of the built-in Java print libraries, since those aren't included on Android.
I don't have any ambition to sell the app, or distribute it under my name, or anything of that nature, so if you can point me to some open-source converters which I can use directly, that would be great.

A: The "send to a network printer" part of this question is a duplicate of existing Stack Overflow questions, Printing API in Android and Android Printing API on Galaxy Tab.
The answer, thanks to Horcrux7 in August 2011:
Currently there are some bad working third party apps. Nothing is a professional solution.... All which need a printing API in Android should vote for it.

*

*http://code.google.com/p/android/issues/detail?id=1148

*http://code.google.com/p/android/issues/detail?id=13275


text:
Q: How to find time difference between 2 records in SQL Server I have written a query joining multiple tables and looking out for assistance to find time difference between 2 rows of same identifier.
Example: Row num is an additional column that I have added to explain better
Row num     NodeID  Caption     VolumeID    Caption     DateTime
1.          2245    SERVERNAME  6545        D:\RAID     10/10/16 10:25 PM
2.          2245    SERVERNAME  6545        D:\RAID     10/10/16 10:10 PM
3.          2245    SERVERNAME  6545        D:\RAID     10/10/16 9:55 PM
4.          2245    SERVERNAME  6545        D:\RAID     10/10/16 9:40 PM
5.          2245    SERVERNAME  6545        D:\RAID     10/10/16 9:25 PM
6.          2245    SERVERNAME  6545        D:\RAID     10/10/16 9:25 PM
7.          2245    SERVERNAME  7710        D:\AFS\G    10/10/16 10:25 PM
8.          2245    SERVERNAME  7710        D:\AFS\G    10/10/16 10:10 PM
9.          2245    SERVERNAME  7710        D:\AFS\G    10/10/16 9:55 PM
10.         2245    SERVERNAME  7710        D:\AFS\G    10/10/16 9:40 PM
11.         2245    SERVERNAME  7710        D:\AFS\G    10/10/16 9:25 PM
12.         2245    SERVERNAME  7711        D:\AFS\G    10/10/16 10:25 PM
13.         2245    SERVERNAME  7711        D:\AFS\G    10/10/16 10:10 PM
14.         2245    SERVERNAME  7711        D:\AFS\G    10/10/16 9:55 PM
15.         2245    SERVERNAME  7711        D:\AFS\G    10/10/16 9:40 PM
16.         2245    SERVERNAME  7711        D:\AFS\G    10/10/16 9:25 PM
17.         2245    SERVERNAME  7712        D:\AFS\C    10/10/16 10:25 PM
18.         2245    SERVERNAME  7712        D:\AFS\C    10/10/16 10:10 PM
19.         2245    SERVERNAME  7712        D:\AFS\C    10/10/16 9:55 PM
20.         2245    SERVERNAME  7712        D:\AFS\C    10/10/16 9:40 PM
21.         2245    SERVERNAME  7712        D:\AFS\C    10/10/16 9:25 PM
22.         2245    SERVERNAME  7713        D:\AFS\C    10/10/16 10:25 PM
23.         2245    SERVERNAME  7713        D:\AFS\C    10/10/16 10:10 PM
24.         2245    SERVERNAME  7713        D:\AFS\C    10/10/16 9:55 PM
25.         2245    SERVERNAME  7713        D:\AFS\C    10/10/16 9:25 PM
26.         2245    SERVERNAME  7713        D:\AFS\C    10/10/16 9:40 PM

in the above data sample, identifier is Nodeid and volumeid.
Whenever identifier matches, than record with latest timestamp and the record one before that should be compared to determine the difference.
in above example query should be able to match only row number 1 and 2 for nodeid 2245 and volumeid 6545 and output should be 15 mins
Similarly, for nodeid 2245 and volumeid 7710, row number 7 and 8 should be used for calculation.
How can I do this? I tried using with CTE expression but was unable to do. I also tried with sub query but failed.
Can someone help me here to write the query.
Query that I tried:
WITH rows AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY [Operations-Orion].[dbo].[VolumeUsage].Datetime) AS rn
    FROM [Operations-Orion].[dbo].[VolumeUsage]
)
SELECT  DATEDIFF(second, mc.DateTime, mp.Datetime)
FROM    [Operations-Orion].[dbo].[VolumeUsage] mc
JOIN    [Operations-Orion].[dbo].[VolumeUsage] mp
ON      mc.rn = mp.rn

This throws an error:

Msg 207, Level 16, State 1, Line 10
  Invalid column name 'rn'.
  Msg 207, Level 16, State 1, Line 10
  Invalid column name 'rn'.

A: You must use cte in your query instead of main table:
WITH CTEViewName AS
(
    SELECT *, ROW_NUMBER() OVER (ORDER BY [Operations-Orion].[dbo].[VolumeUsage].Datetime) AS rn
    FROM [Operations-Orion].[dbo].[VolumeUsage]
)
SELECT  DATEDIFF(second, mc.DateTime, mp.Datetime)
FROM    CTEViewName mc
JOIN    CTEViewName mp
ON      mc.rn = mp.rn + 1

A: use the below script .
;WITH  cte_1
as
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY NodeID,VolumeID ORDER BY [Datetime] desc) AS rn
    FROM #t
)
SELECT A.NodeID,A.Caption,A.VolumeID,A.Caption1,A.[DateTime]
,CASE DATEDIFF(HOUR, B.[DateTime], A.[DateTime])
                    WHEN 0 THEN CAST(DATEDIFF(MINUTE, B.[DateTime], A.[DateTime]) AS VARCHAR(10))
                    ELSE CAST(60 - DATEPART(MINUTE, B.[DateTime]) AS VARCHAR(10)) +
                        REPLICATE(',60', DATEDIFF(HOUR, B.[DateTime], A.[DateTime]) - 1) +
                        + ',' + CAST(DATEPART(MINUTE, A.[DateTime]) AS VARCHAR(10))
                END TimeDifference
FROM cte_1 A
 join cte_1 B
  on A.rn=b.rn-1
   AND A.NodeID=B.NodeID AND A.VolumeID=B.VolumeID
WHERE B.rn=2 --if you dont want to limit ,comment this line

Sample Output :

IF you wanted to display all the rows ,but need the time difference only for the first two rows,add an extra case statement like the below script.
;WITH  cte_1
as
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY NodeID,VolumeID ORDER BY [Datetime] desc) AS rn
    FROM #t
)
SELECT A.NodeID,A.Caption,A.VolumeID,A.Caption1,A.[DateTime]
,CASE WHEN b.rn=2 THEN CASE DATEDIFF(HOUR, B.[DateTime], A.[DateTime])
                    WHEN 0 THEN CAST(DATEDIFF(MINUTE, B.[DateTime], A.[DateTime]) AS VARCHAR(10))
                    ELSE CAST(60 - DATEPART(MINUTE, B.[DateTime]) AS VARCHAR(10)) +
                        REPLICATE(',60', DATEDIFF(HOUR, B.[DateTime], A.[DateTime]) - 1) +
                        + ',' + CAST(DATEPART(MINUTE, A.[DateTime]) AS VARCHAR(10))
                END ELSE NULL END TimeDifference
FROM cte_1 A
 join cte_1 B
  on A.rn=b.rn-1
   AND A.NodeID=B.NodeID AND A.VolumeID=B.VolumeID

Sample Output :


text:
Q: Get Android user defined device name by code I want to get my android phone device/phone name that defined by user. I already know android.os.Build.MODEL which return exact model of my device, But I want to get the name that sate by user or owner of the phone.

A: The problem is that not all Android devices have such a custom name, therefor there is no direct way of getting it reliable.
What I have experienced (at least for Samsung) is that the user-defined name is also used for the WifiP2pDevice name: http://developer.android.com/reference/android/net/wifi/p2p/WifiP2pDevice.html
Some manufacturers also use it as the default Bluetooth-Name or as the Hostname, anyway you can check what property is used for your phone by using dumpsys in an adb shell
dumpsys | grep 'My new phone'

A: String userDeviceName = Settings.Global.getString(getContentResolver(), Settings.Global.DEVICE_NAME);
if(userDeviceName == null)
    userDeviceName = Settings.Secure.getString(getContentResolver(), "bluetooth_name");

https://stackoverflow.com/a/66651458/4531734

A: Settings.Global.getString(getContentResolver(), "device_name");


text:
Q: SemanticImport adds garbage characters to key name I want to import a csv to a dataset. This exact dataset successfully imported on a PC, but on a Mac one of the columns has garbage characters added to the key (see below example). I don't believe these characters are in the csv--regular "Import" doesn't show them. At least one other csv SemanticImport doesn't do this. If I rename the key, the characters remain. If I delete the leftmost column, the new key for the leftmost column gets these characters. So:

*

*What is causing this?

*Can I systematically avoid this issue? (I can probably think of a bandaid for this situation, but if this happens with any frequency this is a terrible roadblock to my workflow.)


text:
Q: Math: How to convert a left-handed transformation matrix to a right handed one I have a transformation matrix (rotation + translation) which was constructed in a right-handed coordinate system where X is right, Y is up and Z is into the screen.
If I want to apply this same transformation but in a left-handed coordinate system where X is right, Y is down and Z is out of the screen (is this left handed?) what alterations should I make to the existing transformation matrix.
Thanks

A:
a right-handed coordinate system where X is right, Y is up and Z is into the screen

Then it's a left-handed coordinate system: X is the thumb, Y is the forefinger, Z is the middle-finger. Your right hand should not be able to do what you describe without breaking a few bones :-p

a left-handed coordinate system where X is right, Y is down and Z is out of the screen

This one is indeed a left-handed coordinate system too.
As for the transformation linking these two, this is a simple 180° rotation around the X axis (beware of the wrist sprain while trying this one), which expresses as the following 3x3 matrix:
(1  0  0)
(0 -1  0)
(0  0 -1)

You can pre-multiply your transformation with this one!
Hope this helps!

A: @mbrenon's answer is correct. Just to be clear.
Check my answer on this question Changing a matrix from right-handed to left-handed coordinate system
As for your question, let M_ori be transformation matrix you have, M_dst is what you want in target corrdinate system.


text:
Q: Missing keyword ora -00905 I am getting the error indicated in the question title when I execute the following query:
select mantas_stg.NY_EGIFTS_TRANS_STG.*,
CASE WHEN  MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_CURR != 'USD' THEN
CASE WHEN  MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_CURR != 'USD' AND MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_LOCAL_CURR != 'USD'  THEN
MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT = MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT * 100
END
END
from mantas_stg.NY_EGIFTS_TRANS_STG;

Can anyone tell me why the above query is failing at
MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT = MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT * 100

A: The line below in your nested case is probably the issue:
THEN MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT = MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT * 100
You're trying to assign a value to MANTAS_STG.NY_EGIFTS_TRANS_STG.FUNDS_ORIG_AMT in a select statement which isn't allowed
If your goal is to update the value in that column of a particular record you should be using an update statement.

A: One doesn't assign values in a case expression.  I think you want something like this:
select s.*,
       (CASE WHEN s.FUNDS_ORIG_CURR <> 'USD' AND s.FUNDS_LOCAL_CURR <> 'USD'
             THEN s.FUNDS_ORIG_AMT * 100
             ELSE s.FUNDS_ORIG_AMT
        END) as new_funds_orig_amt
from mantas_stg.NY_EGIFTS_TRANS_STG s;

Indentation and table aliases sure make the query easier to read.