text:
Q: Using GroupBy with Concat only returns first group values I have some test code with GroupBy which works as expected...
Code
var sw = Stopwatch.StartNew();
int groupSize = 5;

var coreObservable = Observable
    .Range(1, 20)
    .Select((x, idx) => new { x, idx })
    .GroupBy(x => x.idx / groupSize, x => x.x)
    .Select(x => x.ToList())
    .Replay()
    .RefCount();

coreObservable.Subscribe(
    x => x.Subscribe(y => Console.WriteLine("Event raised [Books: {0}, Timestamp: {1}]", string.Join("|", y), sw.Elapsed)),
    () => Console.WriteLine("Subcription closed"));

coreObservable.Wait(); // blocking until observable completes

Output
Event raised [Values: 1|2|3|4|5, Timestamp: 00:00:00.3224002]
Event raised [Values: 6|7|8|9|10, Timestamp: 00:00:00.3268353]
Event raised [Values: 11|12|13|14|15, Timestamp: 00:00:00.3270101]
Event raised [Values: 16|17|18|19|20, Timestamp: 00:00:00.3270803]
Subcription closed

The problem is when I try to use Concat with this expression...
Code
var sw = Stopwatch.StartNew();
int groupSize = 5;

var coreObservable = Observable
    .Range(1, 20)
    .Select((x, idx) => new { x, idx })
    .GroupBy(x => x.idx / groupSize, x => x.x)
    .Select(x => x.ToList())
    .Concat() // JUST ADDED THIS
    .Replay()
    .RefCount();

coreObservable.Subscribe(
    x => Console.WriteLine("Event raised [Values: {0}, Timestamp: {1}]", string.Join("|", x), sw.Elapsed),
    () => Console.WriteLine("Subcription closed"));

coreObservable.Wait(); // blocking until observable completes

Output
Event raised [Values: 1|2|3|4|5, Timestamp: 00:00:00.2728469]
Event raised [Values: , Timestamp: 00:00:00.2791311]
Event raised [Values: , Timestamp: 00:00:00.2793720]
Event raised [Values: , Timestamp: 00:00:00.2794617]
Subcription closed

Notice only the first set of values was exposed.
The reason I am using GroupBy and not Buffer, is because I am trying to use it as a way to create max size chunks for a data feed which comes in bursts. The original observable will probably be arrays of items, where I want to split the arrays when there are too many items in a single event.
The reason I want to use Concat is because I want to be able to create delays between the array events, like many people have recommended here.

A: Replace Concat() with Merge(), and it works correctly.
I believe the reason for your issue, is that Concat() will not begin listening to the next sequence until the current one completes.
Concat diagram:
s1 --0--1--2-|
s2           -5--6--7--8--|
r  --0--1--2--5--6--7--8--|

While Merge() subscribes to all child sequences at the same time, and publishes a value whenever any child publishes a value.
Merge diagram:
s1 --1--1--1--|
s2 ---2---2---2|
r  --12-1-21--2|

So in your case, the Concat() subscribes to the first IObservable<IList<int>> from the Select(x => x.ToList()), publishes values until it completes, then subscribes to the next sequence.  GroupBy() will create a new IGroupedObservable stream for each group that it finds, however all of the IGroupedObservables will complete at the same time: When the underlying stream completes.
So Concat() listens to the first stream until it completes, but when the first stream completes, all the others have also completed (Since they are all actually the same sequence, just split by key), so there are no values for it to publish for the following sequences.
All diagrams were borrowed from here which is a fantastic resource for Rx, and I highly recommend you look there for any questions about how the various operators work.

A: Your problem can reduce to something like this, which may be simpler to think on:
var sw = Stopwatch.StartNew();
var subject = new Subject<int>();

var o2 = subject.Where(i => i % 2 == 0).ToList();
var o3 = subject.Where(i => i % 3 == 0).ToList();
var o4 = subject.Where(i => i % 4 == 0).ToList();

var c = Observable.Concat(o2, o3, o4)
//      .Replay()
//      .RefCount()
//.Replay().RefCount() has no impact here.
    ;

c.Subscribe(
    x => Console.WriteLine("Event raised [Values: {0}, Timestamp: {1}]", string.Join("|", x), sw.Elapsed),
    () => Console.WriteLine("Subcription closed"));

for(int i = 0; i < 6; i++)
    subject.OnNext(i);
subject.OnCompleted();

Output:
Event raised [Values: 0|2|4, Timestamp: 00:00:00.0002278]
Event raised [Values: , Timestamp: 00:00:00.0002850]
Event raised [Values: , Timestamp: 00:00:00.0003049]
Subcription closed

If you were to marble diagram these, it would like this:
s   : 012345|
o2  : ------(024)|
o3  : ------(03) |
o4  : ------(04) |

cOut: ------(024)|
cSub: (So2)------(So3)(So4)

cSub shows when c subscribes to child observables. cOut shows c's output.
So2 means subscribe to o2, So3 means subscribe to o3, etc..

Concat subscribes to the first observable passed to it, then only subscribes to the subsequent observable when the current one is complete. In our case, ToList doesn't omit anything until the source completes, when it dumps the whole list. So o2, o3, o4 all complete simultaneously, but c is only subscribed to o2. After o2 completes, it tries subscribing to the others, but they're already done.
As for how to fix it, Merge would work, but I'm guessing you want to process group 1 before group 2, which Merge would break.


text:
Q: Why can't I save a document when I click on Save in Word 2010? I use Word 2010, and when I click Save or Save As..., nothing happens.  The dialog doesn't even pop up.  It's strange because I can create a copy of an existing document and save it just fine.

A: It turns out that the problem is related to High Contrast Mode.  Who would have possibly thought?  I use High Contrast Mode #2 in Windows, and when I tried to save the document, nothing happened.  When I switched back to regular mode (Left Alt + Shift + Prt Scr), the save as dialog popped up just fine as if nothing was a problem.
I got some help from an answer over here:
https://answers.microsoft.com/en-us/office/forum/office_2010-office_install/save-as-dialog-box-does-not-appear-cannot-save/62f0940b-5ba3-4b52-89c6-569d29a4debb?page=2
As I investigate further, I think it has something to do also with Edge having its dark theme enabled.  High Contrast Mode does some funky stuff, and Windows is smart enough not to invert dark mode on Edge when High Contrast Mode is enabled.  That is probably where the bug is coming from.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Restore from external hard drive I had to pay to have Windows reinstalled because a you know what deleted my user profiles. In order to restore it myself I created a backup on a external hard drive. How do I restore to the clean version of Windows from the external drive. I'm assuming it would involve DOS commands.

A: Have you created a image backup on the external hard driver?
we can create a whole image backup on the external hard driver, then recover it back if we want.it contains a copy of Windows and copies of your programs, system settings, and files. When you restore your computer from a system image, it's a complete restoration.
we could refer to the following link for detailed steps about create image backup.
http://windows.microsoft.com/en-us/windows/back-up-programs-system-settings-files#1TC=windows-7
then, how to Restore your computer from a system image backup
http://windows.microsoft.com/en-us/windows/restore-computer-from-system-image-backup
Best regards


text:
Q: How to detect if an MPMediaItem represents a DRM-protected audio track on iOS I would like to know if an MPMediaItem that represents a music track is for a Fairplay/DRM-protected item. Any way to do this?

A: Since iOS 4.2 there is a way. There may be a more effective way then the example here (but for my app I needed to create AVPlayerItems anyway).
MPMediaItem item;
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVPlayerItem *avItem = [[AVPlayerItem alloc] initWithURL:assetURL];
BOOL fairplayed = avItem.asset.hasProtectedContent;

A: From iOS 4.2 the AVAsset class has a property hasProtectedContent so you can check:
NSURL *assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
AVAsset *asset = [AVAsset assetWithURL:assetURL];

if ([asset hasProtectedContent] == NO) {..do your stuff..}

A: MPMediaItemPropertyAssetURL is not nil on iPhone X running iOS 11 for songs saved offline via Apple Music but AVPlayer is unable to play them since they are DRM protected. The same song returns MPMediaItemPropertyAssetURL nil on iOS 9.
MPMediaItemPropertyAssetURL returns nil for songs added to Library via Apple Music but not available offline - both on iOS 9 & 11.
Thus, @voidStern's answer (and not Justin Kent's) is the correct way to test for DRM-protected asset.
Swift 4 version of voidStern's answer (works perfectly for me on iOS 9 to 11):
let itemUrl = targetMPMediaItem?.value(forProperty: MPMediaItemPropertyAssetURL) as? URL
if itemUrl != nil {
    let theAsset = AVAsset(url: itemUrl!)
    if theAsset.hasProtectedContent {
        //Asset is protected
        //Must be played only via MPPlayer
    } else {
        //Asset is not protected
        //Can be played both via AVPlayer & MPPlayer\
    }
} else {
    //probably the asset is not avilable offline
    //Must be played only via MPPlayer
}

Another correct way of checking for DRM-protected asset is by making use of protectedAsset property of MPMediaItem - an answer by @weirdyu. But, this property is available only on iOS 9.2 and above.
Swift 4 solution for this method (works perfectly for me on iOS 9.2 and above):
if #available(iOS 9.2, *) {
    if (targetMPMediaItem?.hasProtectedAsset)! {
        //asset is protected
        //Must be played only via MPMusicPlayer
    } else {
        //asset is not protected
        //Can be played both via AVPlayer & MPMusicPlayer
    }
} else {
    //Fallback on earlier versions
    //Probably use the method explained earlier
}

A: Here's how I do it:
MPMediaItem* item;

NSURL* assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
NSString *title=[item valueForProperty:MPMediaItemPropertyTitle];

if (!assetURL) {
    /*
     * !!!: When MPMediaItemPropertyAssetURL is nil, it typically means the file
     * in question is protected by DRM. (old m4p files)
     */
    NSLog(@"%@ has DRM",title);
}

A: iOS9.2+:
Please use MPMediaItem "protectedAsset" property
iOS9.2-:
Judge MPMediaItem"assetURL"property is nil or not

A: Justin Kents' solution works great. I recommend using blocks though or else the UX will suffer if you deal with a bunch of songs:
-(void)checkDRMprotectionForItem:(MPMediaItem*)item OnCompletion:(void (^)(BOOL drmProtected))completionBlock
{
    dispatch_async(_drmCheckQueue, ^{
        BOOL drmStatus;
        NSURL* assetURL = [item valueForProperty:MPMediaItemPropertyAssetURL];
        if (!assetURL) {
            drmStatus = YES;
        }

        dispatch_async(dispatch_get_main_queue(), ^{
            if (completionBlock) {
                completionBlock(drmStatus);
            }
    });
    });
}

A: Now I'm building on swift 2 for ios 9, I found my code broken using hasProtectedContent or using nil url test.  I've found the following code work:
    let playerItem = AVPlayerItem(URL: mpMediaItem.assetURL!)
    playableByAVPlayer = (playerItem.status == .ReadyToPlay) ? true : false

If the item is not playable by AV Player, then it's a DRM item and should be played by iPod Player (now called SystemMusicPlayer).


text:
Q: SQL Server merge and pk violation I'm trying to understand why in a scenario like the following
DECLARE @source TABLE
             (
                 orderId NVARCHAR(50),
                 customerId NVARCHAR(50)
             )

