text:
Q: Meteor observeChanges changed fires more than once This Meteor server code needs to invoke myFunc() only once when myArray.length === 3 but it gets fired more than once. How can it be fixed? thx
let name = 'john';
myCol.find({name: name}).observeChanges({
   changed: function (id, fields) {
     if (fields.myArr) {
        if (fields.myArr.length === 3) {
            console.log('setting time out for: ' + name); // <--- prints more than once
            let doc = myCol.find({name: name});
            setTimeout(Meteor.bindEnvironment(function () {
              ddpCall(doc);
           }), 15000);
        }  else if (fields.myArr.length === 4) {
              ddpCall(doc);
        }
    }
});

let dppCall = function (doc) {
  if (doc.search === 'required') {
      myCol.update({_id: doc._id}, {$unset: {search: ''}});
      ddpConn.call('myFunc', doc);
  }
}

// some where else in the ddp call code
'myFunc': function () {
    // some logic here which changes the myArr
    myCol.update({name: name}, {$set: myObj, $addToSet: {myArr: myLabel}}); // push myLabel
});

A: I am not sure you would really need an observer for this. If you have a method writing into this array, why don't you do the whole thing inside the method. If there is any blocking actions like sending sms or email you can use the Meteor this.unblock(). I mention the unblocking because I see you use a long timeout there.
When you avail of the variable with the same name you can skip the declaration:
const name = 'john';
myCol.find({name})....

the method would be like:
'meteormethod' with simple schema or validation etc and inside the method:
 myCol.update({name}, {$set: myObj, $addToSet: {myArr: myLabel}})
 const myArr = myCol.findOne({name}).myArr  // hope 'name' is unique
 if( myArr && myArr.length === 3 ) { fire what you need (with unblock if required) }
end of your method

If your required action is server side, your method can call a server side method (which is the typical case for emailing).
Just to keep in mind that $addToSet will not change the length of your array if the value exists in the array Mongo $addToSet
I personally prefer to do many things like in the electronic circuits, kind of if this...that just to make sure I do not have to many different logics implemented in a project. I am not sure if the "wireframe" principle may apply to you here.
Also you can simplify your code above by merging the 2 'if' functions:
if (fields && fields.myArr && fields.myArr.length === 3 ) { ... }

Regards,
Paul


text:
Q: Comparing AUC, log loss and accuracy scores between models I have the following evaluation metrics on the test set, after running 6 models for a binary classification problem:
  accuracy logloss   AUC
1   19%      0.45   0.54
2   67%      0.62   0.67
3   66%      0.63   0.68
4   67%      0.62   0.66
5   63%      0.61   0.66
6   65%      0.68   0.42

I have the following questions:

*

*How can model 1 be the best in terms of logloss (the logloss is the closest to 0) since it performs the worst (in terms of accuracy). What does that mean ?

*How come does model 6 have lower AUC score than e.g. model 5, when model 6 has better accuracy. What does that mean ?

*Is there a way to say which of these 6 models is the best ?

A: Very briefly, with links (as parts of this have already been discussed elsewhere)...

How can model 1 be the best in terms of logloss (the logloss is the closest to 0) since it performs the worst (in terms of accuracy). What does that mean ?

Although loss is a proxy for the accuracy (or vice versa), it is not a very reliable one in that matter. A closer look at the specific mechanics between accuracy and loss may be useful here; consider the following SO threads (disclaimer: answers are mine):

*

*Loss & accuracy - Are these reasonable learning curves?

*How does Keras evaluate the accuracy? (despite the title, it is a general exposition, and not confined to Keras in particular)

To elaborate a little:
Assuming a sample with true label y=1, a probabilistic prediction from the classifier of p=0.51, and a decision threshold of 0.5 (i.e. for p>0.5 we classify as 1, otherwise as 0), the contribution of this sample to the accuracy is 1/n (i.e. positive), while the loss is
-log(p) = -log(0.51) = 0.6733446

Now, assume another sample again with true y=1, but now with a probabilistic prediction of p=0.99; the contribution to the accuracy will be the same, while the loss now will be:
-log(p) = -log(0.99) = 0.01005034

So, for two samples that are both correctly classified (i.e. they contribute positively to the accuracy by the exact same quantity), we have a rather huge difference in the corresponding losses...
Although what you present here seems rather extreme, it shouldn't be difficult to imagine a situation where many samples of y=1 will be around the area of p=0.49, hence giving a relatively low loss but a zero contribution to accuracy nonetheless...

How come does model 6 have lower AUC score than e.g. model 5, when model 6 has better accuracy. What does that mean ?