DECLARE @target TABLE
             (
                  orderId NVARCHAR(50) PRIMARY KEY,
                  customerId NVARCHAR(50) NOT NULL
             )

INSERT INTO @source
VALUES ('test', '123'), ('test', '234')

MERGE @target AS TRG
USING (SELECT DISTINCT orderId, customerId
       FROM @source) AS SRC ON SRC.orderId = TRG.orderId

WHEN MATCHED THEN
    UPDATE SET TRG.customerId = SRC.customerId

WHEN NOT MATCHED BY TARGET THEN
    INSERT (orderId, customerId)
    VALUES (orderId, customerId);

I'm getting a duplicate key violation error:

Msg 2627, Level 14, State 1, Line 21
  Violation of PRIMARY KEY constraint 'PK__#B3D7759__0809335D4BE1521F'. Cannot insert duplicate key in object 'dbo.@target'. The duplicate key value is (test).

What I expect is that the update statement finds the existing key and updates the customerId so that at the end I have in @target 1 row with orderId = 'test' and customerId = '234'.
For what I can assume, it instead tries to insert all records as it first doesn't find any key match at the beginning of the merge, causing the violation as the source contains the key multiple times.
Is this right? Is there any way to achieve what I am expecting using the merge function?

@user1443098
I've read your link, thanks. However I have a massive data insertion coming from a source table and going into 10 different tables; I tried to implement the procedure with a cursor and it took like 0.5s per record (with all the if exists statements). With merge statement, 300 rows have been inserted in the 10 different tables in less than one sec. So in my case it does a lot of difference in performance terms.

A: There are two records in @source with the same OrderID.  There is not a match for either record in @target so the NOT MATCHED clause is trying to insert both of these records.  But it can not do this because the primary key on OrderID in the @target table requires that all inserted records have unique values for OrderID.  The duplication of values into the primary key causes the primary key violation.
If you are expecting duplicates are possible in the source... you should eliminate them in your USING sub-query.  Something like this:
(SELECT orderId, max(customerId) customerId
FROM @source
group by orderId)


text:
Q: Consumir web-service em ASP.NET MVC Preciso de consumir alguns métodos na minha página através de um Web-Service. Este Web-Service está na Europa.
Qual é a melhor forma de o fazer? O que são End-Points?

A: Segundo o site http://www.ehow.com/info_12212371_definition-service-endpoint.html, um endpoint é definido no texto traduzido abaixo:

Um endpoint é um ponto de conexão de onde os arquivos HTML ou dinâmicos estão expostos. Endpoints fornecem informações necessárias para acessar um Webservice. O endpoint fornece uma referência ou especificação que é usada para definir um grupo ou família de propriedades  de endereçamento de mensagens e dar características da mensagem ponto-a-ponto, como referências para a origem eo destino dos terminais, bem como a identidade de mensagens para permitir endereçamento uniforme de mensagens "independentes". O endpoint pode ser um PC, PDA, ou terminal de ponto-de-venda.

No seu caso, o endpoint é o próprio endereço do WebService que se deseja acessar.
Para adição de um WebService na sua aplicação, faça o seguinte:
Passo 1
Botão direito no projeto > Add > Service Reference

Passo 2
Nesta tela, clique em Advanced

Passo 3
Clique em Add Web Reference...

Passo 4
Cole o endereço do WebService que deseja acessar no campo URL. Se for mesmo um WebService com uma WSDL válida, os métodos aparecerão no quadrado de baixo. Basta clicar em Add Reference que será adicionado ao seu projeto uma classe que representa o acesso ao WebService.

Consumindo o WebService
Para acessar os dados do seu WebService em Controller, use uma declaração mais ou menos assim:
var wsMeuWebService = new wsMeuWebService.MeuWebService();
wsMeuWebService.MetodoDoWebService();

A: Faça o seguinte, clique com o botão direito no projeto e escolha a opção Adicionar referência de serviço.
Cole a URL do WS, mude o namespace e aperte em OK.


text:
Q: Activating / launching the google chrome extension with a keyboard shortcut If in the tab development tools ->extensions -> keyboard shortcuts I added a shortcut e.g. Ctrl + b
Then if someone else installs the extension on their computer this shortcut from the machine will work, Will anyone have to add it again in the 'keyboard shortcuts' tab? I think I once read that the shortcut to activate the extension can be set in the file manifest.json.
Does anyone know how to set this shortcut in the manifest.json file?

A: From the Chrome Docs
Note:
You must have a "manifest_version" of at least 2 to use this API.
{
    "name": "My extension",
    "commands": {
        "toggle-feature-foo": {
            "suggested_key": {
                "default": "Ctrl+Shift+Y",
                "mac": "Command+Shift+Y"
            },
            "description": "Toggle feature foo",
            "global": true
        }
    }
}


text:
Q: Do I need a balanced sample (50% yes, 50% no) to run logistic regression? I'm working on a project using logistic regression to predict student retention. The data were collected through three self-report instruments. We are trying to find out which predictors are powerful enough to predict the at-risk students. I came across some articles saying a balanced sample (50% stay, 50% dropouts) is desirable for such study, e.g. Glynn, J.G., Sauer, P.L., & Miller, T.E. (2003). Signaling Student Retention With Prematriculation Data, NASPA Journal, 41 (1), 41-67:

A problem however, is that the distribution of the dependent variable is likely to be highly skewed toward persistence. For example, if 85% of the analysis sample were persistors, a classification model that classified every student as a persistor would have a success rate of 85%, or would classify 85% of student correctly. To resolve this issue, the maintenance of relative balance between the number of dropouts and the number of persistors (about 50% each) in the analysis sample was desirable.

Is this true? Our sample only has about 25%-30% dropout students. Will this affect the results?

A: This is not so much a problem of logistic regression per se as it is a problem with classification accuracy as a performance measure. Note that balancing the data set is not necessarily the only valid approach. If one of the classes is actually much more common in the population (and not merely in your sample), a naive model (classifying everything as belonging to the most common category) really is a good guess. If the error costs are not symmetric, balancing the data set might lead you to err in the wrong direction (the more costly one).
The problem also often comes up the other way around: Training/evaluating on some artificially balanced data set before using the resulting model in a strongly unbalanced situation (think detecting fraud or diagnosing a rare disease) where the usefulness of the model is not nearly as high as the raw accuracy would suggest. It all depends on your objectives and your cost structure.

A: Yes; it will affect the results.  Logistic regression fits an MLE by minimizing an objective function which is evaluated at all the data points.  If the data is unbalanced then the minimization will be unbalanced too.
While your example is not extreme, you will get different answers if you re-balance.
A good explanation of this and how to address it is in King and Zeng, http://gking.harvard.edu/files/gking/files/0s.pdf.

A: Class imbalance can be a real problem.
An alternative to down-sampling would be to assign costs to the different classes, which is supported in popular toolkits.
E.g. look for the -j parameter in SvmLight (for support-vector regression), or the -w in LibLinear (for different kinds of linear regression).


text:
Q: Issue with react router Uncaught Error: Invariant Violation: Element type is invalid: expected a string (for built-in components) I have some issue with using react-router. I get this error and couldn't render my app.enter image description here
I looking for answer every where but couldn't find anything helpful. So i will be really appreciated if somebody could help me, because I am stuck.

import React from 'react';
import HomePage from './pages/page.create.jsx';
import { render } from 'react-dom';
import { Router, Route, IndexRoute, Link, IndexLink } from 'react-router';
import { createHistory, useBasename } from 'history';

class CreatePage extends React.Component {
    constructor (props) {
        super(props);
        this.state = {};
    }

    render() {
        return (

Hello World!

                {this.props.children}

        );
    }
}

//render(<HomePage />, document.body);

const routes = {
    path: '/',
    component: CreatePage,
    childRoutes: [
        { path: 'about', component: HomePage }
    ]
};

render(<Router>{routes}</Router>, document.getElementById('root'));

A: You didn't pass history to your router. Something like that should do the trick:
const history = createHistory();
render(<Router history={history}>{routes}</Router>, document.getElementById('root'))

A: Thanks all. The problem was in react-router version, I tried to use features from v 1.0 but installed was a v13.5. For resolve I reinstall router and everything start fine.


text:
Q: Facebook infinite loop, setTimeout not helping =( I have a loop on my facebook when using ie and firefox (Facebook Javascript SDK window location reload not working on Firefox)
because of the:
FB.Event.suscribe('auth.login',function(response){
    location.reload(true);
});

I tryied with:
FB.Event.suscribe('auth.login',function(response){
    window.setTimeout('location.reload(true)',0);
});

But it keeps doing the loop.
Additional information: I'm only using html,javascript and jquery not using php, asp, aspx, ruby, nothing else than that.

A: Change to:
FB.Event.suscribe('auth.login',function(response){
   window.setTimeout(function () {
       location.reload(true);
   },0);
});

A: You shouldn't call reload if user already connected
FB.getLoginStatus(function(response) {
    var reload = function(){location.reload(true);};
    if(response.status !== 'connected'){
        FB.Event.subcribe('auth.login',function(response){
            setTimeout(reload,0);
        });
    }else {
        FB.Event.subcribe('auth.logout',function(response){
            setTimeout(reload,0);
        });
    }
});


text:
Q: parsing string using regex or php To put simply, I'm trying to find and replace text with the wrapped xhtml tags without touching the surrounding text. Ideally I was going to use regex in Notepad++ but have had no experience with regular expressions and only limited experience with PHP,
For example:
Year: 2007    Registration: XYZS23
Transmission: Auto    Stock Number: AZ1234
Kilometres: 1280    Colour: Blue
Features:
includes cruise control.

With the parsed text it would then look like the following:
Year: 2007    Registration: XYZS23
Transmission: Auto    Stock Number: AZ1234
Kilometres: 1280    Colour: Blue
Features:
includes cruise control.

so any suggestions would be greatly appreciated.

A: So - you will have to search for this:
<whitespace> <any non-null number of alphanumerical characters> : <whitespace>

Which will, when using preg_replace (regex in PHP) look like this:
$parsed = preg_replace("/([A-Z]+:)/", "$0", $original);

A: You can search for [^\s{2,}]+: and replace with $0 or \0 depending on the editor.
Here it is in TextMate!
http://i.stack.imgur.com/5aqfO.png

A: Try this:
search : ([a-zA-Z]+ *[a-zA-Z]*:)
replace: \1


text:
Q: JFileChooser to allow the user to select the input file of credit card numbers Here, I did with the user input test credit card number, but now I want to do this things with  uses JFileChooser to allow the user to select the input file of credit card numbers and Display the results in an output file. I got As output file with card number is valid or not but if i want to print the card number  with company name.how can i do that?
Here is my code:
public static void main(String[] args) throws FileNotFoundException {
        // TODO Auto-generated method stub
        Scanner user = new Scanner(System.in);

        JFileChooser jfc = new JFileChooser(".");
        int jfcUserOption = jfc.showOpenDialog(null);
        if (jfcUserOption == JFileChooser.APPROVE_OPTION){
            File chosenFile = jfc.getSelectedFile();
            Scanner scan = new Scanner( chosenFile );
            System.out.print("Output File Name: ");
            String outputFileName = user.nextLine();
            PrintWriter output = new PrintWriter( outputFileName );

                while(scan.hasNextLine()){
                long number = scan.nextLong();
                while(number != 0){
                    if(isValid(number)){
                        output.println(number + " is valid number");
                        }
                    else{
                        output.println(number + " is invalid number");
                    }

                    output.close();

                }
                }
        }
        }

    public static boolean isValid(long number) {
        // TODO Auto-generated method stub
          int total = sumOfEvenPlace(number) + sumOfoddPlace(number);

            if ((total % 10 == 0) && (preMatched(number, 1) == true)) {
                return true;
            } else {
                return false;
            }
    }

    private static int sumOfoddPlace(long number) {
        // TODO Auto-generated method stub
        int n = getSize(number);
        int sum = 0;
        for(int i = 1; i <= n; i += 2){
            sum += getDigitIndex(number, i);
        }
        return sum;
    }

    private static int sumOfEvenPlace(long number) {
        // TODO Auto-generated method stub
        int sum = 0;
        int n = getSize(number);
        for (int i = 2; i <= n; i+= 2){
            sum += getDigit(2 * getDigitIndex(number, i));
        }

        return sum;
    }

    private static int getDigit(int number) {
        // TODO Auto-generated method stub
        int digit1 = number / 10;
        int digit2 = number % 10;

        if(digit1 == 0){
            return number;
        }
        else{
            return digit1 + digit2;
        }

    }

    private static int getDigitIndex(long number, int index) {
        // TODO Auto-generated method stub
        int digit;
        digit = (int)(((number / Math.pow(10, index - 1))) % 10);
        return digit;
    }

    private static int getSize(long digit) {
        // TODO Auto-generated method stub
        int digitNumber = 1;
        while((digit = digit / 10) != 0){
            digitNumber++;
        }
        return digitNumber;
    }

    private static int getPre(long number, int p) {
        // TODO Auto-generated method stub
        int digitnumber = getSize(number);
        return (int) (number / (long) ( Math.pow(10.0, (double)(digitnumber - p))));
    }

    private static boolean preMatched(long number, int digit){

        if ((getPre(number, digit) == 3) /*|| (getPre(number, digit) == 37) */ || (getPre(number, digit) == 4) || (getPre(number, digit) == 5) || (getPre(number, digit) == 6)) {

            //PrintWriter pw = null;
            if (getPre(number, digit) == 3 /* && getPre(number, digit) == 37 */ ) {
                //output.println( " American Express Card");
            } else if (getPre(number, digit) == 4) {
                //pw.println(" Visa Card ");
            } else if (getPre(number, digit) == 5) {
               //pw.println("Master Card");
            } else if (getPre(number, digit) == 6) {
                //pw.println("Discover Card");
            }

            return true;

        } else {
            return false;

        }
    }

    }

My Input file is: test.txt
5535085286738004
 5443144794186700
 6011436897231072
 011600388914427

My output should be: testOutput.txt
5535085286738004    Master Card         Valid
5443144794186700    Master Card         Valid
6011436897231072    Discover Card       Valid
011600388914427     None                Invalid

A: JFileChooser fc = new JFileChooser(f);
    fc.showOpenDialog(this);
    if (fc.getSelectedFile() != null) {
        return fc.getSelectedFile().getAbsolutePath();
    } else {
        return "No file selected";
    }

afterwards use BufferedReader to go through lines and call the methods for every line
BufferedReader reader = null;

    try {
        reader = new BufferedReader(new FileReader(file));
        String line;
            while ((line = reader.readLine()) != null) {
                if (!line.isEmpty()) {
                        long accNumber=Long.parseLong(line);
                        //do your stuff
                    }
                }
        }


text:
Q: Why I can't get the internal output of a trained model? import tensorflow.keras as keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    model = keras.models.load_model('model/model_test_0.99408.h5', custom_objects={'leaky_relu': tf.nn.leaky_relu})
    model.summary()
    inputs = keras.layers.Input(shape=(28, 28, 1))
    y = model(inputs)
    feature = model.get_layer('conv2d_4').output
    model = keras.Model(inputs=inputs, outputs=[y, feature])
    model.summary()

why i can't get the output of 'conv2d_4' that is the internal layer of the model? And i get the following error.
Graph disconnected: cannot obtain value for tensor Tensor("input_1:0", shape=(None, 28, 28, 1), dtype=float32) at layer "conv2d". The following previous layers were accessed without issue: []

A: We can try restacking the model, assigning feature to the required layer,
import tensorflow.keras as keras
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    model = keras.models.load_model('model/model_test_0.99408.h5', custom_objects={'leaky_relu': tf.nn.leaky_relu})
    model.summary()
    inputs = keras.layers.Input(shape=(28, 28, 1))
    y = inputs
    for layer in vgg.layers:
        if layer.name == 'conv2d_4':
            feature = y
        y = layer( y )
    model = keras.Model(inputs=inputs, outputs=[y, feature])
    model.summary()


text:
Q: PYspark erroring when sending RDD to Kafka Topic HI all I'm a bit confused about this one.
my spark code generate the expected output however once I try and send the RDD back to kafka it is erroring every single time.  Im not quite sure what is wrong with my code.
 def sendkafka(messages):
    kafka = KafkaClient(kafkaip)
    producer = SimpleProducer(kafka, 'dev_test_upstream')
    for message in messages:
         producer.send_messages(message)

A: Are you sure that your sendkafka() method is working as intended. It looks like you provided partial listing, so not sure if that part is working. I have a sample of how to send data to Kafka from Python, take a look Python client for publishing and consuming message from Apache Kafka, you might want to use the producer.py instead of sendKafka() method


text:
Q: I want to copy file from one folder to another using cmd, with each file copied is updated with newer date I want to copy from one folder to another on daily basis but each file copied is updated with current date.
I know the code to copy file but I dont know how to copy file with updated date and I need to put this in Task scheduler to run it daily.
This is my code:
cd C:\Automation\
Copy "Z:\VENDOR_LOAD\Access DB\COMPLETE SM DATA\SupplierMaster_Query.xlsx" "Z:\VENDOR_LOAD\Access DB\COMPLETE SM DATA\BACKUP\SupplierMaster_Query_.xlsx"


text:
Q: Capture rendered markup between two arbitrary points in a view So I'd like to be able to do the following in a razor page:

 some markup
    @using(var myMarkupCapturer = Html.CaptureHtml())
    {

this markup will be captured

    }

Any suggestions? I was thinking about substituting the TextWriter of my ViewContext (ViewContext.Writer) for a specialized version that can be intercepted. Is there a better way?


text:
Q: how to get last cells and load more data from api I have a problem with how the last cell appears in the table as well as loading more cells through the API
I would also like to add the Gray Activity Indicator At the bottom of the cells in the queue while loading the cells
Use Alamofire library
Swift 5

A: We can achieve this using the tableview delegate method
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;

This delegate method is called before tableview uses cell to draw a row which allows us to customise the cell before being displayed.
In this override method we get indexPath which can be used to check if the cell is the last one.

A: For Gray Activity Indicator At the bottom add a custom cell with a Activity indicator along with a label stating "fetching more..........." or else show like below
To Add Activity indicator in tableview
func showIndicator() {
    let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)

    spinner.startAnimating()
    tableView.backgroundView = spinner
}

To get last cells and load more data from api
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
         if yourArr.count-1 == indexPath.row{
            getMoreImages(page)
         }
 }

    func getMoreImages(page:Int){
       //hit api
       if api_success == true {
           if self.page == 0 {
              self.yourArr.removeAll()
           }
       self.yourArr.appendContentsOf(api_data)
       self.tableView.reloadData()
       self.page = self.page + 1
       }
    }


text:
Q: javax.ejb.EJBException: Transaction aborted Transaction marked for rollback I'm working on a JavaEE application with EJB.
Two of my Entities are the following:
@Entity
public class Utente implements Serializable {
/**
 *
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue
private int cod_utente; //BI
private String nome_utente;
private String morada_utente;
@Temporal(TemporalType.DATE)
private GregorianCalendar dnasc_utente;
private int tel_utente;
private ArrayList<GregorianCalendar> agenda;
@OneToMany
@Column(nullable=true)
private ArrayList<Prescricao> lista_presc;

and
@Entity
public class FichaClinica implements Serializable{
/**
 *
 */
private static final long serialVersionUID = 1L;
/**
 *
 */
@Id
@GeneratedValue
private int cod_ficha;
@OneToOne
private Utente utente;
@OneToMany
@Column(nullable=true)
private ArrayList <AtoEnfermagem> lista_atos_enf;
@OneToMany
@Column(nullable=true)
private ArrayList <AtoMedico> lista_atos_medicos;
@OneToMany
@Column(nullable=true)
private ArrayList<Consulta> lista_consultas;

When I try to create an Entity Utente and FichaClinica using the method:
@Override
public String cria_utente(String nome_utente, String morada_utente,GregorianCalendar dnasc_utente, int tel_utente) {
    Utente u=new Utente(nome_utente,morada_utente,dnasc_utente,tel_utente);
    em.persist(u);
    FichaClinica fc=new FichaClinica();
    em.persist(fc);
    fc.setUtente(u);
    return "Utente "+Integer.toString(u.getCod_utente())+" cirado!";
}

The following error occurs:
Exception in thread "main" javax.ejb.EJBException: Transaction aborted
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:725)
at com.sun.ejb.containers.EJBContainerTransactionManager.postInvokeTx(EJBContainerTransactionManager.java:503)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4566)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2074)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2044)
at com.sun.ejb.containers.EJBObjectInvocationHandler.invoke(EJBObjectInvocationHandler.java:212)
at com.sun.ejb.containers.EJBObjectInvocationHandlerDelegate.invoke(EJBObjectInvocationHandlerDelegate.java:79)
at com.sun.proxy.$Proxy235.cria_utente(Unknown Source)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie.dispatchToMethod(ReflectiveTie.java:143)
at com.sun.corba.ee.impl.presentation.rmi.ReflectiveTie._invoke(ReflectiveTie.java:173)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatchToServant(ServerRequestDispatcherImpl.java:528)
at com.sun.corba.ee.impl.protocol.ServerRequestDispatcherImpl.dispatch(ServerRequestDispatcherImpl.java:199)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequestRequest(MessageMediatorImpl.java:1549)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:1425)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleInput(MessageMediatorImpl.java:930)
at com.sun.corba.ee.impl.protocol.giopmsgheaders.RequestMessage_1_2.callback(RequestMessage_1_2.java:213)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.handleRequest(MessageMediatorImpl.java:694)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.dispatch(MessageMediatorImpl.java:496)
at com.sun.corba.ee.impl.protocol.MessageMediatorImpl.doWork(MessageMediatorImpl.java:2222)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.performWork(ThreadPoolImpl.java:497)
at com.sun.corba.ee.impl.threadpool.ThreadPoolImpl$WorkerThread.run(ThreadPoolImpl.java:540)
Caused by: javax.transaction.RollbackException: Transaction marked for rollback.
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:490)
at com.sun.enterprise.transaction.JavaEETransactionManagerSimplified.commit(JavaEETransactionManagerSimplified.java:854)
at com.sun.ejb.containers.EJBContainerTransactionManager.completeNewTx(EJBContainerTransactionManager.java:719)
... 24 more
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred while accessing method [_persistence_set_lista_atos_enf] on class [class Entities.FichaClinica].
Internal Exception: java.lang.NoSuchMethodException: Entities.FichaClinica._persistence_set_lista_atos_enf(Entities.AtoEnfermagem)
Descriptor: RelationalDescriptor(Entities.FichaClinica --> [DatabaseTable(FICHACLINICA)])
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl$1.handleException(EntityManagerSetupImpl.java:696)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.handleException(AbstractSynchronizationListener.java:275)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:170)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:68)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 26 more
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: An internal error occurred while accessing method [_persistence_set_lista_atos_enf] on class [class Entities.FichaClinica].
Internal Exception: java.lang.NoSuchMethodException: Entities.FichaClinica._persistence_set_lista_atos_enf(Entities.AtoEnfermagem)
at org.eclipse.persistence.exceptions.DescriptorException.errorAccessingSetMethodOfEntity(DescriptorException.java:410)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.getSetMethod(WeavedObjectBasicIndirectionPolicy.java:121)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.setRealAttributeValueInObject(WeavedObjectBasicIndirectionPolicy.java:176)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.setRealAttributeValueInObject(WeavedObjectBasicIndirectionPolicy.java:144)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.updateValueInObject(WeavedObjectBasicIndirectionPolicy.java:134)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.getRealAttributeValueFromObject(WeavedObjectBasicIndirectionPolicy.java:77)
at org.eclipse.persistence.mappings.ForeignReferenceMapping.getRealAttributeValueFromAttribute(ForeignReferenceMapping.java:1068)
at org.eclipse.persistence.mappings.DatabaseMapping.getRealAttributeValueFromObject(DatabaseMapping.java:786)
at org.eclipse.persistence.mappings.CollectionMapping.getRealCollectionAttributeValueFromObject(CollectionMapping.java:1142)
at org.eclipse.persistence.mappings.CollectionMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(CollectionMapping.java:473)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:2514)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4207)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:949)
at org.eclipse.persistence.mappings.ObjectReferenceMapping.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectReferenceMapping.java:927)
at org.eclipse.persistence.internal.descriptors.ObjectBuilder.cascadeDiscoverAndPersistUnregisteredNewObjects(ObjectBuilder.java:2514)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.discoverAndPersistUnregisteredNewObjects(UnitOfWorkImpl.java:4207)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.discoverUnregisteredNewObjects(RepeatableWriteUnitOfWork.java:305)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.calculateChanges(UnitOfWorkImpl.java:723)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1516)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3168)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:352)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:158)
... 28 more
Caused by: java.lang.NoSuchMethodException: Entities.FichaClinica._persistence_set_lista_atos_enf(Entities.AtoEnfermagem)
at java.lang.Class.getDeclaredMethod(Class.java:2122)
at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.findMethod(PrivilegedAccessHelper.java:87)
at org.eclipse.persistence.internal.security.PrivilegedAccessHelper.getMethod(PrivilegedAccessHelper.java:290)
at org.eclipse.persistence.internal.helper.Helper.getDeclaredMethod(Helper.java:1020)
at org.eclipse.persistence.internal.indirection.WeavedObjectBasicIndirectionPolicy.getSetMethod(WeavedObjectBasicIndirectionPolicy.java:97)
... 48 more