This one is easier.
According to my experience at least, most ML practitioners think that the AUC score measures something different from what it actually does: the common (and unfortunate) use is just like any other the-higher-the-better metric, like accuracy, which may naturally lead to puzzles like the one you express yourself.
The truth is that, roughly speaking, the AUC measures the performance of a binary classifier averaged across all possible decision thresholds. So, the AUC does not actually measure the performance of a particular deployed model (which includes the chosen decision threshold), but the averaged performance of a family of models across all thresholds (the vast majority of which are of course of not interest to you, as they will be never used).
For this reason, AUC has started receiving serious criticism in the literature (don't misread this - the analysis of the ROC curve itself is highly informative and useful); the Wikipedia entry and the references provided therein are highly recommended reading:

Thus, the practical value of the AUC measure has been called into question, raising the possibility that the AUC may actually introduce more uncertainty into machine learning classification accuracy comparisons than resolution.
[...]
One recent explanation of the problem with ROC AUC is that reducing the ROC Curve to a single number ignores the fact that it is about the tradeoffs between the different systems or performance points plotted and not the performance of an individual system

Emphasis mine - see also On the dangers of AUC...
Simple advice: don't use it.

Is there a way to say which of these 6 models is the best ?

Depends of the exact definition of "best"; if "best" means best for my own business problem that I am trying to solve (not an irrational definition for an ML practitioner), then it is the one that performs better according to the business metric appropriate for your problem that you have defined yourself. This can never be the AUC, and normally it is also not the loss...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does the .NET framework violate SOLID principles? I see some classes in the .net framework that support reading and writing, saving and loading, classes whose main responsibility is not them, for instance the Stream classes and the XML Dom/XLinq classes.

A: Let's touch on these one by one.
S is for Single Responsibility

*

*The single responsibility for XMLDocument is to provide APIs for traversing an XML document

*Yes, its interface has methods for saving and loading, but the implementation of XMLDocument doesn't actually save or load. It parses or unparses with respect to a abstraction, a "stream," which you'd have to supply to the XMLDocument in order for those methods to work. Parsing and unparsing is naturally associated with traversal. Persistence isn't handled by the class itself.

*Stream and StreamReader/Writer classes also do this.  They work on logical representations, a theoretical infinite byte array, which is actualized in one of the subtypes, such as a MemoryStream or FileStream.

O is for open/closed
Moot. All framework classes are closed to modification, unless you are doing something really weird.
L is for Liskov Substitution
Pretty sure you can substitute any type of stream when a steam is needed; whoever is using the stream generally won't care if it's a stream that goes to memory, to disk, or to a network connection. If there are differences in capability (e.g. a maybe a network stream doesn't provide random access) those capabilities are discoverable via properties in the base class, e.g. CanSeek.
I is for Interface Segregation
Microsoft has been a bit slow on providing interfaces for many of its classes. That being said, you can easily write code that works with abstract base types instead of concrete types, e.g. you can write code that works with any type of stream as long as it inherits from BaseStream.
D is for Dependency Inversion
XMLDocument and the stream classes both use dependency injection, following the principle of inversion of control. In fact StreamReader and StreamWriter are two of the earliest examples of this principle, since they take the underlying stream as a constructor argument (via a stream's abstract base implementation, which is as good as accepting an interface). XMLDocument uses DI by allowing an abstract base stream to be injected as a method argument to Save or Load.
So no, I don't agree with you, I think the .NET framework does a decent job of following SOLID.


text:
Q: Haskell Twitch (high level file watcher DSL) executing 2 times I want to use Twitch package to copy any javascript files in the "central" directory to the "back" and "front" directories. This is the code:
{-# LANGUAGE OverloadedStrings #-}

module Main where

import Data.List
  ( isPrefixOf
  , tails
  , findIndex
  )
import System.Directory
  ( createDirectoryIfMissing
  , removeDirectoryRecursive
  , copyFile
  )
import System.Directory.Recursive
  ( getSubdirsRecursive
  , getFilesRecursive
  )
import Twitch
  ( defaultMain
  , (|>)
  )

main :: IO ()
main = do

  putStrLn "Haskell works <(^u^)>"

  -- Copy central folder to back and front, and setup recopy when central changes
  copyCentral
  defaultMain $ do
    "./central/**/*.js" |> copyFileToBackAndFront

copyCentral :: IO ()
copyCentral = do

  createDirectoryIfMissing False "./back/src/central/"
  removeDirectoryRecursive "./back/src/central"
  createDirectoryIfMissing False "./front/src/central/"
  removeDirectoryRecursive "./front/src/central"

  centralFiles <- getFilesRecursive "./central/"
  centralDirs  <- getSubdirsRecursive "./central/"

  mapM_ (\d -> createDirectoryIfMissing True $ "./back/src" ++ tail d) centralDirs
  mapM_ (\d -> createDirectoryIfMissing True $ "./front/src" ++ tail d) centralDirs
  mapM_ (\f -> copyFile f $ "./back/src" ++ tail f) centralFiles
  mapM_ (\f -> copyFile f $ "./front/src" ++ tail f) centralFiles

copyFileToBackAndFront :: FilePath -> IO ()
copyFileToBackAndFront absolutePath =
    maybe
      (putStrLn "Error in the file path")
      getRelativePathAndCopy
      (findIndex (isPrefixOf "central") (tails absolutePath))
  where
    getRelativePathAndCopy n = do
      let relativePath = drop n absolutePath
      copyFile relativePath $ "./back/src/"  ++ relativePath
      copyFile relativePath $ "./front/src/" ++ relativePath
      putStrLn $ "Copied file " ++ relativePath ++ " to back and front"

And surprisingly it works! But i get the putStrLn output 2 times:
Copied file central\models\Board\Board.js to back and front
Copied file central\models\Board\Board.js to back and front

And I suspect it may be because of the program running in 2 threads, because sometimes I get interlaced output:
CCooppiieedd  ffiillee  cceennttrraall\\mmooddeellss\\BBooaarrdd\\BBooaarrdd..jjss  ttoo  bbaacckk  aanndd  ffrroonntt

CopiCeodp ifeidl ef icleen tcreanlt\rmaold\emlosd\eBlosa\rBdo\aBroda\rBdo.ajrsd .tjos  btaoc kb aacnkd  afnrdo nftr
ont

Also this happends when i run cabal v2-repl, i just tried cabal v2-run myprogram & and it does not work at all :(
Any help with both issues please?


text:
Q: save data in wxRichTextCtrl I have found only two methods (SaveFile, LoadFile) which save in a file.
How can I use wxRichTextCtrl to save XML data directly in a variable?

A: You can use control.GetBuffer() to get RichTextBuffer and use RichTextXMLHandler to save buffer to a stream, which could be any file type object e.g. StringIO e.g. if rt is your rich text control
import cStringIO
buf = cStringIO.StringIO()
handler = wx.richtext.RichTextXMLHandler()
handler.SetFlags(wx.richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET)
handler.SaveStream(rt.GetBuffer(), buf)
print buf.getvalue()

here is a complete example which you can run and see it prints out xml, when you click outside rich text cntrl in frame
import wx
import wx.richtext

app = wx.App(False)
f=wx.Frame(None, title="Test")
f.Show()
rt = wx.richtext.RichTextCtrl(f, size=(200,200))
def onEvent(evt):
    import cStringIO
    buf = cStringIO.StringIO()
    handler = wx.richtext.RichTextXMLHandler()
    handler.SetFlags(wx.richtext.RICHTEXT_HANDLER_INCLUDE_STYLESHEET)
    handler.SaveStream(rt.GetBuffer(), buf)
    print buf.getvalue()

f.Bind(wx.EVT_LEFT_DOWN, onEvent)
app.MainLoop()

output:
<?xml version="1.0" encoding="UTF-8"?>
<richtext version="1.0.0.0" xmlns="http://www.wxwidgets.org">
  <paragraphlayout textcolor="#101010" fontsize="10" fontstyle="90" fontweight="90" fontunderlined="0" fontface="Sans" alignment="1" parspacingafter="10" parspacingbefore="0" linespacing="10">
    <paragraph>
      <text>sdsa</text>
    </paragraph>
  </paragraphlayout>
</richtext>


text:
Q: MVVM-Light PropertyChanged ViewModelBase I would like to understand how the MVVM light toolkit raises the PropertyChanged event.
I have a feeling that this may be obvious... but I can't satisfy my curiousity without 100% clarity!
I know that this event is raised for each RaisePropertyChanged called, but I'm confused as to why PropertyChanged is raised when the HasValidationErrors property is changed as well?
Thanks,
Richard

A: When it comes to ViewModels or any class that implements INotifyPropertyChanged it is part of the contract that every property should raise the event when the property value changes. This way there is no unexpected behavior.


text:
Q: Is there a way to figure out the security protocol of a wireless network purely from a probe response .pcap file? I am trying to analyze probe response .pcap files of a network to deduce the security protocol (as in wpa, wpa2, wep, open network).
I realized that in some beacon .pcaps, there is a tag with the wpa information and in the following image for example, it says that the WPA version is 1, meaning the security protocol is WPA. But in other beacon .pcaps that tag doesn't appear and I'm guessing it is not always there because that tag is vendor specific.

Either way, I couldn't find this tag in any probe response .pcaps and couldn't figure out the security protocol from the RSN Information tag. For example I tried checking if AES is in the Pairwise Cipher Suite List (since it isn't used in WPA, but is used in WPA2), but it appears in both WPA and WPA2 networks. Is there a reliable way to do this with any captured probe response packet?


text:
Q: Silverlight fetching latest version of data from database using WCF RIA Service One of the ambition of business application is to allows multiple users running the application at the same time to manage huge of data.
How do I get the latest version of data from the database with using WCF RIA Service?
I have tried to use the DomainCollectionView to display list of Product, and allows to perform search, but unfortunately, the search results display on the client is still the old version if I have modified the product name or product code or deleted records directly from the database by using SQL Management Studio or changes made by another user.
To get the latest version of data, I have to refresh my browser.
Sounds like the data are cached on the client side already.
Please advise.
Attached with my coding file using AdventureWorks as a sample,
please navigate to the ProductPage and try to type something on the search box.
http://www.mediafire.com/?l4aee46y3vljuv7
Thanks.

A: In the LoadProductSummaryList method, change the line
Return context.Load(context.GetProductSummaryListQuery.Where(Function(p) p.Name.Contains(SearchText))

to
Return context.Load(context.GetProductSummaryListQuery.Where(Function(p) p.Name.Contains(SearchText)), LoadBehavior.RefreshCurrent, True)

The data will be refreshed as per your needs.
Hope this helps...
Chris Anderson


text:
Q: Login Openshift with GitHub OpenShift has only creates github, but when I try rhc setup from terminal, do not know what username and password. I tried with the user and password github, but rejects it.
What would be the username and password ?.
thanks

A: Use OC, then go to https://console.preview.openshift.com/console/command-line.
There you will find a command line with a token to authenticate.
The rhc do not work with github authentication as far as I know

A: I'll repeat what others have said, but with screenshots:
Once you're logged in to the web interface, click the (?) icon in the top bar, select Command Line Tools entry:

This will show a page which includes exact oc login options you need to login.  Note you need to use the "copy to clipboard" button to actually get the token:

A: You need to login with your GitHub account, authorize the application, wait a while until an email comes to your GitHub email address, then login to GitHub again following the steps in the email. I did this and it worked.


text:
Q: Why does this code have an IndentationError? I am trying to write a program where the user enters a Int value then the int has to be compared using If statement and the result has to be printered and If the user enters a string then the message should be  "you have entered a string value".
Can you let me know what is wrong with my program
print ("Enter a value")
input()
if int (value) == 10:
print('The value is 10')
if (value) == str:       (Its wrong in here)
print (' Enter a Number not text')
elif int (value) == 12:
print('The value is not 10')
else:
print('The value is not a number')

Error message        File "<ipython-input-35-29c9dd2647d4>", line 6
     print (' Enter a Number not text') IndentationError: expected an indented block

A: print("Enter a value")
value = input()
if not value.isnumeric():
    print("Enter a Number not text")
elif int (value) == 10:
    print("The value is 10")
elif int (value) == 12:
    print("The value is not 10")


text:
Q: PHP Form gives success message but nothing in db I have the following PHP v.5.6.29
<?php
// Connect to the database
include_once("php_includes/db_connect.php");

error_reporting(E_ALL);
ini_set("display_errors", 1);

// Gather the posted data into local variables
$m = $_POST['MRN'];
$l = $_POST['LastName'];
$f = $_POST['FirstName'];
$s = $_POST['SSN'];

// Get user IP Address
$ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));

// Form data error handling
if($m == "" || $l == "" || $f == "" || $s == ""){
    echo "The form submission is missing data.";
} else {
    // End form data error handling
    $sql = "INSERT INTO nys_demographics (mrn, pt_last_name, pt_first_name, pt_ssn, ip_address, record_insert_dtime)
    VALUES('$m', '$l','$f','$s','$ip',now()";
    mysqli_query($db_connect, $sql);
    echo "insert success";
}

header("refresh:3; url=demographics.php");
?>

I get the success message but then there is nothing in the db table. Not sure what to do from here.

A: First print your success message only if insert actually was a success which you get from Boolean returned
if (mysqli_query($db_connect, $sql)) {
  echo "insert success";
} else {
  printf("Error: %s\n", mysqli_error($db_connect));
}

A: You can check to see if the query was successful by putting it in an if as per the PHP docs located here.

A: I've modified the code to include a boolean conditional check. This should work assuming you are also using mysqli_connect_errno in db_connect.php file.
<?php
    // Connect to the database
    include_once("php_includes/db_connect.php");

    error_reporting(E_ALL);
    ini_set("display_errors", 1);

    // Gather the posted data into local variables
    $m = $_POST['MRN'];
    $l = $_POST['LastName'];
    $f = $_POST['FirstName'];
    $s = $_POST['SSN'];

    // Get user IP Address
    $ip = preg_replace('#[^0-9.]#', '', getenv('REMOTE_ADDR'));

    // Form data error handling
    if($m == "" || $l == "" || $f == "" || $s == ""){
        echo "The form submission is missing data.";
    } else {
        // End form data error handling
        $sql = "INSERT INTO nys_demographics (mrn, pt_last_name, pt_first_name, pt_ssn, ip_address, record_insert_dtime)
        VALUES('$m', '$l','$f','$s','$ip',now()";
        if( mysqli_query($db_connect, $sql) ) { echo "insert success"; }
        else {  echo "error with insert"; }
    }

    header("refresh:3; url=demographics.php");
    ?>


text:
Q: Solr: Invalid Date String:'1996' I am new to Solr. I have indexed some data in my solr(5.1.1). My data has fields like contract_year whose value are like:
contract year: 1996
contract year: 2000

The field type of contract year is "int". I want to change the field type to "date" or "tdate" with just year . For that, I have edited my schema.xml and changed the field type of contract year from "int" to "date". After doing this and reindexing my data, I got this error:
Invalid Date String:'1996'

What should I do to change the field type to "date" and get the same result like
contract year: 1996

without changing the format of date. I want to get only the year(yyyy) from the date.
Thanks for your help

A: Nupur, the only format that Solr date field support is of the format like this yyyy-MM-dd'T'HH:mm:ss'Z'.So you will have to convert your date in a format like this to be accepted by Apache Solr .


text:
Q: Java input stream to character stream location mapping I have an input stream that is used to produces a stream of characters. For every given character that gets decoded from the stream I would like to know corresponding byte ranges in the original stream (start/end).
Is there a java library that is capable of doing this?


text: Q: Tensor product of Koszul complexes I am trying to understand the tensor product of Koszul complexes. So, let $A$ and $B$ be $R$-modules over some commutative ring $R$. I am looking at the Koszul complex $K_{A\otimes_R B}(1 \otimes \gamma)$ where $\gamma$ is some endomorphism on $B$. I think it is true that this complex is quasi-isomorphic to the tensor product of complexes $K_A(1) \otimes_R K_B(\gamma)$. But is this true if we look at $K_{A\otimes_R B}(1 \otimes \gamma_1, \ldots, 1 \otimes \gamma_d)$ for some $d>1$? If it helps assumptions on $A$ and $B$ may be added...


text:
Q: Multidimensional array calendar, how to fix simple issues I am trying to fix my Calendar (Month-March):
Mon Tue Wed Thu Fri Sat Sun
1   2   3   4   5   6   7
8   9   10  11  12  13  14
15  16  17  18  19  20  21
22  23  24  25  26  27  28
29  30  31  0   0   0   0
32  0   0   0   0   0   0

1) The first problem is that I can't stop counting after 31, as you can see I have 0 0 0 0 0 but in this place I would like to have empty space.
2) Second problem is that March is starting from Thursday, not from Monday, how to start counting days from Thursday?. This is my code:
public class MyPoorCalendar{
    public static void main(String[] args) {
        int firstday = 1;
        int mycalendar[][] = new int[6][7];
        String nameOfTheWeeks = "Mon\t" + "Tue\t" + "Wed\t" + "Thu\t" + "Fri\t" + "Sat\t" + "Sun\t";
        System.out.println(nameOfTheWeeks);

        //initializing
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                mycalendar[i][j] = firstday++;
                if (firstday > 31) {
                    break;
                }
            }
        }
        //printing
        for (int i = 0; i < 6; i++) {
            for (int j = 0; j < 7; j++) {
                System.out.print(mycalendar[i][j] + "\t");
                if (j == 6) {
                    System.out.println();
                }
            }
        }
    }
}

A: Just print a blank space when mycalendar[i][j] == 0
 System.out.print((mycalendar[i][j] == 0 ? " " : mycalendar[i][j]) + "\t");

When setting the values you should break out of the outer most for loop, currently you only break out of the inner most loop so do this instead
   for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            mycalendar[i][j] = firstday++;
        }
        if (firstday > 31) {
                break;
        }
    }

Lastly if you want to start at a different location in the calendar then you could place a counter that, when it equals 0 you start your days. For example if you wanted to start on Thursday you could do something like this
   int dayToStartOn = 4; //Thursday
   for (int i = 0; i < 6; i++) {
        for (int j = 0; j < 7; j++) {
            mycalendar[i][j] = dayToStartOn-- > 0 ? 0 : firstday++;
        }
        if (firstday > 31) {
                break;
        }
    }

A: You can do this (explanation in code):
// store the length of the month and the first day of month's weekday number
int lengthOfMonth = LocalDate.now().lengthOfMonth();
int firstDayOfMonthsWeekDay = LocalDate.now().withDayOfMonth(1).getDayOfWeek().getValue();

// use a labeled break statement to terminate the outer for loop when we reach the end of the month
month:
for (int i = 0; i < 6; i++) {
    for (int j = 0; j < 7; j++) {
        if(--firstDayOfMonthsWeekDay > 0){ // fixing first day of month's weekday to start counting from tuesday for example
            continue;
        }

        mycalendar[i][j] = firstday++;
        if (firstday > lengthOfMonth) {
            break month;                   // the execution will continue after the outer loop
        }
    }
}

for (int i = 0; i < 6; i++) {
    for (int j = 0; j < 7; j++) {
        System.out.print((mycalendar[i][j] == 0 ? " " : mycalendar[i][j]) + "\t");  // replace 0's in the array with spaces
        if (j == 6) {
            System.out.println();
        }
    }
}

Output:
Mon Tue Wed Thu Fri Sat Sun
            1   2   3   4
5   6   7   8   9   10  11
12  13  14  15  16  17  18
19  20  21  22  23  24  25
26  27  28  29  30  31

More information about labeled break here. And about the java.time api here.


text:
Q: TortoiseHG: undoing commit that fails I've been using TortoiseHG for some time now and I've been running into the same issue once in a while.
Sometimes, when I commit my work, it gives me an error, saying that one (or more) of my files is being used by another process. However, the commit still goes through and is visible in the repository browser.
Next, after closing the processes that caused the error, I reopen the commit dialog that says that there are still changes to be committed (meaning the first commit didn't really do anything). I do another commit, which accomplishes what I wanted to do in the first place, but now I have a different problem: the repository now has two heads. Of course, I'm forced to merge the two heads after this, but my process seems unclean.
Is there a better way to get around such a problem, such as by somehow undoing the commit (but not reverting my files), or should I not bother cleaning stuff like this up?

A: hg rollback at the command line should revert the commit but not the changes (I don't use tortoisehg, so unclear if it puts that in a nice UI).


text:
Q: How to access the anonymous inner class using ASM framework For example, I need to aceess the information in run() after the code compiled.
Class A{
    public static void main(String[] args){
        new Thread(new Runnable() {
            @Override
            public void run() {
                //something
            }
        }).start();
    }
}

I have extended the ASM ClassVisitor, how should I do to access the information in an anonymous inner class.
public class MyClassVisitor extends ClassVisitor {

    public MyClassVisitor(final ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public void visit(int version, int access, String name, String signature,
            String superName, String[] interfaces) {
        if (cv != null) {
            cv.visit(version, access, name, signature, superName, interfaces);
        }
    }

    @Override
    public void visitInnerClass(String name, String outerName, String innerName, int access) {
        //how should I do to access the information in an anonymous inner class
        super.visitInnerClass(name, outerName, innerName, access);
    }
}

A: You know that the name of anonymous inner class after compiled like Main$1. Based on this fact, we can access the method information by override visitMethod.
The code is as follows.
public class MyClassVisitor extends ClassVisitor {

    private String ownerClassName;

    public MyClassVisitor(final ClassVisitor cv) {
        super(Opcodes.ASM5, cv);
    }

    @Override
    public void visit(int version, int access, String name, String signature,
            String superName, String[] interfaces) {
        if (cv != null) {
            cv.visit(version, access, name, signature, superName, interfaces);
            ownerClassName = name;
        }
    }

    @Override
    public MethodVisitor visitMethod(int access, String name, String desc,
            String signature, String[] exceptions) {
        MethodVisitor mv = cv.visitMethod(access, name, desc, signature,
                exceptions);
        //the name of anonymous inner class after compiled was like this: Main$1
        String[] array = ownerClassName.split("$");
        boolean isNumber = false;
        if(array.length > 1){
            isNumber = array[array.length - 1].matches("[0-9]+");
        }
        //if it's an anonymous inner class and the method was not construction method
        if(isNumber && !name.equals("<init>")){
            //return my custom MethodVisitor to parse the method information
            return new MyMethodVisitor(mv);
        }
        return mv;
    }
}


text:
Q: Error running meteor in MAC I am trying to run meteor app on MAC without success with following error. Surprisingly other project is running properly in MAC and very this project runs properly on Windows. But in MAC I can't figure out what's wrong.
/Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/fibers/future.js:245
                        throw(ex);
                              ^
Error: Must throw non-empty error
    at Object.Future.throw (/Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/lib/node_modules/fibers/future.js:259:10)
    at /Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/tools/buildmessage.js:541:23
    at runWithEnvironment (/Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/tools/fiber-helpers.js:139:21)
    at /Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/tools/fiber-helpers.js:146:14
    at /Users/user1/.meteor/packages/meteor-tool/.1.1.4.xh5uo++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/tools/buildmessage.js:549:11

A: The issue is probably related problems fetching the packages, see https://github.com/meteor/meteor/issues/4921


text:
Q: Valor Capturado DataGridView Estoy intentando mostrar el valor de una consulta en SQL mediante un DataGridView. Para ser más preciso, al seleccionar un ítem del DataGridView me debe mostrar el valor de SQL. Es decir, en el DataGridView yo muestro el ID de los clientes, y al seleccionar un ítem quiero que me muestre el celular en un TextBox. El problema es queno me está mostrando nada.
public void llenarId() {//con este método lleno el datagridview
            try {
                string cadena = "cadenaConexion";
                using (SqlConnection con = new SqlConnection(cadena)) {
                    con.Open();
                    string query = "SELECT id FROM clientes GROUP BY id";
                    SqlCommand cmd = new SqlCommand(query, con);
                    SqlDataAdapter da = new SqlDataAdapter(cmd);
                    DataSet ds = new DataSet();
                    da.Fill(ds);
                    dtgId.DataSource = ds.Tables[0];
                    con.Close();
                }
            } catch(SqlException ex) {
                MessageBox.Show("Error: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

private void dtgId_CellContentClick(object sender, DataGridViewCellEventArgs e){//con este trato de capturar el dato y mostrarlo en un textbox
            var row = dtgId.Rows[e.RowIndex];
            var id = row.Cells["id"].Value.ToString();
            try
            {
                string conn = "cadenaConexion";
                using (SqlConnection con = new SqlConnection(conn)){
                    con.Open();
                    string sql = "SELECT celular FROM clientes WHERE id=@id";
                    SqlCommand cmd = new SqlCommand(sql, con);
                    cmd.Parameters.AddWithValue("@id", id);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read()){
                        txtNum.Text = Convert.ToString(reader["celular"]);
                    }
                }
            }
            catch (SqlException exc){
                MessageBox.Show("Error: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

¿Hay algún error? ¿Alguna sugerencia?

A: puedes usarlo asi:
Usa el evento CellDoubleClick para obtener el ID del datagrid asi:
if(e.ColumnIndex == 0)//numero de columna donde esta el ID
        {
string id= dgv.Rows[e.RowIndex].Cells[0].Value.ToString();
try
        {
            string conn = "cadenaConexion";
            using (SqlConnection con = new SqlConnection(conn)){
                con.Open();
                string sql = "SELECT celular FROM clientes WHERE id=@id";
                SqlCommand cmd = new SqlCommand(sql, con);
                cmd.Parameters.AddWithValue("@id", id);
                SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read()){
                    txtNum.Text = reader["celular"].ToString();
                }
            }
        }
        catch (SqlException exc){
            MessageBox.Show("Error: " + exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

}


text:
Q: Evaluate the integral $\int_0^\infty \frac{\sin(ax)}{x} \frac{\sin(bx)}{x}e^{-kx}dx$ I would like to evaluate the following integral:

$$\int_0^\infty \frac{\sin(ax)}{x} \frac{\sin(bx)}{x}e^{-kx}dx$$

I have made several attempts using some crude methods, the workout is way too long to format and type out, so I will make it as brief as possible.
Firstly, I evaluated the integral:

$$\int_0^\infty \frac{\sin(ax)}{x} \frac{\sin(bx)}{x}dx$$

Using integration by parts and the properties of definite integrals:

Setting $u=\sin(ax)\sin(bx)$ and $dv=x^{-2}$

Using:

*

*$\int_{-\infty}^\infty \frac{g(ax)}{x}dx = \int_{-\infty}^\infty \frac{g(x)}{x}dx$

*$\int_{-\infty}^\infty f(x)dx=\frac 1 2\int_{0}^\infty f(x)dx$

*$2\sin a\cos b=\sin(a+b)+\sin(a-b)$
I obtained:

$$\frac1 2b\pi$$

I tried the same approach with the original question, and obtained 3 sets of integrals:

*

*$\frac{1}{2}(a+b)\int_{0}^\infty \operatorname{sinc}xe^{-kx}dx = \frac{1}{2}(a+b)\arctan(k^{-1})$

*$\frac{1}{2}(b-a)\int_{0}^\infty \operatorname{sinc} xe^{-kx}dx = \frac{1}{2}(b-a)\arctan(k^{-1})$

*$(-\frac{1}{2}k)\int_{0}^\infty \frac {\sin(ax)\sin(bx)e^{-kx}}{x}dx$
(These 3 are all summed up)

For (1) and (2), the term $a$ cancels out as expected.
I have no idea how (1) and (2) resulted in $\arctan(k^{-1})$, I just put the intrgral in wolfram alpha. I think inverse Fourier Transforms were involved here. I also don't think $\int_{-\infty}^\infty \frac{g(ax)}{x}dx = \int_{-\infty}^\infty \frac{g(x)}{x}dx$ can be used here, since we have an $e^{-kx}$ term. I went with it just to see where I can get to.
I am unable to solve integral (3).
My second attempt involved dominant and monotone convergence theorems, which was a mess. I don't even know what I was trying to do, hence I will not type it out here. I'm 100% sure it is totally wrong.
We were given some hints:

There's a common and smart trigonometric identity involved, then invoke convergence theorems. The final answer looks very neat.

I suspect the "smart trigonometric identity" is the one listed above, and my answer for the integral without the exponent did indeed look very neat. However using the same method, I wasn't able to obtain the result I needed. It should be a lot easier if convergence theorems are used, at least I assume it would.
I appreciate any help or hints. I'd like to know how this was obtained:

$\int_{0}^\infty \operatorname{sinc} xe^{-kx}dx = \arctan(k^{-1})$

Also please pick out any mistakes I've made, as I am certain my method for the question was highly fallacious and/or mathematically unrigorous. I think I'm on the right track though.
Thanks in advance!

A: A common strategy is to write $x^{-n}=\frac{1}{\Gamma (n)}\int_0^\infty y^{n-1}e^{-xy}dy$. For example, $$\int_0^\infty\frac{\sin x}{x}e^{-kx}dx=\int_0^\infty dy\Bigg[\int_0^\infty e^{-(k+y)x}\sin x dx\Bigg]=\int_0^\infty\frac{dy}{(k+y)^2+1}.$$

A: I've solved the integral, the answer looks odd, and it is very very long. I'll post the results later. It's 5am the I have a class that begins at 10.
Basically, these are all wrong:

*

*$\frac{1}{2}(a+b)\int_{0}^\infty \operatorname{sinc}xe^{-kx}dx = \frac{1}{2}(a+b)\arctan(k^{-1})$

*$\frac{1}{2}(b-a)\int_{0}^\infty \operatorname{sinc} xe^{-kx}dx = \frac{1}{2}(b-a)\arctan(k^{-1})$

*$(-\frac{1}{2}k)\int_{0}^\infty \frac {\sin(ax)\sin(bx)e^{-kx}}{x}dx$
(These 3 are all summed up)

For 1 and 2, $(a+b)$ cannot be removed from the integral. The result has the inverse tangent function.
For 3, I used dominant convergence theorem which allowed me to differentiate within the integral. (I checked all conditions and they were satisfied) The result was a set of functions involving $ln(x)$.
Here's the the result looks like:

$$\int_0^\infty \frac{\sin(ax)}{x} \frac{\sin(bx)}{x}e^{-kx}dx=\frac{1}{2(a+b)}(\frac{\pi}{2}-arctan(\frac{k}{a+b})+\frac{1}{2(b-a)}(arctan(\frac{k}{b-a})-\frac{\pi}{2})+\frac{barctan(\frac{a-b}{k})}{k}+\frac{1}{2}ln((a+b)^2+k^2)-\frac{1}{2}ln((a-b)^2+k^2)$$

Which is just ridiculous. I assume it can be simplified into something nicer, or I just made a massive mistake somewhere in my 13 pages of writing. I'll know the result later today anyway. I'll post a proper solution if mine is wrong.


text:
Q: How to make Qt Dbus more responsive? (When the main thread is busy) I am using Qt DBus to monitor signals. However, as the main Qt thread is often busy with a long running task (a design I currently cannot change), there is a long delay between sending a qt-dbus message by another program an the slot being called. How can I reduce this delay?
I connect a slot to be called when a signal is received something like so:
#include <QtDBus>
#include <QString>
#include <QObject>

MyDbus : public QObject {
public:
    MyDbus() {
        QDBusConnection::systemBus().connect("", "path", "interface.com", "member", this, SLOT(mySlot(QString)));
    }

private slots:
    void mySlot(QString& message) const {
        // Do something.
    }
 };

Using Qt 4.8.6.


text:
Q: Pass Action Buttons in DataTables using ajax or php 'aoColumns': [
        {'bVisible':true}, // 0 full name
        {'bVisible':false}, // 1 first name
        {'bVisible':false}, // 2 last name
        {'bVisible':false}, // 3 title
        {'bVisible':true}, // 4 company
        {'bVisible':true}, // 5 email
        {'bVisible':true}, // 6 phone
        {'bVisible':false}, // 7 fax
        {'bVisible':false}, // 8 address1
        {'bVisible':false}, // 9 address2
        {'bVisible':false}, // 10 city
        {'bVisible':false}, // 11 state
        {'bVisible':false}, // 12 postal code
        {'bVisible':false}, // 13 country
        {'bVisible':false}, // 14 website
        {'bVisible':false}, // 15 facebook
        {'bVisible':false}, // 16 google+
        {'bVisible':false}, // 17 twitter
        {'bVisible':false}, // 18 linkedin
        {'bVisible':true}, // 19 source
        {'bVisible':true}, // 20 status
        {'bVisible':true}, // 21 type
        {'bVisible':false}, // 22 tags
        {'bVisible':false}, // 23 summary
        {'bVisible':false}, // 24 creation date
        {'bVisible':false}, // 25 last update date -- sort on this column
    ],

The above is columns created using ajax/datatables.
Please help me to add Action Buttons like Edit,Show,Delete in this with their respective record id.


text:
Q: WEBDAV Securit - 2FA ubuntu server at the moment I'm creating a server based on WEBDAV and I have a question:
Is it possible to add 2FA to my network map drive or some other type of additional intrusion prevention?
Apart from the firewall, password, ssl and encrypted files of course. (data will be sent outside the LAN).
(Any other advice on the security of sending data over the Internet is welcome :) )


text:
Q: Value not change by method they remain same I want to change my values using a method. Values change in method but not outside of it they remain same. I am trying to change these value by method 1st time so I have no idea about it they can change or not. any reference or help :)
CODE :
Method :-
void WeaponUpdateMethod (int objUpdateValue, float  time, string updateMoney, string saveData, float sliderValue)
{
    buttonClick.Play ();
    int t = objUpdateValue;
    if (t < 1 && totalMoney > 5000) {
        t = 1;
        totalMoney -= 5000;
        time = 12f;
    } else if (t != 2 && t < 2 && totalMoney > 10000) {
        t = 2;
        totalMoney -= 10000;
        time = 15f;
    } else if (t != 3 && t < 3 && totalMoney > 14000) {
        t = 3;
        totalMoney -= 14000;
        time = 17f;
    } else if (t != 4 && t < 4 && totalMoney > 25000) {
        t = 4;
        totalMoney -= 25000;
        time = 20f;
    }
    if (t == 0) {
        updateMoney = "" + 5000;
    } else if (t == 1) {
        updateMoney = "" + 10000;
    } else if (t == 2) {
        updateMoney = "" + 14000;
    } else if (t == 3) {
        updateMoney = "" + 25000;
    } else if (t == 4) {
        updateMoney = "full";
    }
    PlayerPrefs.SetInt (saveData, t);
    PlayerPrefs.SetInt ("totalMoney", totalMoney);
    PlayerPrefs.Save ();
    sliderValue = t;
    objUpdateValue = t;
    print (objUpdateValue);
    print(objUpdateValue+" from method");
}

Using Here :-
public void UpgradeSpeedUp ()
{
    // to upgrade speedUp
    WeaponUpdateMethod (speedUpUpdateValue, ManageSingleShotPowers.speedUpTime, speedUpUpdateMoney.text, "spedUpUpdate", speedUpSlider.value);

    print(speedUpUpdateValue +" from calling");
}

A: In C#, parameters are passed in by value by default.  You have to specify the parameters to be passed in by reference.  You do that by using the keyword ref in front of your parameters, for example, ref int objUpdateValue.


text:
Q: Sub-pixel rendering of fonts on the iPad Sub-pixel font rendering like ClearType dramatically improves font display resolution and improves screen readability. How would I program sub-pixel rendering of a font (in general), and how can this be achieved on the iPad (C, C++, or Objective-C on an iOS device)? Fonts are quite blurry at certain sizes on the iPad, and I know that the iPad's display would work well with this technique...
So, how would I develop a font rendering engine for the iPad (e.g. How do I even access sub-pixels? Do I use OpenGL? Is there an existing open-source font rendering engine written in C, C++, or Objective-C for Mac OS X?)?

A: Each pixel on the iPad is a rectangle of red, green, and blue components, so one might think that sub-pixel font rendering would be a good choice for the device.
But consider that this device can be easily changed from portrait to landscape modes, and applications are expected to respond to that change.  This would imply that your sub-pixel font mechanism would also have to respond to that change, and you would need two separate sub-pixel descriptions for each font.
Now throw in the fact that developers expect to be able to write universal applications that run on the pad and the phones in a single purchase/download. But look at the different pixel configurations on the various generations of the phones in the image below.  Each of those, recall, would need to describe fonts differently in portrait mode and landscape mode.  Now you have an explosion of font descriptions.
Now recall that we're speaking of portable devices where the most precious resource is the battery, and sub-pixel font rendering is more computationally intensive.
I'm guessing that this is not too different from the thought process that led Apple to eschew sub-pixel font rendering in favor of hoping that display technology increases pixel density to the point where it is no longer necessary (the retina display on the iPhone 4 being the first step in that direction.)
I would wager that in some future edition of the iPad, we'll have a display with similar density, and it won't matter as much.  Any effort that you invest trying to invent a sub-pixel font rendering mechanism for your iPad application will immediately become obviated at that point, so I would recommend not going down that path.


text:
Q: Remove From Cart operation not rendering anything I got an issue with my Ajax.  When I clicked on the Remove From Cart, The ajax seems not rendering anything.  Any hint?  Here is my code:
Index.cshtml
  @model Tp1WebStore3.ViewModels.ShoppingCartViewModel

  @{
     ViewBag.Title = "Shopping Cart";
  }

     Details du panier:

      @Html.ActionLink("Checkout >>", "AddressAndPayment", "Checkout")

          Produit

          Prix (unitaire)

          Quantite

     @foreach (var item in Model.CartItems)
     {

              @Html.ActionLink(item.Produit.Description,"Details", "Panier", new { id =
                    item.ProduitId }, null)

               @item.Produit.Prix

               @item.Quantite

               Remove From Cart

     }

           Total

           @Model.CartTotal

PanierController.cs
    // AJAX: /ShoppingCart/RemoveFromCart/5
    [HttpPost]
    public ActionResult RemoveFromCart(int id)
    {
        // Remove the item from the cart
        var cart = ShoppingCart.GetCart(this.HttpContext);

        // Get the name of the album to display confirmation
        string produitDescription = dbProduit.Paniers
            .Single(item => item.PanierId == id).Produit.Description;

        // Remove from cart
        int itemCount = cart.RemoveFromCart(id);

        // Display the confirmation message
        var results = new ShoppingCartRemoveViewModel
        {
            Message = Server.HtmlEncode(produitDescription) +
                " has been removed from your shopping cart.",
            CartTotal = cart.GetTotal(),
            CartCount = cart.GetCount(),
            ItemCount = itemCount,
            DeleteId = id
        };
        return Json(results);

ShoppingCart.cs
    public int RemoveFromCart(int id)
    {
        // Get the cart
        var cartItem = db.Paniers.Single(
            cart => cart.CartId == ShoppingCartId
            && cart.ProduitId == id);

        int itemCount = 0;

        if (cartItem != null)
        {
            if (cartItem.Quantite > 1)
            {
                cartItem.Quantite--;
                itemCount = cartItem.Quantite;
            }
            else
            {
                db.Paniers.Remove(cartItem);
            }
            // Save changes
            db.SaveChanges();
        }
        return itemCount;

Here is the Chrome output PF12 for the network tab

A: Change:
 $.ajax({
             url: '/Panier/RemoveFromCart',
             data: { id: $(this).data('id') },
             cache: false,
             success: function (result) {
                 $('#row-' + result.DeleteId).fadeOut('slow');
                 $('#cart-status').text('Cart (' + result.CartCount + ')');
                 $('#update-message').text(result.Message);
                 $('#cart-total').text(result.CartTotal);
             }

To:
 $.ajax({
             url: '/Panier/RemoveFromCart',
             data: { id: $(this).data('id') },
             type: 'POST',
             cache: false,
             success: function (result) {
                 $('#row-' + result.DeleteId).fadeOut('slow');
                 $('#cart-status').text('Cart (' + result.CartCount + ')');
                 $('#update-message').text(result.Message);
                 $('#cart-total').text(result.CartTotal);
             }

Another option, although not recommended is to remove the [HttpPost] from the top of your controller.  This will raise other issues for you, as the recommended way to send data using ajax is 'POST'


text:
Q: The minimum value of $P(A \cup B )$, if $P(\bar B)={ \{P(A \cup B)}\}^2$ What I tried: $$1-P(B)=\{P(A)+P(B)-P(A \cap B)\}^2$$
Now since $0\le P(B) \le1 \\
$:
$\therefore 1-P(B) \in\  [0,1]\\$
Also, the R.H.S is also the square value of a probability hence it is also in $[0,1]$.
Next, I decided to check the options given if any of them has the range $[0,1]$ and apparently there were two of them.
Looking at the options I got an intuition that the answer probably is the root of a quadratic equation but I am unable to form that quadratic equation.
(I will attach the image for reference)
I also tried using Venn diagram and had an idea that $1=\text{Probability of the sample space}$ and then I could write some expression for $P(\bar{B})$ by equating it with $P(A)-P(A\cap B)\  \mathbf{\text{along with something more}}$ that something more is what I am unable to find out. If I get that then I think I can let some terms as $x$ and form and equation.
I also made an approach using conditional probability but that didn't give any progress.
OR Maybe I am wrong all along.
This is the Question:
I know B can't be the answer A and C hint at it being a quadratic function but if I don't get an absolute value then, option D could also be correct.

A: For notational simplicity, let
\begin{align*}
x&\equiv\mathbb P(A\setminus B),\\
y&\equiv\mathbb P(B).
\end{align*}
Then, we have
\begin{align*}
\mathbb P(A\cup B)=x+y,
\end{align*}
and the constraint $\mathbb P(\overline B)=[\mathbb P(A\cup B)]^2$ can be written as $1-y=(x+y)^2$ (drawing a Venn diagram may help).
Therefore, the problem can be restated as follows:
\begin{align*}
\text{minimize }x+y&\mathrel{\phantom=}\text{such that}\\
1-y&=(x+y)^2,\\
x&\geq0,\\
y&\geq0,\\
x+y&\leq 1.
\end{align*}
The condition $1-y=(x+y)^2$ is a quadratic equation. Solving for $x$ yields two roots (as a function of $y$), one of which is negative for any possible value of $y\in[0,1]$, and hence inadmissible. The only candidate for a non-negative root is $$x=\sqrt{1-y}-y.$$ Plugging this back into the minimization problem above yields the following simplified problem:
\begin{align*}
\text{minimize }\sqrt{1-y}&\mathrel{\phantom=}\text{such that}\\
\sqrt{1-y}&\geq y,\\
y&\geq0,\\
\sqrt{1-y}&\leq 1.
\end{align*}
If the first constraint were slack, that is, $\sqrt{1-y}>y$, then you could slightly increase $y$ and further decrease the value of the objective function $\sqrt{1-y}$. Therefore, the minimizing solution $y^*$ must solve $\sqrt{1-y^*}=y^*$, and the only number that satisfies this is $$y^*=\frac{\sqrt{5}-1}{2}.$$ This is also the minimum value we sought, since
\begin{align*}
\mathbb P(A\cup B)=x^*+y^*=\left(\sqrt{1-y^*}-y^*\right)+y^*=\sqrt{1-y^*}=y^*=\frac{\sqrt{5}-1}{2}.
\end{align*}

A: As P(AUB) is minimum so we will take intersection is maximum
so first case P(B) is greater then P(A) then u will get a quadratic equation and by solving it u will get option a ,
and coming to the second case P(A) greater than P(B)
, which is not possible as ,
By the given hint u get P(A) is greater than P(B) which is a controversy so option a is answer


text:
Q: Lucene QueryParser Analyzer inconsistency I have a very simple Analyzer that tries to replace forward slashes (/) by spaces. Because QueryParser forces me to escape strings with slashes before parsing, I added a MappingCharFilter to the analyzer that replaces "\/" with a single space. The analyzer is defined as follows:
@Override
protected TokenStreamComponents createComponents(String field, Reader in) {
    NormalizeCharMap.Builder builder = new NormalizeCharMap.Builder();
    builder.add("\\/", " ");
    Reader mappingFilter = new MappingCharFilter(builder.build(), in);

    Tokenizer tokenizer = new WhitespaceTokenizer(version, mappingFilter);
    return new TokenStreamComponents(tokenizer);
}

Then I use this analyzer in the QueryParser to parse a string with dashes:
String text = QueryParser.escape("one/two");
QueryParser parser = new QueryParser(Version.LUCENE_48, "f", new MyAnalyzer(Version.LUCENE_48));
System.err.println(parser.parse(text));

The expected output would be
f:one f:two

However, I get:
f:one/two

The puzzling thing is that when I debug the analyzer, it tokenizes the input string correctly, returning two tokens instead of one.
What is going on?
Thanks.

A: A very simple fix. Don't escape the front slash character in the first argument of the builder.add method.
builder.add("/", " ");


text:
Q: Deploy .Net Website from three different branches I am not sure if I should ask this here or on ServerFault but I am trying to put together a way of making production patches easier when we find a problem.
We have several websites in one git depo, right now what we do is use a TeamCity server to build the .nupkg for each website, then we push it to octopus that handles the publishing to the dev, UAT and production servers.
I have been trying to make TeamCity build from a different branch and push the built package to octopus but that means the we'll need 3 projects per website for each TeamCity and Octopus to handle this kind of architecture.
I would like to know if there is a better way to handle what I want to achieve.
UPDATE: Maybe this needs a little more explanation. We have one repo, for all the websites. As bad as this is this is, this is how it is right now and we can't really change it now. But I wanted some insights from people using .Net and a Dev/UAT/master branching strategy for their deployments.

A: There is always a better way but what you are asking takes some work. Here is how I am handling a similar scenario. In my case I have a single application all under a single Git repository, but I want the application deployed to a different web site based on the Git branch. So here is how I've set this up:
Prerequisites:
PowerShell
PSake - A PowerHhell build framework for .NET applications

*

*I have a Psake build file that resides in each branch, it can be run locally from the command line, but it's also used by TeamCity to run the build. That build file takes a name of a branch as a parameter, builds and packages the solution by using the name of the branch to create the package ID for the NuGet package. For example, if my branch is called "feat-API", i strip the "feat-" and my NuGet package ID becomes "api.myapp.com" and when the NuGet package gets built, it becomes "api.myapp.com-2017.05.26.nupkg"

*Once the package is built, it's pushed to the NuGet feed on the OctopusDeploy server but without actually triggering a release.

*The next step is the PSake build script calls the Octopus API and triggers a new release, passing the ID of the package as a parameter.

*On the Octopus Deploy end, I have a single project, with a custom step template that takes a parameter...you should have guessed it by now, the package ID.

*To actually make this generic enough to work, your package needs to contain the actual deployment. I am using Chocolatey (an enhanced version of NuGet of sources) and since NuGet/Chocolatey are just PowerShell based, the install script inside the package handles the actual deployment. It takes as parameters the Octopus Environment in which it's running, constructs the values it needs to do the deployment from a config file and an environment specific file, and deploys the web site, etc.

As you can see, it's doable, but not simple.


text:
Q: conda-forge recipe for python package with a fortran extension not working on appveyor I am trying to get a conda-build recipe to pass all the CI tests on conda-forge/staged-recipes. Here is a link to the pull request The python package has a fortran extension and uses numpy.distutils in the setup.py to build the extension. Circle CI for Linux, Travis-CI for OSX pass, but I cannot get Appveyor for Windows to work with the conda-build recipe.
When using Miniconda for the Appveyor build for Windows and Travis CI build for OSX and Linux for the package repo everything works and the tests pass. I can also get the conda-build recipe to work locally on Windows and Linux, but as you can see from the pull request to conda-forge the tests do not pass for Windows using Appveyor.
The import test fails to load the fortran extension with ImportError: DLL load failed: The specified module cannot be found. The extension module is copied to the site-packages directory, copying build\lib.win-amd64-3.6\timml\besselaesnew.cp36-win_amd64.pyd C:\bld\timml_1541596078787\_h_env\Lib\site-packages\timml, so I am stumped why it is not being found. I read about the differences between .pyd and dll, and tried --compiler=mingw32 instead of --compiler=msvc as mentioned here. That still didn't work. I also added zlib to the host and run section, after reading this and that didn't help.
Any tips to get a conda-build recipe for python package with a fortran extension working on Appveyor would be greatly appreciated. The compiler args in the setup.py file for windows is copied below in case that matters.
if os.name == "nt":
    compile_args = ["-static-libgcc", "-Wall", "-shared"]

A: The issue was with the difference between dll and .pyd files and the compiler specification. After looking at the conda-forge-pinning conda_build_config.yaml, the way to choose mingw instead of msvc is:
requirements:
  build:
    - {{ compiler('fortran') }}
    - {{ compiler('m2w64_c') }}  # [win]
    - {{ compiler('m2w64_fortran') }}  # [win]


text:
Q: Pagefault when using recvfrom() in VxWorks I have a weird problem with the posix socket api in vxworks 5.5.1. The code is trivial and probably not interesting (added below), but the gist of it is: When calling socket() and bind() in a separate function from the one calling recvfrom(), a pagefault occurs at the recvfrom() call. If everything is done in the same function it works fine. Note that the fault happens immediately when calling recvfrom(), not when a packet arrives.
Does VxWorks use the stack in some unexpected way for this API?
Edit: Added some code. The te_serve1() function works fine, but te_serve_one() (using helper functions) do not.
#include <taskLib.h>
#include <sysLib.h>
#include <string.h>
#include <taskLib.h>
#include <stdlib.h>
#include <stdio.h>
#include <types.h>
#include <sys/socket.h>
#include <sockLib.h>
#include <netinet/in.h>

#ifdef DEBUG
#define DP(...) printf(__VA_ARGS__)
#else
#define DP(...) do { } while(0)
#endif

#define LLB(l, b) ((l & (0x000000FF << (b*8))) >> b*8)

struct msg_log {
  unsigned long src;
  int           size;
};

static int setup(short port)
{
  int err = 0;
  struct sockaddr_in addr;
  int sock;

  DP("socket()\n");
  err = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (err < 0)
    return err;
  sock = err;

  addr.sin_family = AF_INET;
  addr.sin_port   = htons(7357);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);

  DP("bind()\n");
  err = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
  if (err) {
    close(sock);
    return err;
  }

  return sock;
}

static int serve(int sock, struct msg_log *log)
{
  char buf[32];
  struct sockaddr_in caddr;
  int caddr_len = sizeof(caddr);
  int ret;
  int len;

  bzero((char *)&caddr, sizeof(caddr));
  DP("recvfrom()\n");
  ret = recvfrom(sock, buf, sizeof(buf), 0,
         (struct sockaddr *) &caddr, &caddr_len);
  if (ret < 0) return ret;
  len = ret;
  if (log) {
    DP("log()");
    log->src = caddr.sin_addr.s_addr;
    log->size = len;
  }
  DP("sendto()");
  ret = sendto(sock, (caddr_t) &buf, len, 0, (struct sockaddr *) &caddr, caddr_len);

  return ret;
}

static void serve_multiple(int sock)
{
  for (;;)
    if (serve(sock, NULL) < 0) break;
}

int te_serve_one(void)
{
  DP("%s\n", __FUNCTION__);
  int sock;
  struct msg_log log;  /* = {0}; */
  int ret = 0;
  short port = 1234;

  DP("setup()\n");
  sock = setup(port);
  if (sock < 0)
    goto out;
  sock = ret;
  ret = serve(sock, &log);
  if(ret < 0)
    goto tidy;

  DP("report:\n");
  printf("Echo'd %d byte to %lu.%lu.%lu.%lu\n",
     log.size,
     LLB(log.src, 0),
     LLB(log.src, 1),
     LLB(log.src, 2),
     LLB(log.src, 3));

 tidy:
  DP("close()");
  close(sock);
 out:
  return ret;
}

int te_serve1(short port)
{
  int ret = 0;
  int sock;
  struct sockaddr_in addr;
  char buf[32];
  struct sockaddr_in caddr;
  int caddr_len = sizeof(caddr);
  int len;

  DP("socket()\n");
  ret = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
  if (ret < 0)
    goto out;
  sock = ret;

  /* host addr */
  addr.sin_family = AF_INET;
  addr.sin_port   = htons(port);
  addr.sin_addr.s_addr = htonl(INADDR_ANY);

  DP("bind()\n");
  ret = bind(sock, (struct sockaddr *)&addr, sizeof(addr));
  if (ret)
    goto tidy;

  /* serve */
  for (;;) {
    DP("recvfrom()\n");
    ret = recvfrom(sock, buf, sizeof(buf), 0,
           (struct sockaddr *) &caddr, &caddr_len);
    if (ret < 0)
      break;
    len = ret;

    if (len >= 4 && !strncmp(buf, "kill", 4)) {
      ret = 0;
      break;
    }

    DP("sendto()\n");
    ret = sendto(sock, (caddr_t) &buf, len, 0,
         (struct sockaddr *) &caddr, caddr_len);

    printf("Echo'd %d byte to %lu.%lu.%lu.%lu\n",
       len,
       LLB(caddr.sin_addr.s_addr, 0), LLB(caddr.sin_addr.s_addr, 1),
       LLB(caddr.sin_addr.s_addr, 2), LLB(caddr.sin_addr.s_addr, 3));
  }
 tidy:
  DP("close()");
  close(sock);
 out:
  return ret;
}

A: settup() declares following local:
struct sockaddr_in addr;
What happens if you declare "struct sockaddr_in addr;" in te_serve_one() and pass it to setup()?

A: Looking at the optimized assembly, I realized that the sock variable got overwritten by ret, which at that point is unused and initialized to zero. Splendid.


text: Q: "Unable to locate application file [program name].msi "Error after reboot Is there any way that we can avoid getting this error? Some people say that it's because the msi file gets cleared after reboot, which is why setup.exe can't find that msi file from %TEMP% folder. So, what can I do to make sure that msi file will still be there after system reboot? Any suggestions? Thanks.


text:
Q: Making field unique in Django Admin I have a model
class ScrapEventInstructionMap(models.Model):
    instruction = models.ForeignKey(Instruction)
    scrap_code = models.CharField(max_length=100, null=True, blank=True)
    event_code = models.CharField(max_length=100, null=True, blank=True)

    class Meta:
        unique_together = (("instruction", "event_code"), ("instruction", "scrap_code"))

I have used unique_together so that for a particular instruction, scrap_code and event_code should be unique.
And from frontend if we're clicking on a particular scrap_code and event_code the instruction page is opening.
I am using InlineModelAdmin in Admin.py so that for one instruction there can be multiple scrap_code or event_code
But issue is like we have two instructions, Instruction 1 and Instruction 2
So if I am entering same scrap_code or event_code in both instructions. It is saving.
I have to restrict it in admin page that event_code and scrap_code should also be unique for different instructions.

A: Try this
class ScrapEventInstructionMap(models.Model):
    instruction = models.ForeignKey(Instruction)
    scrap_code = models.CharField(max_length=100, null=True, blank=True)
    event_code = models.CharField(max_length=100, null=True, blank=True)

    class Meta:
        unique_together = (("event_code", "scrap_code"))

A: You should add custom validation in BaseInlineFormSet of InlineAdmin. Here is example of BaseInlineFormSet validation.


text:
Q: Inspect a Ramdrive? I have mounted a ramdrive via /etc/fstab.
And I would like to inspect the properties of the drive such as the memory policy (e.g. bind, prefer, or?) to make sure all properties are expected.
How can I do so?
Thanks!

A: Executing mount without any arguments gives a list of mounted filesystems, including tmpfs, and their properties:
tmpfs on /mountpoint type tmpfs (rw,relatime)


text:
Q: How to export image and contents to wordfile using jquery / Javascript I am able to export text and image to pdf using client side + server side logic.
For pdf client side
$http.get( url, {cache: false} )
            .success( function( data )
            {
                if(success){
                    window.location.href = 'service path';

                }
            })

I am able to generate pdf .
But no idea how to export image and content into word file .I have googled but didnt get any answer .I am converting images into binary format.
Is it possible to do in client side .Please suggest


text:
Q: Unknown Firebase Service Crash in Android I had made little to no changes in my code but today, as soon as I ran my app on my device, it gave an exception, and did not fetch my data from my Firebase database. I looked up the error on StackOverflow and Github, these are the links I have visited
https://github.com/libgdx/gdx-pay/issues/114
FirebaseRemoteConfig Error "No value of type 'String' exists for parameter key"
Firebase Remote Config Fetch failed with user not authorized
Log
W/ConnectionTracker: Exception thrown while unbinding
    java.lang.IllegalArgumentException: Service not registered: tin@934894f

W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_feature_enabled'.
W/FirebaseRemoteConfig: No value of type 'String' exists for parameter key 'sessions_max_length_minutes'.

E/FirebaseInstanceId: binding to the service failed

Dependencies
implementation 'com.google.firebase:firebase-analytics:17.4.2'
implementation 'com.google.firebase:firebase-firestore:21.4.3'
implementation 'com.google.firebase:firebase-auth:19.3.1'

Comment if you want more data from the Logcat or if you want to see any of my code.
Thank you!


text:
Q: Symfony: execute() return array? <?php
  $result = $query->execute()
  gettype($result); //output: object
?>

Why is this? While $result functions as an array (may be referenced so $result[i]), it is actually an object? I actually need to have an array to use array functions on it (e.g. array_slice()). Help?
Thanks.

A: execute(); return object Doctrine_Collection which implements SPL interfaces, such as ArrayAccess, Countable, Iterator so you can do basic array manipulations with it (such as $result[$i]).
if you really need array, then you need to use $query->fetchArray(); instead

A: symfony itself doesn't do ORM, but i assume you are using doctrine (which is the default for symfony) - the execute() method returns a Doctrine_Collection. Maybe you want to take a look at the API documentation: http://www.doctrine-project.org/api/orm/1.2/doctrine/doctrine_query_abstract.html#execute()
usually there is no need to use any array methods on it.. if you only need a subset of the results, don't query for all your data. what exactly do you need?


text:
Q: Why does this automatic-storage structure still exist? Code
stack.h:
struct customer
{
    char fullname[35];
    double payment;
};

typedef customer Item;

class Stack
{
private:
    ...
    Item items[MAX];
public:
    ...
    bool push(const Item & item);
    bool pop(Item & item);
};

main.cpp:
#include "stack.h"

...

int main()
{
    Stack s; double total;
    while (1)
    {
        ...
        cin >> c;
        switch (c)
        {
        case '1': push(s);
            break;
        case '2': pop(s, total);
            break;
        ...
        }
    }
    ...
}

void push(Stack & s)
{
    Item newitem;
    cout << "name -- ";    cin >> newitem.fullname;
    cout << "payment -- "; cin >> newitem.payment;
    s.push(newitem);
}

void pop(Stack & s, double & total)
{
    Item olditem;
    s.pop(olditem);
    total += olditem.payment;
}

Remark
Most of main() is probably irrelevant, but I just want to show what I'm doing. push() and pop() are the important blocks.
The code above is supposed to fill a stack with Items. When an Item is popped, its payment is added to a running total.
Also, differentiate between Stack methods pop() and push() with the functions in main().

Dilemma
The code works exactly as I want it to, but I don't understand why...
I create a local Item in the push() function. It is referenced and placed onto the Stack. However, when the push() function ends, shouldn't this local Item be removed since it is on automatic storage? Yet, somehow it still exists because when I call pop(), there it is.

A: The expression items[top] = item uses the copy assignment operator to copy the structure.


text:
Q: BackgroundWorker and Threads What are the pros and cons in using the either for achieving a given task.
The million dollar question is which one to use and when?
Many Thanks.

A: Have a look at this great threading overview:

[The BackgroundWorker] provides the following features:

*

*A "cancel" flag for signaling a worker to end without using Abort

*A standard protocol for reporting progress, completion and cancellation

*An implementation of IComponent allowing it be sited in the Visual Studio Designer
  Exception handling on the worker thread

*The ability to update Windows Forms and WPF controls in response to worker progress or completion.
The last two features are particularly useful – it means you don't have to include a try/catch block in your worker method, and can update Windows Forms and WPF controls without needing to call Control.Invoke.

A: Threads only when you don't have to work with a UI (WinForms or WPF) and background workers when you do have to deal with a UI.
You avoid a lot of problems with UIs and background workers.

A: I use to associate BackgroundWorker as a wrapper for what Threads would do. So I use BackgroundWorker on GUI works, and Threads on more specialized or dirty jobs (Windows Services, etc)

A: If by "Threads"  you mean explicitly using the System.Threading.Thread class to create, configure and kick off your own threads, then the answer is that doing this is more work on your part, involves more cpu cycles than just pulling a thread from the thread pool, (wjhich is what the other techniques do), but it gives you more flexibility, as it allows you to specify thread priority, and several other characteristics that using Thread Pool threads does not afford you.
The "Thread Pool" approach is more appropriate when the number of threads required is not known at design time.  The pool initially contains a small number of threads, "ready" for you to call upon them.  It can dynamically create new threads on demand, and it manages creation, coordination, and deletion of unused threads for you. There are three mechanisms you can use to access and use threads from the pool.

*

*Using  Delegate.BeginInvoke()  (the most common technique)

*Using timers (several variations)

*System.Threading.ThreadPool provides several other features (BackGroundWorker class, QueueUserWorkItem(), etc.).

A: The BackgroundWorker class is an easy way to add a thread to a Form to perform some heavy operation without blocking the UI.  You could do the same with a thread but with slightly more coding.

A: The BackgroundWorker class simply provides events that are switched to the context of the UI thread for you, but don't be confused; the DoWork event (which is where you actually, well, do the work) is still executed in the context of another thread (as that's the point of the whole thing) and performing any kind of UI interaction or update there will throw an exception at best, and crash at worst. The BackgroundWorker should be used on forms when you're trying to do something that requires a UI update and whose scope doesn't extend beyond that of the form. For other background operations, consider either using the ThreadPool (for short-lived operations) or creating your own Thread.
The BackgroundWorker provides convenience with the ProgressChanged event, but don't get too comfortable and start doing UI updates in DoWork.


text:
Q: How can I Check if String is in an Array in a specific Firestore document (Swift)? What I want to do: Check if a user is following another user. Basically I want to see if the UID of the user is in the "follower" array in the document of the other user-profile.

I thought of the option to use the .whereField command, but then I would get more documents and not only the one that I care of.

A: Get the user document (using whereField isEqualTo)and check if the followers field array contains the uid of the second user.

A: You can go with array-contains operator:
https://firebase.google.com/docs/firestore/query-data/queries#array_membership
So you can write something like this:
usersRef
    .whereField("followers", arrayContains: "l47GVBdjsabjdjds")


text:
Q: What are the scoping or visibility constraints in Java? I have started programming in Java since 2000, while in C++ since 1987. So, most of the times I could grasp Java concepts fairly easily aptly aided by C++ knowledge. On certain occasions, though, it gives me a "cultural" shock(for a person ingrained with C++ culture). If I have the following program in C++:
// override.cpp
class Base
{
public:
   void f(int) { }
};

class Derived : public Base
{
public:
   void f(char *) { }
};

int main()
{
   Derived d;
   d.f(5); // This line throws a compilation error
}

invoking f(5) through a Derived object d throws an error, as within the scope of Derived class, f() can accept only a character pointer. If I translate this program into Java:
// Override.java
class Base
{
    public void f(int i) { System.out.println("Base.f()"); }
}

class Derived extends Base
{
    public void f(String s) { System.out.println("derived.f()"); }

    public static void main(String [] args)
    {
        Derived d = new Derived();
        d.f(5);
    }
}

The compiler does not throw any error and the program produces the output:
Base.f()

which's obviously misleading. Am I not supposed to get a compilation error for calling a function that's not available within Derived's scope?

A: The overriding method must have same argument list.
If not then functions work as overloaded functions.
In above case your base class function is matched on d.f(5); call.

A: In java, non-private members such as public void f(int i) will be inherited by subclass, which means it will be a method member of subclass, so both

*

*public void f(String s)

*public void f(int i)
is accessible in subclass.

A: In C++ it does not search base class to call a function/method by default. You need to explicitly specify for the same by the keyword using like using Base::f; in your case. But in case of Java, it does by default.The using statement brings the overload function into the same scope so that it can participate in overload resolution. Below C++ code works fine for me. So the difference is only in default behavior.
class Base
{
public:
   void f(int) { }
};

class Derived : public Base
{
public:
using Base::f; // this line allow you to use function from base class
   void f(char *) { }
};

int main()
{
   Derived d;
   d.f(5); // This line throws a compilation error
}

A: All public functions are available from the class and all of its base classes (all the way up to Object.class). The key here is the declared type of the instance. For example:
Base b = new Derived();
b.f(10); // prints Base.f()
b.f("foo"); // does not compile

Derived d = new Derived();
d.f(10); // prints Base.f()
d.f("foo"); // prints derived.f()

Even though b's runtime type is Derived.class, the declared type is Base.class. You see the same behavior with interfaces:
List list = new ArrayList();

You only get access to methods declared in List and not all of ArrayList.


text:
Q: a:first-child modifying all links within my list I'm having a problem with my links and I can't seem to find why first-child is acting this way.
Instead of modifying the first link inside my unordered list, it modifies them all. The same thing happens when i try using last-child or nth-child.
Could anyone help me figure this out? Thanks
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

    <title></title>

1

2

3

4

5

6

7

8

9

A: Try
#types li:first-child a

insted.

A: a:first-child matches  elements that are the first child of their parent. Your  elements are in completely different
s, so they all are the first children of their parent element.
You should match the
 elements instead:
#types li:first-child a {background-color:#A02723;}


text:
Q: Программно определить вычислительную сложность неизвестного алгоритма JS Есть функция f : неизвестный алгоритм принимающий на вход одномерный массив . Есть коллекция массивов различной длины data каждый из которых передаю в f.
Необходимо написать функцию результатом которой будет строка оценивающая вычислительную сложность алгоритма в f. Функция должна различать O(n), O(n2), O(n3), O(ln(n))
Есть ли пример как программно вычисляется вычислительная сложность алгоритма? Буду благодарен любым ссылкам и материалам, желательно с простейшими примерами.

A: В общем случае невозможно даже определить программно завершается ли другая программа вообще - а уж детали асимптотики определять еще труднее :-)
В качестве примера можно рассмотреть алгоритм быстрого возведения в степень. Будучи применен к кольцу вычетов или к арифметике с плавающей точкой, он дает логарифмическую асимптотику относительно показателя степени, но в длинной арифметике логарифм "теряется" и быстрое возведение в степень выполняется столь же быстро, как простое умножение - за O(N2).
Чтобы замечать такие детали, нужен сильный ИИ, способный формулировать и доказывать теоремы.

A: Задачи, которые сложно решить в общем случае, могут иметь простые решения, которые хорошо на практике работают во многих случаях. К примеру, Симплекс-метод имеет экспоненциальную сходимость в худшем случае, но во многих практических задачах, его время исполнения гораздо лучше (полиномиальная сходимость в среднем).
Если это допустимо в вашем случае, то вы можете померить фактические времена исполнения для доступных данных и оценить какая из моделей O(n), O(n2), O(n3) или O(log(n)) лучше описывает результаты.
К примеру, не сложно программно убедиться, какие из рассматриваемых алгоритмов являются O(1) (для используемых данных):

Точки это измерения, а линии это соответствующие апроксимирующие полиномы.
Апроксимирующий полином вычисляется с помощью numpy.polyfit() в make-figures.py.
Вот таблица соответствия между log2(N) полиномами на графике и соответствующими функциями роста:
|------------------------------+-------------------|
| Fitting polynom              | Function          |
|------------------------------+-------------------|
| 1.00  log2(N)   +  1.25e-015 | N                 |
| 2.00  log2(N)   +  5.31e-018 | N*N               |
| 1.19  log2(N)   +      1.116 | N*log2(N)         |
| 1.37  log2(N)   +      2.232 | N*log2(N)*log2(N) |

К примеру, измерения показывают, что слияние двух отсортированных списков это O(n) операция, если используется heapq.merge() в Питоне (которая медленнее встроенного sort(), который O(n * log n) в общем случае, но так как на входе два отсортированных массива, то timsort, используемый в Питоне лучше показывает результаты):

Конечно, измерения не всегда позволяют определить функцию роста:

См. пример кода как выполнить измерения, найти полиномы и построить графики в cdleary.py и make-figures.py

A: Грубо - если данные достаточно разных размеров - отличающиеся на порядки - можно пытаться построить зависимость времени работы от размера и посмотреть, для какого из вариантов корреляция будет выше.
Но обычно вмешивается столько других факторов, что сказать абсолютно точно абсолютно уверенно практически нереально. Например, при T=N + 0.00000001*N^2 при том, что алгоритм - O(N2), эксперимент при реальных N даст O(N)...

A: Для асимптотик вида O(n^k) увеличение n вдвое ведёт к увеличению времени выполнения в 2^n раз, что довольно заметно. Так, при линейной асимптотике время будет удваиваться, при квадратичной - учетверяться, а при кубической - увеличиваться в 8 раз.
Соответственно, надо на достаточно больших n (чтобы время выполнения было ощутимым) некоторое достаточное для усреднения число раз выполнить функцию и посчитать среднее время работы. Очевидно, что при одинаковом числе повторений можено сравнивать не среднее значение, а сумму времён выполнения.
Примеры:

*

*function go(n) { while (Math.random() * n | 0); } - линейная O(n) (заметно по суммарной длительности 10К вызовов при n > 2^7):

*Сложение строк в javascript - линейная без зависимости от длины строк O(n) (заметно при n > 2^7, а где-то при n > 2^17 алгоритм меняется - такие уж они оптимизации):

*Сложение строк в C# - квадратичная относительно числа сложений и линейная относительно длины строк O(n*n*len):
       len          !         !2       !234   !2345678
-------------------------------------------------------
 0       1      0.000      0.000      0.000      0.000
 1       2      0.000      0.000      0.000      0.000
 2       4      0.000      0.000      0.000      0.000
 3       8      0.001      0.001      0.001      0.001
 4      16      0.002      0.001      0.001      0.002
 5      32      0.002      0.004      0.004      0.004
 6      64      0.005      0.006      0.009      0.014
 7     128      0.013      0.019      0.028      0.043
 8     256      0.042      0.057      0.087      0.148
 9     512      0.118      0.174      0.302      0.559
10    1024      0.354      0.606      1.124      2.279
11    2048      1.220      2.242      4.545     10.041
12    4096      4.517      8.982     19.706     41.568
13    8192     17.864     39.063     82.814    169.274
14   16384     78.454    165.893    337.830    718.843


text:
Q: Package conflicts creating an Anaconda environment with Keras and Tensorflow I am trying to create a new environment in Anaconda with these packages that I have installed locally:
Python: 3.8.8 (default, Apr 13 2021, 15:08:03) [MSC v.1916 64 bit (AMD64)]
Pandas: 1.4.2
Numpy: 1.23.5
sklearn: 1.0.2
dateutil: 2.8.2
keras: 2.10.0
argparse: 1.1
sqlalchemy: 1.4.22
statsmodels: 0.13.5
tensorflow: 2.10.1

I run without problems my script with those package versions.
If I run this code in Anaconda prompt:
conda create -n myenv python=3.8.8 pandas=1.4.2 scikit-learn=1.0.2 numpy=1.23.5 dateutil=2.8.2 keras=2.10.0 argparse=1.1 mysql sqlalchemy=1.4.22 statsmodels=0.13.5 tensorflow=2.10.1

I get this error:
*PackagesNotFoundError: The following packages are not available from current channels:

*

*tensorflow=2.10.1

*dateutil=2.8.2

*argparse=1.1*

So I run this:
conda create -n myenv python=3.8.8 pandas=1.4.2 scikit-learn=1.0.2 numpy=1.23.5 dateutil keras=2.10.0 argparse mysql sqlalchemy=1.4.22 statsmodels=0.13.5 tensorflow

But I get this error:
Found conflicts! Looking for incompatible packages.
And if I try this:
conda create -n myenv python pandas scikit-learn numpy dateutil keras argparse mysql sqlalchemy statsmodels tensorflow

Same error:
Found conflicts! Looking for incompatible packages.
What I'm doing wrong?

A: First install python and tensorflow, then you can let anaconda figure out which version of the other requirements it should install
Sklearn and pandas will take care of installing numpy, if not already installed by tensorflow
BTW, if you did not find the tensorflow version it's probably because you did not add -c conda-forge
to sum up:
conda create -n myenv python=3.8.8 tensorflow=2.10.1 -c conda-forge
conda install -n myenv scikit-learn pandas dateutils statsmodels ...

A: I finally fixed it without installing the dateutil and argparse packages, because they are already included in the latest versions of Python.
That code worked:
conda create -n myenv python tensorflow keras pandas scikit-learn numpy mysql sqlalchemy statsmodels


text:
Q: Unable to send more than 5 emails to Exchange server using JavaMail I have a method that sends many emails to exchange server over smtp using JavaMail, below is my code,
public void sendMail(){
        final String host="host",port="587",username="mail1@local.local",password="password",from="";
        try {

            Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.port", port);
            props.put("mail.smtp.ssl.trust", host);

            final String email = from;

            Authenticator authenticator = new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                 return new PasswordAuthentication(username, password);
                }
            };

            Session session = Session.getInstance(props,authenticator);
            InternetAddress replyToAddress [] = new InternetAddress[1];
            replyToAddress[0] = new InternetAddress("mail1@local.local");
            Transport transport = session.getTransport("smtp");
            MimeMessage mimeMessage = new MimeMessage(session);
            mimeMessage.setFrom(new InternetAddress("mail1@local.local"));
            mimeMessage.addRecipient(Message.RecipientType.TO, new InternetAddress("mail2@local.local"));
            mimeMessage.setSubject("Test");
            mimeMessage.setText("Hello Testing");

            mimeMessage.setReplyTo(replyToAddress);
            transport.send(mimeMessage);
            System.out.println("Email has been Sent Successfully to");
       } catch (MessagingException e) {
            e.printStackTrace();
        }

Now when I apply a loop and call this function 10 times then only first five emails are sent successfully, for rest of the request I get the following exception,
javax.mail.MessagingException: Can't send command to SMTP host;
  nested exception is:
    java.net.SocketException: Connection closed by remote host
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2157)
    at com.sun.mail.smtp.SMTPTransport.sendCommand(SMTPTransport.java:2144)
    at com.sun.mail.smtp.SMTPTransport.close(SMTPTransport.java:1210)
    at javax.mail.Transport.send0(Transport.java:197)
    at javax.mail.Transport.send(Transport.java:124)

if I increase the request count then still only first five emails are sent, rest of them throws the exception.
If I put the failed request in some queue and retry them later then some of them will be sent.
Any clue will be appreciated, do I need to check for some configuration on Exchange server?

A: We have seen this exact same issue with a  MS Exchange Server 2010. We had to increase the  ReceiveConnector message rate limit by issuing the following Powershell-command:
Set-ReceiveConnector "Client CLIENTNAME" -MessageRateLimit unlimited


text:
Q: Capturing a copy of parameter pack My class has a member of a type optional<A>. I'm trying to implement function emplaceWhenReady which gets list of parameters to A's constructor, but the non-trivial part is that A can be only initialized after a certain event. When emplaceWhenReady is invoked before the event, I need to somehow capture the initialization values.
For single constructor parameter the code can be written as:
struct B {
   bool _ready;
   std::optional<A> _a;
   std::function<void()> _fInit;

   template<typename ARG>
   void emplaceWhenReady1(ARG&& arg) {
      if (_ready) {
         _a.emplace(std::forward<ARG>(arg));
      } else {
         _fInit = [this, argCopy = std::forward<ARG>(arg)]() {
            _a.emplace(std::move(argCopy));
      };
    }
};

and _fInit() can be now invoked when the class becomes _ready. But I fail to write similar code for multiple parameters:
// Fails to compile
template<typename... ARGS>
void emplaceWhenReady(ARGS&&... args) {
    if (_ready) {
        _a.emplace(std::forward<ARGS>(args)...);
    } else {
        _fInit = [this, argsCopy = std::forward<ARGS>(args)...]() {
            _a.emplace(std::move(argsCopy)...);
        };
    }
}

Godbolt: https://godbolt.org/z/Fi3o1S
error: expected ',' or ']' in lambda capture list
       _fInit = [this, argsCopy = std::forward<ARGS>(args)...]() {
                                                          ^

Any help is appreciated!

A: If we look at proposal p0780: Allow pack expansion in lambda init-capture it covers this problem and possible solutions:

With the introduction of generalized lambda capture [1], lambda
  captures can be nearly arbitrarily complex and solve nearly all
  problems. However, there is still an awkward hole in the capabilities
  of lambda capture when it comes to parameter packs: you can only
  capture packs by copy, by reference, or by... std::tuple?
Consider the simple example of trying to wrap a function and its
  arguments into a callable to be accessed later. If we copy everything,
  the implementation is both easy to write and read:
template<class F, class... Args>
auto delay_invoke(F f, Args... args) {
    // the capture here can also be just [=]
    return [f, args...]() -> decltype(auto) {
        return std::invoke(f, args...);
    };
}

But if we try to be more efficient about the implementation and try to
  move all the arguments into the lambda? It seems like you should be
  able to use an init-capture and write:
template<class F, class... Args>
auto delay_invoke(F f, Args... args) {
    return [f=std::move(f), ...args=std::move(args)]() -> decltype(auto) {
        return std::invoke(f, args...);
    };
}

But this runs afoul of very explicit wording from
  [expr.prim.lambda.capture]/17, emphasis mine:

A simple-capture followed by an ellipsis is a pack expansion. An init-capture followed by an ellipsis is ill-formed.

It discusses various solutions including using a tuple:

As a result of this restriction, our only option is to put all the
  args... into a std::tuple. But once we do that, we don't have access
  to the arguments as a parameter pack, so we need to pull them back out
  of the tuple in the body, using something like std::apply():
template<class F, class... Args>
auto delay_invoke(F f, Args... args) {
    return [f=std::move(f), tup=std::make_tuple(std::move(args)...)]() -> decltype(auto) {
        return std::apply(f, tup);
    };
}

Which gets even worse if what we wanted to do with that captured
  parameter pack was invoke a named function rather than a captured
  object. At that point, all semblance of comprehension goes out the
  window:

This proposal was merged in the draft standard in March, so we should get this change in C++2a.

A: With some help (see answer and comments above) the solution I was able to find is:
    template<typename... ARGS>
    void emplaceWhenReady(ARGS&&... args) {
      if (_ready) {
        _a.emplace(std::forward<ARGS>(args)...);
      } else {
        _fInit = [this, argsCopy = std::make_tuple(std::forward<ARGS>(args)...)]() {
            auto doEmplace = [&](auto&... params) {
                _a.emplace(std::move(params)...);
            };
            std::apply(doEmplace, argsCopy);
        };
      }
    }


text:
Q: Inserting values into tables I have created some values and I want to insert them into the database but I find that some data are inserted and others are not, I don't know why
Here is my code
SqlConnection con = new SqlConnection();
con.ConnectionString = "Persist Security Info=False;Integrated Security=SSPI;database=DB1;server=KHALED-PC;Connect Timeout=30";

char[] delimiterChars = { ' ', ',', '.', ':', '\t', '<', ':', '$', '=', ';', ' ', '<', '>', '!', ';', ']', '[', '"',
  '/','=','-','!','#','$','%','^','&','*','/'
};
string[] stopwords ={"a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also","although","always","am","among", "amongst", "amoungst", "amount",  "an", "and", "another", "any","anyhow","anyone","anything","anyway", "anywhere", "are", "around", "as",  "at", "back","be","became", "because","become","becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven","else", "elsewhere", "empty",
  "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few",
  "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found",
  "four", "from", "front", "full", "further", "get", "give", "go", "had", "has",
  "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein",
  "hereupon", "hers", "herself", "him", "himself", "his", "how", "however",
  "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it",
  "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd",
  "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more",
  "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name",
  "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody",
  "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off",
  "often", "on", "once", "one", "only", "onto", "or", "other", "others",
  "otherwise", "our", "ours", "ourselves", "out", "over", "own","part", "per",
  "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed",
  "seeming", "seems", "serious", "several", "she", "should", "show", "side",
  "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone",
  "something", "sometime", "sometimes", "somewhere", "still", "such", "system",
  "take", "ten", "than", "that", "the", "their", "them", "themselves", "then",
  "thence", "there", "thereafter", "thereby", "therefore", "therein",
  "thereupon", "these", "they", "thickv", "thin", "third", "this", "those",
  "though", "three", "through", "throughout", "thru", "thus", "to", "together",
  "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under",
  "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were",
  "what", "whatever", "when", "whence", "whenever", "where", "whereafter",
  "whereas", "whereby", "wherein", "whereupon", "wherever", "whether",
  "which", "while", "whither", "who", "whoever", "whole", "whom", "whose",
  "why", "will", "with", "within", "without", "would", "yet", "you", "your",
  "yours", "yourself", "yourselves", "the"
};

string[] words = txt.Split(delimiterChars);//remove punctuation character

int index = 1;
bool check = true;
foreach (string f in words)
{
  for (int s = 0; s < stopwords.Length; s++)
  {
    if (f == stopwords[s])
    {
      check = false;
      index++;
      break;
    }
  }
  if (f.Trim().Length > 0 && check == true)
  {
    //Console.WriteLine("word : " + e + "(position):" + index);
    con.Open();
    //s.ToLower();
    SqlCommand cmd = new SqlCommand("INSERT INTO TableFF (Position) VALUES (@index)", con);

    cmd.Parameters.Add(new SqlParameter("@index",index));

    //  cmd.CommandType = CommandType.Text;
    cmd.ExecuteNonQuery();
    con.Close();
    index++;
  }
  check = true;
}

string []wordsbeforesoundex = new string[10000000];
for (int j = 0; j < words.Length; j++)
{
  wordsbeforesoundex[j] = words[i];
}

foreach (string word in wordsbeforesoundex)
{
  string results = "";
  con.Open();

  string wordss = word;
  SqlCommand cmd1 = new SqlCommand("INSERT INTO TableFF (SoundexNumbers) VALUES (@wordss)", con);
  cmd1.Parameters.Add(new SqlParameter("@wordss", wordss));

  cmd1.ExecuteNonQuery();
  wordss = null;
  con.Close();
}

The first values in the first foreach loop are inserted successfully but in the second foreach nothing is inserted although I make sure of the parameters and the values I insert

A: This line
string[] wordsaftersoundex="khaled go to school by bus and he is good boy"

don't even compile
If you want to get an array of words try with this
string[] wordsaftersoundex="khaled go to school by bus and he is good boy".Split(' ')

In any case, there is something you missed to tell us since as I told you above, your code don't even compile.