I've also created a persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Hospital" transaction-type="JTA">
    <class>Entities.Medico</class>
    <class>Entities.Utente</class>
    <class>Entities.FichaClinica</class>
    <class>Entities.Enfermeiro</class>
    <class>Entities.AtoEnfermagem</class>
    <class>Entities.AtoMedico</class>
    <class>Entities.Consulta</class>
    <class>Entities.Prescricao</class>
    <class>Entities.Encomenda</class>
    <class>Entities.Produto</class>
    <class>Entities.Medicamento</class>
    <properties>
        <property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
    </properties>
</persistence-unit>
</persistence>

Can someone please help me understand why this is happening?

A: I already solved the problem.
The problem was in the arraylists. Glassfish doesn't support that type of struture, so I changed it to Lists


text:
Q: AWS billing shows SNS usage without any topics? I was going through my AWS Billing Dashboard and noticed, that I am using some of my monthly free tier SNS requests. However, I don't uses SNS in any of my projects. I checked the SNS console and Topics, Subscriptions and Platform applications all show 0.
I am mostly using eu-west-1 region, but billing shows usage of both 1,000,000 Requests for Amazon Simple Notification Service (EU) and (USE1). The only thing I have in us-east-1 is a lambda that uses a "Alexa Home Skill" as a trigger (and doesn't use SNS afaik). The billing shows 4 used request this month, but the skill is used much more than that, so I don't think that's the culprit.
I have only a bunch of lambdas, triggered with CloudWatch events, Alexa skills or API Gateway. Any idea why would SNS show up?


text:
Q: Magento2: redirect from Observer We have already know that How to redirect from an Observer for magento 1.x version.
but for magento 2,we does not know How to forcefully do redirection from an observer.
I have done google ,but does not get any answer.

A: Yup, i have find a solution by myself by doing a research
If you want to do that then on __construct() function of your class observer,you must inject two classes.

*

*First, \Magento\Framework\App\ResponseFactory which  responsible for
redirection,

*Another  class \Magento\Framework\UrlInterface which will make url
for that redirection.

*Then create object for ResponseFactory  ,and using
setRedirect($YourUrl)->sendResponse(); redirect to your wished url.

Observer
<?php
namespace [Vendor]\[modulename]\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;
class [YourClass] implements ObserverInterface {
    protected $_responseFactory;
    protected $_url;
    public function __construct(
        ......
        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url,
        ......
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }
    public function execute(Observer $observer) {
             $event = $observer->getEvent();
             $CustomRedirectionUrl = $this->_url->getUrl('[ModuleName]/[ModuleName]/[[Action]');
            $this->_responseFactory->create()->setRedirect($CustomRedirectionUrl)->sendResponse();
            /* die use for stop excaution */
             die();
    }
}

Example:
Here i am write an example of that  redirection.
Basically sales_quote_collect_totals_after event,i was try to forcefully redirect to contact us.
Here the observer code:

<?php
namespace Devamit\Mgoto\Observer;
use \Magento\Framework\Event\Observer;
use \Magento\Framework\Event\ObserverInterface;

class Challo implements ObserverInterface {
    protected $_responseFactory;
    protected $_url;

    public function __construct(

        \Magento\Framework\App\ResponseFactory $responseFactory,
        \Magento\Framework\UrlInterface $url
    ) {
        $this->_responseFactory = $responseFactory;
        $this->_url = $url;
    }

    public function execute(Observer $observer) {
        $event = $observer->getEvent();

            $myfile = fopen("var/log/debug.log", "a+") or die("Unable to open file!");
          fwrite($myfile, 'Amitber',true);
          fclose($myfile);
      // $this->_responseFactory->create()->setRedirect('www.google.com')->sendResponse();
           $customerBeforeAuthUrl = $this->_url->getUrl('contact/index/index');
          $this->_responseFactory->create()->setRedirect($customerBeforeAuthUrl)->sendResponse();
       die();
    }
}

A: injecting the \Magento\Framework\App\ActionFlag $actionFlag and $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);is the way of forcing Magento to stop processing further events and redirect from an observer specially in the case of using predispatch event.
Here is the sample code
public function execute(\Magento\Framework\Event\Observer $observer)
{

    /** @var \Magento\Customer\Controller\Account\LoginPost\Interceptor $controller_action */
    $controller_action = $observer->getData( 'controller_action' );
    $parameters = $controller_action->getRequest()->getParams();
    $session = $this->customerSession;

    if({yourcondition}){

        // setting an action flag to stop processing further hierarchy
        $this->_actionFlag->set('', \Magento\Framework\App\Action\Action::FLAG_NO_DISPATCH, true);

        /// redirecting back to its referred url
        $observer->getControllerAction()->getResponse()->setRedirect($this->_redirectInterface->getRefererUrl());
        $session->setCustomerFormData($parameters);

    }

    return $this;

}

A: redirect to admin controller
  namespace sample\test\Observer;
  use \Magento\Framework\Event\Observer;
  use \Magento\Framework\Event\ObserverInterface;

  class SendSecurityCode implements ObserverInterface {

protected $_responseFactory;
protected $_url;

public function __construct(

    \Magento\Framework\App\ResponseFactory $responseFactory,
    \Magento\Framework\UrlInterface $url

     ) {

          $this->_responseFactory = $responseFactory;
          $this->_url = $url;
     }

public function execute(Observer $observer) {
        $event = $observer->getEvent();
        $RedirectUrl= $this->_url->getUrl('welcome/code/index');
        $this->_responseFactory->create()->setRedirect($RedirectUrl)->sendResponse();

}
}

A: Here i am writing some code for cart page redirecting.
In your module create a events.xml file
<?xml version="1.0" encoding="UTF-8"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Event/etc/events.xsd">
    <event name="controller_action_predispatch_checkout_cart_index">
        <observer name="my_predispatch_checkout_cart" instance="Namespace\Module\Observer\PredispatchCheckoutCart"/>
    </event>
</config>

In your observer file yourmodule\Observer\PredispatchCheckoutCart.php
<?php
    namespace Namespace\Module\Observer;
    use Magento\Framework\Event\ObserverInterface;

    class PredispatchCheckoutCart implements ObserverInterface{
        protected $_objectManager;

        public function __construct(
            \Magento\Framework\ObjectManagerInterface $objectManager,
            \Magento\Checkout\Helper\Cart $_cartHelper
        ) {
            $this->_objectManager = $objectManager;
            $this->_cartHelper = $_cartHelper;
        }

        public function execute(\Magento\Framework\Event\Observer $observer){
                //redirect to cart
                $redirectUrl = $this->_cartHelper->getCartUrl();
                $observer->getControllerAction()->getResponse()->setRedirect($redirectUrl);

            }
    }


text:
Q: Positive matrix with integer eigenvalues Is there any way of creating a positive matrix which has integer eigenvalues? Each entry $a_{ij}$ of the matrix must be strictly greater than $0$. I get how to create a matrix with certain eigenvalues using diagonal matrices, but I do not know how to make sure the matrix is strictly positive

A: The $n \times n$ matrix with diagonal entries $b$ and off-diagonal entries $a$ has eigenvalues $b-a$ (with multiplicity $n-1$) and $b + (n-1) a$.

A: If you are fine with some restrictions on eigenvalues, then this procedure might be helpful:

*

*Generate orthonormal matrix $S$ with the first column being in the direction of $u=(1,1,\ldots 1)$. For example, you can start with the vector $u$ and $d-1$ random vectors and apply Gram-Schmidt process to them.

*Create $J=\begin{pmatrix}\lambda_1&0&\cdots\\0&\lambda_2&\cdots\\\cdots&\cdots&\cdots\end{pmatrix}$. Where all lambdas are positive and $\lambda_1$ is sufficiently large.

*Now matrix $M=SJS^{-1}$ has all positive values (if not, increase $\lambda_1$) and eigenvalues $\lambda_i$.
You can also make matrix $M$ integer by replacing $S$ with its rational approximation ($S_1=\frac1N[NS]$) and multiplying the matrix $M$ by the common denominator of its elements. That will also increase the eigenvalues, but if you don't care what they are, that's fine.
Example:
Start with
$$
S_0 = \begin{pmatrix}1&0&0&0\\1&1&0&0\\1&0&1&0\\1&0&0&1\end{pmatrix}.
$$
After Gram-Schmidt and rationalization:
$$
S_1 = \begin{pmatrix}0.5&-0.29&-0.41&-0.71\\0.5&0.87&0&0\\0.5&-0.29&0.82&0\\0.5&-0.29&-0.41&0.71\end{pmatrix}.
$$
Take
$$
M=S_1\begin{pmatrix}5&0&0&0\\0&1&0&0\\0&0&2&0\\0&0&0&3\end{pmatrix}S_1^{-1} = \frac16\begin{pmatrix}19&6&4&1\\6&12&6&6\\4&6&16&4\\1&6&4&19\end{pmatrix}.
$$
Thus, matrix $M'=6M$ is integer and has eigenvalues $(30,6,12,18)$.

A: The problem of determining which complex spectrum can be realised by a nonnegative matrix is known as a nonnegative inverse eigenvalue problem. For an overview, you may read the following survey paper:

Egleston, Lenker, and Narayan, The nonnegative inverse eigenvalue problem, Linear Algebra and Its Applications, 379 (2004), 475-490.

Your requirement is more demanding because the matrix in question is not just nonnegative, but positive. Certainly, not every spectrum is realisable, because the spectrum has to satisfy the Perron condition (that the spectral radius is a simple eigenvalue) and some other necessary conditions (such as the trace condition $\operatorname{tr}(A^k)=\sum_i\lambda_i^k>0$ for every positive integer $k$). Since the literature is vast, I am not sure if the problem has been solved yet, or whether there is a constructive method for a wide class of spectra, but I'll exhibit a simple constructions below that is applicable for some spectra.
Given any decreasing sequence of integers $\lambda_1>\lambda_2\ge\cdots\ge \lambda_n\ge0$, the matrix
$$
\begin{aligned}
A&=\pmatrix{1\\ t&1\\ t&&1\\ \vdots&&&\ddots\\ t&&&&1}
\pmatrix{\lambda_1&1&1&\cdots&1\\ &\lambda_2\\ &&\lambda_3\\ &&&\ddots\\ &&&&\lambda_n}
\pmatrix{1\\ -t&1\\ -t&&1\\ \vdots&&&\ddots\\ -t&&&&1}\\
&=\pmatrix{\lambda_1-(n-1)t&1&1&\cdots&1\\
(\lambda_1-\lambda_2)t-(n-1)t^2&\lambda_2+t&t&\cdots&t\\
(\lambda_1-\lambda_3)t-(n-1)t^2&t&\lambda_3+t&\ddots&\vdots\\
\vdots&\vdots&\ddots&\ddots&t\\
(\lambda_1-\lambda_n)t-(n-1)t^2&t&\cdots&t&\lambda_n+t}
\end{aligned}
$$
is entrywise positive when $t>0$ is sufficiently small, and the eigenvalues of $A$ are the integers $\lambda_1,\lambda_2,\ldots,\lambda_n$. When $\lambda_1-\lambda_2\ge n$, we may choose $t=1$, so that the previous construction gives a positive integer matrix with a prespecified integer spectrum.
This construction can be generalised to the case where
$$
\begin{cases}
\lambda_1>\lambda_2\ge\cdots\ge\lambda_k\ge0>\lambda_{k+1}\ge\cdots\ge\lambda_n \text{ and}\\
\lambda_1-\lambda_2>\sum_{i=k+1}^n|\lambda_i|.
\end{cases}
$$
Let $e$ and $\tilde{e}$ denote the all-one vector in $\mathbb R^{k-1}$ and $\mathbb R^{n-k}$ respectively, $\Lambda=\operatorname{diag}(\lambda_2,\ldots,\lambda_k)$ and $\widetilde{\Lambda}=\operatorname{diag}(\lambda_{k+1},\ldots,\lambda_n)$. Now let $t>0$ be sufficiently small. Define
$$
\begin{aligned}
A&=
\pmatrix{1\\ te&I\\ \tilde{e}&&I}
\pmatrix{\lambda_1&e^T&\tilde{e}^T(tI-\widetilde{\Lambda})\\
&\Lambda\\
&&\widetilde{\Lambda}}
\pmatrix{1\\ -te&I\\ -\tilde{e}&&I}\\
&=
\pmatrix{\lambda_1&e^T&\tilde{e}^T(tI-\widetilde{\Lambda})\\
\lambda_1te&tee^T+\Lambda&te\tilde{e}^T(tI-\widetilde{\Lambda})\\
\lambda_1\tilde{e}&\tilde{e}e^T&\tilde{e}\tilde{e}^T(tI-\widetilde{\Lambda})+\widetilde{\Lambda}}
\pmatrix{1\\ -te&I\\ -\tilde{e}&&I}\\
&=
\pmatrix{\lambda_1-te^Te-\tilde{e}^T(tI-\widetilde{\Lambda})\tilde{e}&e^T&\tilde{e}^T(tI-\widetilde{\Lambda})\\
t\lambda_1e-t(tee^T+\Lambda)e-te\tilde{e}^T(tI-\widetilde{\Lambda})\tilde{e}&tee^T+\Lambda&te\tilde{e}^T(tI-\widetilde{\Lambda})\\
\lambda_1\tilde{e}-t\tilde{e}e^Te-\tilde{e}\tilde{e}^T(tI-\widetilde{\Lambda})\tilde{e}-\widetilde{\Lambda}\tilde{e}&\tilde{e}e^T&\tilde{e}\tilde{e}^T(tI-\widetilde{\Lambda})+\widetilde{\Lambda}}.
\end{aligned}
$$
The first column of $A$ is given by
$$
a_{i1}=
\begin{cases}
\lambda_1-\sum_{i=k+1}^n|\lambda_i|-(n-1)t&\text{when } i=1,\\
\left(\lambda_1-\lambda_i-\sum_{i=k+1}^n|\lambda_i|-(n-1)t\right)t&\text{when } 1<i\le k,\\
\left(\lambda_1-\lambda_i-\sum_{i=k+1}^n|\lambda_i|-(n-1)t\right)&\text{when } i>k
\end{cases}
$$
and hence it is positive. The second block column of $A$ is clearly positive. On the last block column, since $\tilde{e}^T(tI-\widetilde{\Lambda})$ is a positive vector, the first two sub-blocks are positive. The last sub-block $\tilde{e}\tilde{e}^T(tI-\widetilde{\Lambda})+\widetilde{\Lambda}$ is equal to
$$
\pmatrix{t+|\lambda_{k+1}|&t+|\lambda_{k+2}|&\cdots&t+|\lambda_n|\\
t+|\lambda_{k+1}|&t+|\lambda_{k+2}|&\cdots&t+|\lambda_n|\\
\vdots&\vdots&&\vdots\\
t+|\lambda_{k+1}|&t+|\lambda_{k+2}|&\cdots&t+|\lambda_n|}
-\pmatrix{|\lambda_{k+1}|\\ &|\lambda_{k+2}|\\ &&\ddots\\ &&&|\lambda_n|},
$$
which is positive too. Therefore $A$ is a positive matrix.

A: One special case that the matrix entries are strictly positive and it has integer eigenvalues is the reciprocal matrix defined as
\begin{equation}
 A = \begin{pmatrix} 1 & a_{12} & \dots & a_{1N}\\ \frac{1}{a_{12}} & 1 & &\vdots \\ \vdots &&&\vdots \\ \frac{1}{a_{1N}} &\dots  &\dots& 1  \end{pmatrix}
\end{equation}
whose rank is $1$ (all eigenvalues are $0$ except one), and its Perron-Frobenius eigenvalue is proved to be $\lambda_\mathrm{pf}=N$.


text:
Q: Using XML data instead of JSON data in Fancytree Does someone tried this already, I mean does someone made already a 3rd-party/extensions or patch for this?
The ajax XHR object supports reading of XML data, but I guess Fancytree would need some changes or a extensions to support this format?

A: You can parse and convert an XML response in the postProcess event.
For an example, assuming this XML format:
<children>
    <node>
        <title> Node 1</title>
    </node>
    <node folder="true" expanded="true" key="42">
        <title> Node 2 (expanded folder)</title>
        <children>
            <node>
                <title> Node 2.1</title>
            </node>
            <node>
                <title> Node 2.2</title>
            </node>
        </children>
    </node>
</children>

The tree could convert the ajax responses like so:
$("#tree").fancytree({
    source: { url: "ajax-tree.xml", dataType: "xml" },
    lazyLoad: function(event, data) {
        data.result = { url: "ajax-sub.xml", dataType: "xml" };
    },
    postProcess: function(event, data) {
        // Convert the xml responses to a Fancytree NodeData list.
        // data.response is a `#document` root, so we get the outer
        // `<children>` element:
        data.result = parseFancytreeXml($(">children", data.response));
    }
});

Finally the missing sample format converter:
/** Return a list of NodeData objects, assuming $xml points to a list of nodes.
 */
function parseFancytreeXml($xml) {
    var children = [];

    $xml.children("node").each(function() {
        var $node = $(this),
            subnodes = $node.children("children");

        // Create Fancytree NodeData object from <node> element
        children.push({
            title: $node.children("title").text(),
            expanded: $node.attr("expanded"),
            folder: $node.attr("folder"),
            key: $node.attr("key"),
            lazy: $node.attr("lazy"),
            children: subnodes.length ? parseFancytreeXml(subnodes) : null
        });
    });
    return children;
}


text:
Q: How to find duplicate rows in Hive? I want to find duplicate rows from one of the Hive table for which I was given two approaches.
First approach is to use following two queries:
select count(*) from mytable; // this will give total row count

second query is as below which will give count of distinct rows
select count(distinct primary_key1, primary_key2) from mytable;

With this approach, for one of my table total row count derived using first query is 3500 and second query gives row count 2700. So it tells us that 3500 - 2700 = 800 rows are duplicate. But this query doesn't tell which rows are duplicated.
My second approach to find duplicate is:
select primary_key1, primary_key2, count(*)
from mytable
group by primary_key1, primary_key2
having count(*) > 1;

Above query should list of rows which are duplicated and how many times particular row is duplicated. but this query shows zero rows which means there are no duplicate rows in that table.
So I would like to know:

*

*If my first approach is correct - if yes then how do I find which rows are duplicated

*Why second approach is not providing list of rows which are duplicated?

*Is there any other way to find the duplicates?

A: Hive does not validate primary and foreign key constraints.

Since these constraints are not validated, an upstream system needs to
  ensure data integrity before it is loaded into Hive.

That means that Hive allows duplicates in Primary Keys.
To solve your issue, you should do something like this:
select [every column], count(*)
from mytable
group by [every column]
having count(*) > 1;

This way you will get list of duplicated rows.

A: analytic window function row_number() is quite useful and can provide the duplicates based upon the elements specified in the partition by clause.  A simply in-line view and exists clause will then pinpoint what corresponding sets of records contain these duplicates from the original table.  In some databases (like TD, you can forgo the inline view using a QUALIFY pragma option)
SQL1 & SQL2 can be combined. SQL2:  If you want to deal with NULLs and not simply dismiss, then a coalesce and concatenation might be better in the
SELECT count(1) , count(distinct coalesce(keypart1 ,'') + coalesce(keypart2 ,'') )
  FROM srcTable s

3) Finds all records, not just the > 1 records.  This provides all context data as well as the keys so it can be useful when analyzing why you have dups and not just the keys.
select * from  srcTable s
where exists
    ( select 1 from (
                SELECT
                      keypart1,
                      keypart2,
                      row_number() over( partition by keypart1, keypart2 )  seq
                FROM srcTable t
                WHERE
                  -- (whatever additional filtering you want)
                ) t
                where seq > 1
                AND t.keypart1 = s.keypart1
                AND t.keypart2 = s.keypart2
    )

A: Suppose your want get duplicate rows based on a particular column ID here. Below query will give you all the IDs which are duplicate in table in hive.
SELECT "ID"
FROM TABLE
GROUP BY "ID"
HAVING count(ID) > 1


text:
Q: Pass a variable to decimalNumberHandlerWithRoundingMode? Forgive me if I use the wrong terminology as I'm still a little new at iOS development. I've built a calculator-type app and I want users to be able to control how numbers are rounded. Here's the code I'm using:
-(NSString*)calculateWidthFromHeightString:(NSString*)height usingDimensions:(Favorite*)dimensions{

int decimalPlaces = [self.userData.rounding intValue];

NSUInteger *roundingMethod;
if ([self.userData.roundingMode isEqualToString:@"up"]) {
  roundingMethod = NSRoundUp;
}
else if ([self.userData.roundingMode isEqualToString:@"plain"]) {
    roundingMethod = NSRoundPlain;
}
else {
    roundingMethod = NSRoundDown;
}

NSDecimalNumberHandler *handler = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:roundingMethod
scale:decimalPlaces
raiseOnExactness:NO
raiseOnOverflow:NO
raiseOnUnderflow:NO
raiseOnDivideByZero:NO];

This works as expected, but I'm getting the following compiler warning where I assign the rounding mode to the pointer "roundingMethod":

Incompatible Integer to pointer conversion assigning to 'NSUInteger *'
  (aka 'unassigned long *) from 'NSUInteger' (aka 'unassigned long')
  Incompatible Integer to pointer conversion assigning to 'NSUInteger *'
  (aka 'unassigned int *) from 'NSUInteger' (aka 'unassigned int')

I don't really know what this means. Any help would be greatly appreciated.

A: This line:
NSUInteger *roundingMethod;

should be:
NSUInteger roundingMethod;

NSUInteger is a native type, not a class type.


text:
Q: Importing/uploading files from file share to SP 2010 Doc Lib using CSV Can someone please provide a good link (or if you already have a powershell working) that can import files from file share into SharePoint document library using a cvs flat file. I have about 20 columns of all types (string, multi-string, datetime, managed-metadata, choice, etc.).
I saw few but nothing promising. I am short of time and can't evaluate each and every article I run into when doing a bing search. Please suggest. Not sure if this article (http://www.spjeff.com/2012/02/26/powershell-upload-csv-file-to-list-both-server-and-client-om/) is good for document library.

A: Just to understand correctly, do you want to use the CSV file to provide metadata for the files that will be imported from the file share?
If so, the approach depicted in the article (SPJeff) will not work. This sample uses a SP list as destination (as opposed to a SP library which is needed to support files).
Look at this article in Code Project (http://www.codeproject.com/Articles/103503/How-to-upload-download-a-document-in-SharePoint-20); this should give you good pointer on how to use the SP API to upload a document AND set the metadata elements.

A: Try using following articles
http://www.sharepointdiary.com/2012/10/bulk-upload-files-to-sharepoint-using.html
http://spbulkdocumentimport.codeplex.com/


text:
Q: How do i make that only if the user entered any text to textBox so the button1 will be enabled? using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace GatherLinks
{
    public partial class CrawlLocaly : Form
    {
        public CrawlLocaly()
        {
            InitializeComponent();

        }

        public string getText()
        {
            return textBox1.Text;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textBox1.Text))
            {
                DialogResult = DialogResult.OK;

            }
            else
            {

            }
        }

    }
}

In Form1 i Show this Form and its textBox:
private void button6_Click(object sender, EventArgs e)
        {

            using (var w = new StreamWriter(keywords))
            {
                crawlLocaly1 = new CrawlLocaly();
                crawlLocaly1.StartPosition = FormStartPosition.CenterParent;
                DialogResult dr = crawlLocaly1.ShowDialog(this);

I want to do in the crawlLocaly new Form that when i click in Form1 and open/show the new Form button1 on the new Form will be Enabled = false and once the user typed anything in the textBox in the new Form button1 will be enabled true and only then the user will able to click on the button1 in the new Form wich is OK(the text of the button in the new Form is OK).
Tried in the new Form to use on the button1 textchanged event but it didnt work. the button became false only after i clicked on it.

A: You can try with this code - based on  TextChanged event
protected void TextBox1_TextChanged(object sender, EventArgs e)
{
   if(TextBox1.Text.Trim().Length > 0)
   {
      Button.Enabled = true;
   }
}

Nota : Initialize Button.Enabled to false; on control

A: If you want to keep it in C# you can do this, don't forget to set AutoPostBack to True and test if the length is 0 to disable the button again:
    <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" Enabled="false" />
    <asp:TextBox ID="TextBox1" runat="server" AutoPostBack="true" OnTextChanged="TextBox1_OntTextChanged" />

protected void TextBox1_OntTextChanged(object sender, EventArgs e)
{
    if (TextBox1.Text.Length > 0)
    {
        Button1.Enabled = true;
    }
    else
    {
        Button1.Enabled = false;
    }
}

A: private void textBox1_TextChanged(object sender, EventArgs e) {
    button1.Enabled = true;
}


text:
Q: How to get full file path of magento file using FIREBUG or INSPECT. Mozilla extension. Is there any way. I am using editor Firebug extension of Mozilla to do temporary editing of my website pages. It is really easy to edit through Firebug & also it is very difficult to locate the file which we are editing. Magento website file structure is very difficult to understand. Is there any way to locate the file which we are editing through Firebug & edit that file for permanent changes. The provided answers does not giving me all full location of files which is i am editing. So is there any easy way to recognize the location of file in Magento file structure.

A: You can simply enable Template Path Hints by:

*

*logging to the backend

*access System > Configuration > Developer

*switch the store view to your current store by using the top left scope switcher

*set Template Hints Path to Yes in the Debug section

A: We have a grep command to search the exact string among the files.
For example in the welcome message has class called welcome-msg

grep -i -n -r "welcome-msg" magento_root/app/design

If it is a Welcome message, no code is needed for this.

Go to System - Configuration - General - Design - Header


text:
Q: Vector can't be NULL, What should I return instead of NULL? I want to return an alternate to NULL for the vector as vectors can't be NULL also I don't want to return an empty vector its already returned in another condition.
std::vector<int> how_sum(long target_sum, std::vector<int> numbers, std::map<int, std::vector<int>> &memo)
{
    . . .

    if (target_sum == 0)
        return {};    // empty vector returned here

    if (target_sum < 0)
        // return an alternate to NULL vector

    . . .
}


text:
Q: How do I create and then declare a linked list in a linked list in c# using classes? So, I'm trying to create a linked list inside each element of a linked list but I have no idea how to fill up the inner list with elements.
I first declare the outer list like this
RoomList<int> room = new RoomList<int>();

This is the class structure I use (not sure if even this is correct)
public class RoomList<T>
{
    DailyList head;

    public class DailyList
    {
        DailyListElement head;
        DailyListElement next;

        class DailyListElement
        {
            public T data;
            public DailyListElement next;
        }
    }
}

And this is a function I use to create a DailyList object
public void DailyListCreate()
{
    DailyList newDailyList = new DailyList();
}

But I don't know how to add a DailyListElement. I hope this makes sense.
So I want to find out how to fill up the DailyList with DailyListElements.

A: You need to implement a method that will add a new element.
You could do this by traversing the elements until you reach the first one where next is null, then assign the new element to next.
Or you could maybe also maintain a pointer to the last element and access it directly.

A: I tried a linked list within a linked list based on your provided code. In there I have added the methods to add a new node and get all nodes at both levels (outer and inner linked lists). Please find the code below for the linked list structure as well as the client code:
The linked list structure
public class RoomList<T> where T : class
{
    private DailyList current;
    private DailyList head;

    public void Add(DailyList newItem)
    {
        if(current != null)
            current.next = newItem;
        current = newItem;
        if(head == null)
            head = current;
    }

    public IEnumerable<DailyList> GetAllNodes()
    {
        DailyList current  = head;
        List<DailyList> lst = new List<DailyList>();
        while (current != null)
        {
            lst.Add(current);
            current = current.next;
        }
        return lst;
    }

    public class DailyList
    {
        public DailyList next;
        private DailyListElement head;
        private DailyListElement current;

        public void Add(DailyListElement newItem)
        {
            if(current != null)
                current.next = newItem;
            current = newItem;
            if(head == null)
                head = current;
        }

        public IEnumerable<DailyListElement> GetAllNodes()
        {
            DailyListElement current  = head;
            List<DailyListElement> lst = new List<DailyListElement>();
            while (current != null)
            {
                lst.Add(current);
                current = current.next;
            }
            return lst;
        }

        public class DailyListElement
        {
            public T data;
            public DailyListElement next;
        }
    }
}

The client code:
using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        var lst =new RoomList<string>();

        var upperNode = new RoomList<string>.DailyList();

        var element = new RoomList<string>.DailyList.DailyListElement();
        element.data = "first";
        upperNode.Add(element);

        element = new RoomList<string>.DailyList.DailyListElement();
        element.data = "second";
        upperNode.Add(element);

        lst.Add(upperNode);

        upperNode = new RoomList<string>.DailyList();

        element = new RoomList<string>.DailyList.DailyListElement();
        element.data = "third";
        upperNode.Add(element);

        element = new RoomList<string>.DailyList.DailyListElement();
        element.data = "fourth";
        upperNode.Add(element);

        lst.Add(upperNode);

        foreach(var item in lst.GetAllNodes())
        {
            foreach(var child in item.GetAllNodes())
            {
                Console.WriteLine(child.data);
            }
        }
    }
}

A: You need to add methods Add to your RoomList and DailyList classes.
public class RoomList<T>
{
    public DailyList head;

    public DailyList Add()
    {
        var newItem = new DailyList();
        if (head != null) head.next = newItem;
        head = newItem;
        return newItem;
    }

    public class DailyList
    {
        public DailyList next;
        public DailyListElement head;

        public DailyListElement Add()
        {
            var newItem = new DailyListElement();
            if (head != null) head.next = newItem;
            head = newItem;
            return newItem;
        }

        public class DailyListElement
        {
            public T data;
            public DailyListElement next;
        }
    }
}

Usage example:
var roomList = new RoomList<string>();
var dailyList = roomList.Add();
var dailyListElement = dailyList.Add();
dailyListElement.data = "StackOverflow rocks!";
Console.WriteLine(roomList.head.head.data);

Output:

StackOverflow rocks!


text:
Q: How to make a Picturebox stop Auto-Validate? I have got problem with an Picturebox(picWorld). When I want to change its size and location like this code, It took much time because I think it is updating twice:
private void lblWorld_MouseEnter(object sender, EventArgs e)
{
    picWorld.Size = new Size(148, 148);
    picWorld.Location = new Point(picWorld.Location.X - 12, picWorld.Location.Y - 12);
}

Is there any way to make it faster?

A: Try hiding it, moving it, then showing it:
private void lblWorld_MouseEnter(object sender, EventArgs e)
{
    picWorld.Hide();
    picWorld.Size = new Size(148, 148);
    picWorld.Location = new Point(picWorld.Location.X - 12, picWorld.Location.Y - 12);
    picWorld.Show();
}

A: create an outside variable (prefer static) to store when to start and when to end, so:
bool now=false;

private void lblWorld_MouseEnter(object sender, EventArgs e)
{
if (!now)
{
now = true;
    picWorld.Size = new Size(148, 148);
    picWorld.Location = new Point(picWorld.Location.X - 12,     picWorld.Location.Y - 12);
now = false;
}

}


text:
Q: why is this value being set to 0? O_O chMB() is a define to MessageBoxA( 0, text, "title", MB_OK );so it displays the text and I can see results. My problem is with the following codez:
CString szWow;
szWow.Format( "%u", idCandidate );
chMB( szWow );

const __int64 i64set = i64VoteAmount+1;

CString addvote;
addvote.Format( "UPDATE dbo.CONSULENTRIES set m_uVoteAmount = %u WHERE m_idCandidate = %u", i64set, idCandidate );

chMB( addvote );

chMB( szWow ); displayes 5
althought chMB( addVote ) displayes:
UPDATE dbo.CONSULENTRIES set m_uVoteAmount = 1 WHERE m_idCandidate = 0
why is idCandidate 0 on this string format??? O___O
in case you need here is teh full codez:
VOTEAPPL CConsulApplication::VoteForApplied( const u_long idVoter, const __int64 idCandidate )
{
if( idVoter && idCandidate )
{

    /* Check if alredy voted */
    CQuery* pQuery = new CQuery;
    if( !pQuery->Connect( 3, DSN_NAME_CHARACTER01, DB_ADMIN_ID_CHARACTER01, DB_ADMIN_PASS_CHARACTER01 ) )
    {
        pQuery->DisConnect();
        SAFE_DELETE( pQuery );
        return VAPL_FAILURE;
    }

    CString szVoted;
    szVoted.Format( "SELECT * FROM dbo.CONSULVOTE WHERE m_idVoter = %u", idVoter );

    if( !pQuery->Exec( szVoted ) )
    {
        pQuery->DisConnect();
        SAFE_DELETE( pQuery );
        return VAPL_FAILURE;
    }

    pQuery->Fetch();

    __int64 i64Voter = pQuery->GetInt64( "m_idVoter" );

    if( i64Voter != 0 )
    {
        pQuery->DisConnect();
        SAFE_DELETE( pQuery );
        return VAPL_VOTED;
    }

    pQuery->DisConnect();
    SAFE_DELETE( pQuery );

    /* Get content and check if candidate exists */

    CQuery* pQuery2 = new CQuery;
    if( !pQuery2->Connect( 3, DSN_NAME_CHARACTER01, DB_ADMIN_ID_CHARACTER01, DB_ADMIN_PASS_CHARACTER01 ) )
    {
        pQuery2->DisConnect();
        SAFE_DELETE( pQuery2 );
        return VAPL_FAILURE;
    }

    CString szCandidate;
    szCandidate.Format( "SELECT * FROM dbo.CONSULENTRIES WHERE m_idCandidate = %u", idCandidate );

    if( !pQuery2->Exec( szCandidate ) )
    {
        pQuery2->DisConnect();
        SAFE_DELETE( pQuery2 );
        return VAPL_FAILURE;
    }

    pQuery2->Fetch();

    __int64 i64Candidate = pQuery2->GetInt64( "m_idCandidate" );
    __int64 i64VoteAmount = pQuery2->GetInt64( "m_uVoteAmount" );
    if( i64Candidate != 0 )
    {
        /* Insert at database that this guy has voted */
        CQuery* pInsertQuery = new CQuery;
        if( !pInsertQuery->Connect( 3, DSN_NAME_CHARACTER01, DB_ADMIN_ID_CHARACTER01, DB_ADMIN_PASS_CHARACTER01 ) )
        {
            pInsertQuery->DisConnect();
            SAFE_DELETE( pInsertQuery );
            return VAPL_FAILURE;
        }

        CString szInsert;
        szInsert.Format( "INSERT INTO dbo.CONSULVOTE values(%u,%u)", idVoter, idCandidate );

        if( !pInsertQuery->Exec( szInsert ) )
        {
            pInsertQuery->DisConnect();
            SAFE_DELETE( pInsertQuery );
            return VAPL_FAILURE;
        }

        pInsertQuery->DisConnect();
        SAFE_DELETE( pInsertQuery );

        /* Update vote amount */

        CQuery* pUpdate = new CQuery;
        if( !pUpdate->Connect( 3, DSN_NAME_CHARACTER01, DB_ADMIN_ID_CHARACTER01, DB_ADMIN_PASS_CHARACTER01 ) )
        {
            pUpdate->DisConnect();
            SAFE_DELETE( pUpdate );
            return VAPL_FAILURE;
        }

        CString szWow;
        szWow.Format( "%u", idCandidate );
        chMB( szWow );

        const __int64 i64set = i64VoteAmount+1;

        CString addvote;
        addvote.Format( "UPDATE dbo.CONSULENTRIES set m_uVoteAmount = %u WHERE m_idCandidate = %u", i64set, idCandidate );

        chMB( addvote );

        if( !pUpdate->Exec( addvote ) )
        {
            pUpdate->DisConnect();
            SAFE_DELETE( pUpdate );
            return VAPL_FAILURE;
        }

        pUpdate->DisConnect();
        SAFE_DELETE( pUpdate );

        return VAPL_SUCCESS;

    }

    pQuery2->DisConnect();
    SAFE_DELETE( pQuery2 );
    return VAPL_FAILURE;

}
return VAPL_FAILURE;

}

A: The problem is here:
addvote.Format( "UPDATE dbo.CONSULENTRIES set m_uVoteAmount = %u WHERE m_idCandidate = %u", i64set, idCandidate );

The format string contains %u while the variable after the format string (i64set) is of a wrong type (__int64).
Try changing the type (%u corresponds to type unsigned int) or the format specifier:
addvote.Format( "UPDATE dbo.CONSULENTRIES set m_uVoteAmount = %I64d WHERE m_idCandidate = %u", i64set, idCandidate );


text:
Q: #pragma warning(push) without #pragma warning(pop) Using C++ Native solution in Visual Studio 2010.
#pragma warning (push) is used in the beginning of the cpp file, after all the includes. After that there are couple of disabled warning by #pragma warning(disable : XXXX).
What are possible consequences of omitting #pragma warning(pop) at the end of the file?
Thanks

A: If you have any other source files that #include that cpp file, then the warning state when compiling the outer file will be messed up -- it could fail to give warnings when the warnings were warranted.
Note, however, that #includeing a cpp file is considered bad form and a code smell; there are certain, rare, situations where it might be the right thing to do (such as a build system that #includes many source files into one to reduce compilation times, sort of like precompiled headers), but almost always it's the wrong thing to do, even if it manages to compile and link without errors.
If that source file is never #included anywhere else, then failing to have a #pragma warning(pop) will not have any adverse consequences, assuming the compiler doesn't complain about that mismatch in the first place.

A: Since this is a compiler only setting, it won't have any impact on the program itself. It may though screw up warnings for external includes.


text:
Q: How to calculate day of the week for RTC? I am using MCP7940 RTC from microchip it requires to enter the day of the week as part of updating RTC with date. So how should I calculate day of the week based on the date provided by the user?

A: If you want to calculate the day-of-week yourself, here's a C implementation of part of a Perl module I wrote about 20 years ago. I like this algorithm because it doesn't require any looping or a table of month lengths. Note that ints are assumed to be 32 bits.
/* Returns the number of days to the start of the specified year, taking leap
 * years into account, but not the shift from the Julian calendar to the
 * Gregorian calendar. Instead, it is as though the Gregorian calendar is
 * extrapolated back in time to a hypothetical "year zero".
 */
int leap (int year)
{
  return year*365 + (year/4) - (year/100) + (year/400);
}

/* Returns a number representing the number of days since March 1 in the
 * hypothetical year 0, not counting the change from the Julian calendar
 * to the Gregorian calendar that occured in the 16th century. This
 * algorithm is loosely based on a function known as "Zeller's Congruence".
 * This number MOD 7 gives the day of week, where 0 = Monday and 6 = Sunday.
 */
int zeller (int year, int month, int day)
{
  year += ((month+9)/12) - 1;
  month = (month+9) % 12;
  return leap (year) + month*30 + ((6*month+5)/10) + day + 1;
}

/* Returns the day of week (1=Monday, 7=Sunday) for a given date.
 */
int dow (int year, int month, int day)
{
  return (zeller (year, month, day) % 7) + 1;
}

A: According to the datasheet at address 0x03 in table 4-1 there is a field 'Day'. At the end of the line there is a short description:
\begin{array}{|c|c|c|} \text{Address} & \text{Bit7:3} & \text{Bit2:0} & \text{Function} & \text{Range} \\
\hline
\text{0x03}&\text{...}&\text{Day}&\text{Day}&\text{1-7}
\end{array}
This means that the day can be set to any number ranging from 1 through 7. You can pick your own convention which day of the week is. On POSIX systems Monday is defined as 1, I think that is a good standard. Then Tuesday = 2; Wednesday = 3; ...
Day = 0 is not documented, so don't use it.
On Linux this number can easily be found using the command date +%u, which today answers 6 as it is saturday. If you want to calculate this locally on your PIC, you'll have to find the C-library that implements the formula, I believe strftime in <time.h> does just that, but I'm not enough C programmer to explain how to use that particular library. It is a commonly used library, so documentation is easy to find.

A: I suggest you use the RTClib library
#include <Wire.h>
#include "RTClib.h"

RTC_DS3231 rtc;

char daysOfTheWeek[7][12] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};

void setup () {
  Serial.begin(9600);
  delay(3000); // wait for console opening

  if (! rtc.begin()) {
    Serial.println("Couldn't find RTC");
    while (1);
  }

  if (rtc.lostPower()) {
    Serial.println("RTC lost power, lets set the time!");

    // Comment out below lines once you set the date & time.
    // Following line sets the RTC to the date & time this sketch was compiled
    rtc.adjust(DateTime(F(__DATE__), F(__TIME__)));

    // Following line sets the RTC with an explicit date & time
    // for example to set January 27 2017 at 12:56 you would call:
    // rtc.adjust(DateTime(2017, 1, 27, 12, 56, 0));
  }
}

void loop () {
    DateTime now = rtc.now();

    Serial.println("Current Date & Time: ");
    Serial.print(now.year(), DEC);
    Serial.print('/');
    Serial.print(now.month(), DEC);
    Serial.print('/');
    Serial.print(now.day(), DEC);
    Serial.print(" (");
    Serial.print(daysOfTheWeek[now.dayOfTheWeek()]);
    Serial.print(") ");
    Serial.print(now.hour(), DEC);
    Serial.print(':');
    Serial.print(now.minute(), DEC);
    Serial.print(':');
    Serial.print(now.second(), DEC);
    Serial.println();

    Serial.println("Unix Time: ");
    Serial.print("elapsed ");
    Serial.print(now.unixtime());
    Serial.print(" seconds/");
    Serial.print(now.unixtime() / 86400L);
    Serial.println(" days since 1/1/1970");

    // calculate a date which is 7 days & 30 seconds into the future
    DateTime future (now + TimeSpan(7,0,0,30));

    Serial.println("Future Date & Time (Now + 7days & 30s): ");
    Serial.print(future.year(), DEC);
    Serial.print('/');
    Serial.print(future.month(), DEC);
    Serial.print('/');
    Serial.print(future.day(), DEC);
    Serial.print(' ');
    Serial.print(future.hour(), DEC);
    Serial.print(':');
    Serial.print(future.minute(), DEC);
    Serial.print(':');
    Serial.print(future.second(), DEC);
    Serial.println();
    Serial.println();

    delay(1000);
}

A: Day of week is Arbitrary. You define it. You could use the Julian Sunday = Day 1. You could use Monday as Day 1 because Sunday is the 7th day. You could use Friday as Day 1 because it's the first day of the weekend. You could use Tuesday as Day 1 because you hate Mondays.


text:
Q: How to pass the querystring parameter into FormControl in vb.net I am passing a value from one form to the other. The second form in inserting the data field into the table. How do I pass the ID(strPID) passed from the first form into the form control PatronIDTextBox of the second form?
VB.Code: on Page load -- strPID = Request.QueryString("value1")
Form control:
<InsertItemTemplate>
    PatronID:
   <asp:TextBox ID="PatronIDTextBox" runat="server" Text='<%# Bind("PatronID") %>' />

Thanks

Ok, Now I am trying to say it this way in object datasource so I can send it into insert statement without being displayed on the screen.
<Insert Parameters>
    <asp:QueryStringParameter Name="PatronID" Type="int32" QueryStringField="value1" />
    <asp:QueryStringParameter Name="PatronName" Type="String" QueryStringField="value2" />
</InsertParameter>

InsertCommand="INSERT INTO [tblIncident] ([PatronID], [PatronName]) values (@PatronID, @PatronName)

A: Have you tried directly putting the value into the textbox?  Like this:
<asp:TextBox ID="PatronIDTextBox" runat="server" Text='<%= Request.QueryString("Value1") %>' />

Just be careful, because this approach could allow a XSS attack.  You might want to read-up on those.

A: I deleted the text box for both id and name and instead I modified the objectdatasource Insert statement as follows. The value of value1 and value2 is captured on page load event.
<InsertParameters>
<asp:QueryStringParameter Name="PatronID" Type="Int32" QueryStringField="value1" />
<asp:QueryStringParameter Name="PatronName" Type="String" QueryStringField="value2"/>
</InsertParameters>


text:
Q: Finding number of elements in an array using a static variable I'm working on a project for a vehicle info system. I have stored all the instances in an array and I have to print out the number of elements/instances I have in it using a static variable. I tried the code below but I kept getting 0 I guess because it references the count defined in the class (which is initialized to 0) instead of the count in the constructor which has the total number of instances. How can I fix this?
package edu.uga.cs1302.vehicles;

import java.util.Scanner;

public class vehicleInstancesAndMenu {
static int count;

public vehicleInstancesAndMenu() {
    menu();
}//constructor

public void vehicles() {
    Vehicle[] vehicles = new Vehicle[15];
    vehicles[0] = new Airplane("Airbus A220-100", "Delta Airlines", "2019", 2, 120, 300, 221, 250);
    vehicles[1] = new Airplane("Airbus A319-100", "Delta Airlines", "2018", 2, 200, 450, 319, 300);
    vehicles[2] = new Airplane("Airbus A320-200", "Delta Airlines", "2018", 2, 220, 500, 320, 320);

    vehicles[3] = new Automobile("Corolla LE", "Toyota", "2020", 300, 6, 150);
    vehicles[4] = new Automobile("Civic SE", "Honda", "2018", 310, 6, 160);
    vehicles[5] = new Automobile("Sentra", "Nissan", "2019", 360, 6, 200);

    vehicles[6] = new Ship("APM - Maersk", "Maersk", "1904", 400000, "Carnival",2695, 35);
    vehicles[7] = new Ship("MSC", "Mediterranean Shipping Company", "1970", 30000 ,"Mediterranean Shipping Company",2565, 32);
    vehicles[8] = new Ship("COSCO", "China Ocean Shipping Company", "1990", 650000, "China Ocean Shipping Company",36201, 40);

    vehicles[9] =  new Tesla("Tesla Model 3", "Tesla", "2020", 1, 250, 200, 6, 300);
    vehicles[10] = new Tesla("Tesla Model S", "Tesla", "2020", 1, 300, 220, 6, 390);
    vehicles[11] = new Tesla("Tesla Model Y", "Tesla", "2020", 1, 400, 360, 6, 420);

    vehicles[12] = new BatMobile("Model A","Wayne Industries", "2020", 4 , 300, 600 , 40000, "Wayne Industries", 500, 320);
    vehicles[13] = new BatMobile("Model C", "Wayne Industries", "2019", 3 , 290, 400, 32000, "Wayne Industries", 450, 310);
    vehicles[14] = new BatMobile("Model T", "Wayne Industries", "2018",3 , 250, 360, 280000, "Wayne Industries", 370, 310);

for(int i = 0; i < vehicles.length; i++) {
        count = vehicles.length;
    //System.out.println(vehicles[i] );
}//for
    System.out.println(count);
    }//vehicles

public void menu() {
    Scanner scan = new Scanner(System.in);
    String response;

    System.out.println("Welcome! \n1 - To see how many vehicles are in the system\n2 - To see the name and the class of each vehicle\n3 - To see which vehicles can fly.\n4 - To see which vehicles can float.\n5 - To see which vehicles can fly and float.\n6 - To see a description of each vehicle.\nh - to see brief help information for your system.\nq - To terminate the program.");
        response = scan.nextLine();

    switch(response) {
        case "1":
            if(response.equals("1")) {
                System.out.println(vehicleInstancesAndMenu.count);
            }
    }
}

}//vehicleInstancesAndMenu

A: You should be able to fix this by including vehicle();  in the menu() function, somewhere before your System.out.println('..'); line. Currently the function is never being called so it isn't counting up anything. And instead of using a loop in the vehicle() function, just set count = vehicles.length; as stated in the comment.

A: I am not sure where are you using a loop to get the count. Below is the code which give you count 15 for every reason. using different constructor or using class name.
public class HelloWorld {
static int  count = 0;
public HelloWorld() {
    String[] strs = new String[15];
    for (int i = 0; i < strs.length; i++) {
        strs[i] = "Some String _ " + i;
    }
    count = strs.length;
    System.out.println("Cons: " + count);
}

public HelloWorld(int x) {
    System.out.println("Cons: " + count);
}

public static void main(String[] args) {
    new HelloWorld();
    System.out.println("In main-" + count);
    new HelloWorld(10);
    System.out.println("Using Class name : " + HelloWorld.count);
}

}
Output
Cons: 15
In main-15
Cons: 15
Using Class name : 15


text:
Q: Is "AllowUnsafeUpdates" available in SharePoint Online? There are a lot of other discussions on AllowUnsafeUpdates, but none mention SharePoint Online. Is AllowUnsafeUpdates available in SharePoint Online? If not, are there alternatives or manual actions to achieve the same? Thank you.

A: AllowUnsafeUpdates property is not available in CSOM.
There are no alternatives for that as well.
To update author column as per your comment, you can try something as below:
Microsoft.SharePoint.Client.User user = context.Web.EnsureUser("i:0#.f|membership|user@tenant.onmicrosoft.com");
context.Load(user);
context.ExecuteQuery();

FieldUserValue userValue = new FieldUserValue();
userValue.LookupId = user.Id;

listItem["Author"] = userValue;
listItem.Update();
context.ExecuteQuery();

A: Silly as it sounds, excellent code by @Gautam Sheth does not work. Please explore this answer for a weird hack necessary to update Author info in addition to valid code provided here. I refused to believe my eyes reading this. But yes, it works. All credits to original author.


text:
Q: Lync 2010 UMCA 3.0 schedule conference join users automatically I have implemented a service, that is capable of scheduling conference meetings in Lync 2010, that can be used for external users using the WEB client.
But there is one problem still. I want to be able to schedule meetings far into the future, and when a user loggs in via the WEB client, all the invited users should automatically be added to the conference. Is this possible? And do I have to configure this on the Lync server, or can this be achieved when I schedule the meeting (in my C# code).

A: You need to share the meeting URI for your scheduled conference with the invitee.  You can get the meeting URI when you schedule the conference in your C# code. You can use the conference property options to control whether the user waits in a lobby or is directly admitted into conference.


text:
Q: Integrate $(\sin x)^{\sin x}\,dx$ Is there any way to calculate $$\int{(\sin x)^{\sin x}\,dx}$$
I do this steps:

A:
Is there any way to calculate $\displaystyle\int{(\sin x)^{\sin x}\,dx}$ ?

No. See Liouville's theorem and the Risch algorithm.

A: Hint:
$\int(\sin x)^{\sin x}~dx$
$=\int(e^{\ln\sin x})^{\sin x}~dx$
$=\int e^{\sin x\ln\sin x}~dx$
$=\int\sum\limits_{n=0}^\infty\dfrac{\sin^nx(\ln\sin x)^n}{n!}dx$
$=\int\left(1+\sum\limits_{n=1}^\infty\dfrac{\sin^nx(\ln\sin x)^n}{n!}\right)dx$


text:
Q: Does JDBC driver for MongoDb exist? I am trying to add mongodb support for my little java project in which I used hibernate, mysql and postgresql. What library do I have to install?
 <!-- https://mvnrepository.com/artifact/org.mongodb/mongo-java-driver -->
 <dependency>
      <groupId>org.mongodb</groupId>
      <artifactId>mongo-java-driver</artifactId>
      <version>3.8.0</version>
 </dependency>

This code above does not add mongo jdbc drivers as i am getting this error
    WARN: HHH000342: Could not obtain connection to query metadata : The application must supply JDBC connections
    Exception in thread "main" org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214)
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:179)
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:119)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904)
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935)
    at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:56)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at Main.main(Main.java:8)
    Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100)
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137)
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35)
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:94)
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263)
    ... 14 more

A: There are more than a handful of MongoDB JDBC drivers out there, but most of them are proprietary and require some license fee, the one free and open-source jdbc driver for MongoDB I can find is from DbSchema, which is available here:
https://www.dbschema.com/mongodb-jdbc-driver.html
Source code is on bitbucket:
https://bitbucket.org/dbschema/mongodb-jdbc-driver/src/master/
It's completely free and works perfectly for me.