text:
Q: Choosing Balls Randomly
4 balls are put randomly into $3$ cells
  what is the probability that:

  1. there is an empty cell?

  2. there is one cell with precisely $2$ balls

*

*if we know that one cell is empty there are $\frac{2^4}{3^4}$ options that a cell will be empty, there are $3$ cells so it is $3*\frac{2^4}{3^4}=\frac{42}{81}$, but the answer is $\frac{45}{81}$ doesn't my answer include that option that $2$ cells will be empty?

*Why the answer is $$\frac{{3\choose 1}{4\choose 2}*2!+{3 \choose 2}{4\choose 2}}{3^4}$$ ?

A: Question 1. Your approach is generally correct, but just multiplying the answer by three is incorrect, not because you haven't included the possibility that two cells are empty, but because you've counted them twice.  That has been compounded by an arithmetical error ($3 \cdot 2^4 = 3 \cdot 16 = 48$, not $42$).  The correct number of ways to have (at least) one empty cell is
$$
3 \cdot 2^4 - 3 = 48 - 3 = 45
$$
and then the probability of having at least one empty cell is $45/81 = 5/9$.
Revised Question 2. There can be a cell with exactly two balls in two different ways.  One is to have a cell with two balls, and two cells with one ball each.  The number of ways to do this (and the associated probability) are analyzed in "Old Question 2", below.
The other way is to have two balls in each of two cells.  We choose two of the cells ($C(3, 2) = 3$ pairs of cells) and choose two of the balls to go in the "first" of that pair of cells ($C(4, 2) = 6$ pairs of balls), for a total of $3 \cdot 6 = 18$ different ways.  The probability is $18/81 = 2/9$, and if you add those together, you end up with the $2/3$ from the expression you gave.
Old Question 2. The original wording of this question was, "What is the probability that there is exactly one cell with two balls?"
The only way of having exactly one cell with two balls is to have one ball in each of the other two cells.  We choose two of the four balls ($C(4, 2) = 6$ different pairs), to share one of the cells ($3$ different cells), and the other two balls to split the two remaining cells ($2! = 2$ different ways).  The product is $6 \cdot 3 \cdot 2 = 36$ different ways, so the probability is $36/81 = 4/9$.
The expression you gave evaluates to $54/81 = 2/3$.  I don't think that can be right, if I understand the problem correctly (but I might not understand the question correctly).
It makes sense that the answers to Question 1 and Old Question 2 add up to $1$, since they are mutually disjoint (if there is one empty cell, there cannot be exactly one cell with exactly two balls), and cover all cases (one of those properties must be true).

A: For part one:  We ask the question "what is the probability that there is at least one empty cell."
You correctly begin by noting that there are $3^4$ possible ways to distribute the balls.  We have a number of ways of approaching this problem, but the easiest perhaps is via inclusion-exclusion.  We count instead: how many ways can $\underline{no}$ cells be empty?
Since there are four balls and three cells, that means that one cell gets two balls, and the other two cells each get one ball.  Pick which cell gets two balls (3 choices).  Pick which two balls went into the cell with two balls ($\binom{4}{2} = 6$ choices).  Pick which ball went into the leftmost cell with one ball ($2$ remaining choices).  Pick which ball went into the final cell ($1$ choice).  For a total of $3\cdot 6\cdot 2\cdot 1 = 36$ ways of distributing balls to not have an empty cell.  Thus there are $3^4-36=81-36=45$ ways of having at least one empty cell.  The probability is therefore $\frac{45}{81}$.
Your answer of $3\cdot \frac{2^4}{3^4}$ made two mistakes.  First was arithmetically.  $3\cdot 2^4 = 3\cdot 16 = 48$, not $42$.  The second mistake was that you had not properly applied inclusion-exclusion.  You have accidentally double-counted each scenario where 2 of the three cells are empty.  To fix this, you should subtract the number of ways that two cells are empty.  There are three ways this can occur.  Indeed, $48-3 = 45$ which gives the correct probability of $\frac{45}{81}$.
Read more at Inclusion-Exclusion Principle

For part two, I will interpret it as "There is at least one cell with exactly 2 balls."  There are two ways this can happen:

*

*There is one cell with 2 balls, and two cells with 1 ball each

*There are two cells with 2 balls each (and one cell which is empty)

The first case was calculated previously to occur $3\cdot\binom{4}{2}\cdot 2 = 36$ different ways.
To count the number of ways the second case can occur, apply multiplication principle.  Pick which of the cells is empty (equivalently pick which two cells are being used) (there are $\binom{3}{1}=\binom{3}{2}=3$ choices).  Pick which two balls go in the leftmost cell that will have two balls in it ($\binom{4}{2} = 6$ choices).  The remaining balls go in the remaining cell that will have two balls in it.  For a total of $\binom{3}{1}\binom{4}{2} = 18$ different ways to fall into the second case.
By the addition principle (since there is no overlap between these cases), there are a total of $36+18=54$ different ways to have "at least one cell has exactly two balls."  Thus the probability is $\frac{54}{81}$


text:
Q: How do i fix these errors I'm receiving these errors in the magento connect/update panel
 Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000]: General error: 2006 MySQL server has gone away' in /home/cleverop/public_html/lib/Zend/Db/Statement/Pdo.php:228 Stack trace:
#0 /home/cleverop/public_html/lib/Zend/Db/Statement/Pdo.php(228): PDOStatement->execute(Array)
#1 /home/cleverop/public_html/lib/Varien/Db/Statement/Pdo/Mysql.php(110): Zend_Db_Statement_Pdo->_execute(Array)
#2 /home/cleverop/public_html/app/code/core/Zend/Db/Statement.php(291): Varien_Db_Statement_Pdo_Mysql->_execute(Array)
#3 /home/cleverop/public_html/lib/Zend/Db/Adapter/Abstract.php(480): Zend_Db_Statement->execute(Array)
#4 /home/cleverop/public_html/lib/Zend/Db/Adapter/Pdo/Abstract.php(238): Zend_Db_Adapter_Abstract->query('SELECT `mg_core...', Array)
#5 /home/cleverop/public_html/lib/Varien/Db/Adapter/Pdo/Mysql.php(428): Zend_Db_Adapter_Pdo_Abstract->query('SELECT `mg_core...', Array)
#6 /home/cleverop/public_html/lib/Zend/Db/Adapter/Abstract.php(828): Varien_Db_Adapter_Pdo_Mysql->query(Object(Varien_Db_Select), Arr in /home/cleverop/public_html/lib/Zend/Db/Statement/Pdo.php on line 235

I have no idea where they came from.

A: The error occur because of mysql execution time out.
Refer following URL

redpajama_set_name: RedPajamaStackExchange


text:
Q: Prevent automatic exit on unsuccessful ActiveMQ reconnect I have a small spring-boot app set up that connects to one or more Topics on ActiveMQ, which are set in the application's application.properties file on startup - and then sends these messages on to a database.
This is all working fine, but I am having some problems when trying to implement a failover - basically, the app will try to reconnect, but after a certain number of retries, the application process will just automatically exit, preventing the retry (ideally, I would like the app to just retry forever until killed manually or ActiveMQ becomes available again). I have tried explicitly setting the connection options (such as maxReconnectAttempts) in the connection URL (using url.options in application.properties) to -1/0/99999 but none of these seem to be right as the behavior is the same each time. From looking at the advice on Apache's own reference page I would also expect this behavior to be working as default too.
If anyone has any advice to force the app not to quit, I would be very grateful! The bits of my code that I think will matter is below:
@Configuration
public class AmqConfig {

    private static final Logger LOG = LogManager.getLogger(AmqConfig.class);
    private static final String LOG_PREFIX = "[AmqConfig] ";

    private String clientId;

    private static ArrayList<String> amqUrls = new ArrayList<>();
    private static String amqConnectionUrl;
    private static Integer numSubs;
    private static ArrayList<String> destinations = new ArrayList<>();

    @Autowired
    DatabaseService databaseService;

    public AmqConfig (@Value("${amq.urls}") String[] amqUrl,
                      @Value("${amq.options}") String amqOptions,
                      @Value("${tocCodes}") String[] tocCodes,
                      @Value("${amq.numSubscribers}") Integer numSubs,
                      @Value("${clientId}") String clientId) throws UnknownHostException {

        Arrays.asList(amqUrl).forEach(url -> {
            amqUrls.add("tcp://" + url);
        });

        String amqServerAddress = "failover:(" + String.join(",", amqUrls) + ")";
        String options = Strings.isNullOrEmpty(amqOptions) ? "" : "?" + amqOptions;

        this.amqConnectionUrl = amqServerAddress + options;

        this.numSubs = Optional.ofNullable(numSubs).orElse(4);
        this.clientId = Strings.isNullOrEmpty(clientId) ? InetAddress.getLocalHost().getHostName() : clientId;

        String topic = "Consumer." + this.clientId + ".VirtualTopic.Feed";

        if (tocCodes.length > 0){
            Arrays.asList(tocCodes).forEach(s -> destinations.add(topic + "_" + s));
        } else { // no TOC codes = connecting to default feed
            destinations.add(topic);
        }
    }

    @Bean
    public ActiveMQConnectionFactory connectionFactory() throws JMSException {

        LOG.info("{}Connecting to AMQ at {}", LOG_PREFIX, amqConnectionUrl);
        LOG.info("{}Using client id {}", LOG_PREFIX, clientId);
        ActiveMQConnectionFactory connectionFactory =
                new ActiveMQConnectionFactory(amqConnectionUrl);

        Connection conn = connectionFactory.createConnection();
        conn.setClientID(clientId);
        conn.setExceptionListener(new AmqExceptionListener());
        conn.start();

        destinations.forEach(destinationName -> {
            try {
                for (int i = 0; i < numSubs; i++) {
                    Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
                    Destination destination = session.createQueue(destinationName);
                    MessageConsumer messageConsumer = session.createConsumer(destination);
                    messageConsumer.setMessageListener(new MessageReceiver(databaseService, destinationName));
                }

            } catch (JMSException e) {
                LOG.error("{}Error setting up queue @ {}", LOG_PREFIX, destinationName);
                LOG.error(e.getMessage());
            }
        });

        return connectionFactory;
    }
}

public class MessageReceiver implements MessageListener, ExceptionListener {

     public static final Logger LOG = LogManager.getLogger(MessageReceiver.class);
     private static final String LOG_PREFIX = "[Message Receiver] ";

     private DatabaseService databaseService;

     public MessageReceiver(DatabaseService databaseService, String destinationName){
         this.databaseService = databaseService;
         LOG.info("{}Creating MessageReceiver for queue with destination: {}", LOG_PREFIX, destinationName);
     }

     @Override
     public void onMessage(Message message) {

         String messageText = null;

         if (message instanceof TextMessage) {
             TextMessage tm = (TextMessage) message;
             try {
                 messageText = tm.getText();
             } catch (JMSException e) {
                 LOG.error("{} Error getting message from AMQ", e);
             }
         } else if (message instanceof ActiveMQMessage) {
             messageText = message.toString();
         } else {
             LOG.warn("{}Unrecognised message type, cannot process", LOG_PREFIX);
             LOG.warn(message.toString());
         }

         try {
             databaseService.sendMessageNoResponse(messageText);
         } catch (Exception e) {
             LOG.error("{}Unable to acknowledge message from AMQ. Message: {}", LOG_PREFIX, messageText, e);
         }
     }
}

 public class AmqExceptionListener implements ExceptionListener {

     public static final Logger LOG = LogManager.getLogger(AmqExceptionListener.class);
     private static final String LOG_PREFIX = "[AmqExceptionListener ] ";

     @Override
     public void onException(JMSException e){
         LOG.error("{}Exception thrown by ActiveMQ", LOG_PREFIX, e);
     }
 }

The console output I get from my application is just the below (apologies, as it is not much to go off)
[2019-12-12 14:43:30.292] [WARN ] Transport (tcp://[address]:61616) failed , attempting to automatically reconnect: java.io.EOFException
[2019-12-12 14:43:51.098] [WARN ] Failed to connect to [tcp://[address]:61616] after: 10 attempt(s) continuing to retry.

Process finished with exit code 0

A: Very interesting Question!
Configuring the maxReconnectAttempts=-1 will cause the connection attempts to be retried forever, but what I feel the problem here are as follows:

*

*You are trying to connect to ActiveMQ while creating the Bean at App
startup, If ActiveMQ is not running when APP is starting up, the
Bean creation would retry the connection attempts forever causing a
timeout and not letting the APP to start.

*Also when the ActiveMQ stops running midway you are not reattempting the connection as it is done inside @Bean and will only happen on APP startup

Hence the Connection shouldn't happen at Bean creation time, but maybe it can be done after the APP is up (maybe inside a @PostConstruct block)
These are just the pointers, You need to take it forward
Hope this helps!
Good luck!


text:
Q: Aggregate total sum for like entries in MongoDb using Aggregration framework I have a huge collection conatins only this kind of documents.
  {
        "_id" : "https://example.com/test.html",
        "Count" : 1503.0000000000000000
    },
    {
        "_id" : "http://example.org/gr/",
        "Count" : 715.0000000000000000
    },
    {
        "_id" : "https://example.com/document/d//edit",
        "Count" : 710.0000000000000000
    },
    {
        "_id" : "http://example.org/gr/test.htm",
        "Count" : 429.0000000000000000
    }
}

How can I use mongodb aggregation framework to achive this result.
 {
        "_id" : "https://example.com/",
        "Count" : 2213.0000000000000000
    },
    {
        "_id" : "http://example.org/",
        "Count" : 1144.0000000000000000
    }
}

Specificaly How can I use text serach after split in $project pipeline?
Thanks In Advance!!

A: First you've got to use $substr to only retrieve the beginning of each URI.
Then you should be able to $group and $sum things up.
The first part might get tricky and/or impossible, because I don't know of any operator that returns the position of the third slash in a string.

Though my suggestion would be to rewrite the code, in order to split the string before you insert it. i.e.
{
  id: ObjectId("..."),
  domain: "http://example.com",
  path: "test.html",
  count: 1503
}

When subdomains should also be accessible, I'd go or something like:
{
  id: ObjectId("..."),
  uri: "http://sub.example.org/foo.html",
  protocol: "http",
  subdomain: "sub",
  domain: "example.org",
  path: "foo.html",
  count: 1503
}

This of course may be slower on insert, but you can query a lot of stuff.


text:
Q: Auto-generating a small book? I'm considering a dive into TeX, but first want to determine if it makes sense for my particular project. I've inherited responsibility for a roster book with names, addresses, etc. for a club with several hundred members. Every year we print hard copies of this book. Currently, the book is a hand-edited Word document. I have three requirements:

*

*Auto-generate the TeX that constitutes the book, pulling current member data from a database/spreadsheet.

*Calculate page breaks dynamically so that member entries are not split across pages.

*Have it look really nice.

I figure I'm in the right place for #3, but, being a complete TeX n00b, I'd like opinions on whether this is something I should even attempt, and if so, the best way to approach it. My programming skills are fairly decent, so that won't be an issue. Thanks much.

A: The datatool package, which can read csv files, is easily capable of doing (1). For (2), pagebreaking can easily be controlled using the minipage environment. (I.e. construct a member environment that wraps the member information into a minipage.) (There are other ways, too.) (3) is obviously possible.  If you need nice fonts (like any fonts available on your system) you should use XeLaTeX.
Be prepared to spend a bit of time learning about LaTeX though.
See this link for an up-to-date free intro.  Also the answers here.


text:
Q: free allocated linked list valgrind says that I don't use "free" in 2 places.
My program deals with linked list of structs, therefore, I have another function that destroys the linked list by using the head struct.
where should I free the newState and newJudge despite the eurovisionDestroy function?
Thank you.

typedef struct citizen_t{
    int citizenVote;
    struct citizen_t* next;
}*Citizen;

typedef struct state_t{
    int stateId;
    char* stateName;
    char* stateSong;
    Citizen citizenFirst;
    Citizen citizenIterator;
    int citizenSize;
    double score;
    struct state_t* next;
}*State;

typedef struct judge_t{
    int judgeId;
    char *judgeName;
    int judgeResults[NUM_STATES_JUDGES_VOTE];
    struct judge_t* next;
}*Judge;

struct eurovision_t{
    int stateSize;
    int sizeJudges;
    Judge judgeFirst;
    State  stateFirst;
    Judge judgeIterator;
    State  stateIterator;
};

void eurovisionDestroy(Eurovision eurovision){
    if(eurovision == NULL){
        return;
    }

    Citizen tmpCitizen;
    State tmpState;
    Judge tmpJudge;

    if(eurovision->stateSize != 0){
        while(eurovision->stateFirst != NULL){
            if(eurovision->stateFirst->citizenSize != 0 ){
                while(eurovision->stateFirst->citizenFirst != NULL){
                    tmpCitizen = eurovision->stateFirst->citizenFirst->next;
                    free(eurovision->stateFirst->citizenFirst);
                    eurovision->stateFirst->citizenFirst = tmpCitizen;
                }
            }
            tmpState = eurovision->stateFirst->next;
            free(eurovision->stateFirst->stateName);
            free(eurovision->stateFirst->stateSong);
            free(eurovision->stateFirst);
            eurovision->stateFirst = tmpState;
        }
    }

    if(eurovision->sizeJudges != 0){
        while(eurovision->judgeFirst != NULL){
            tmpJudge = eurovision->judgeFirst->next;
            free(eurovision->judgeFirst->judgeName);
            free(eurovision->judgeFirst);
            eurovision->judgeFirst = tmpJudge;
        }
    }

    free(eurovision);
}

The function where I alllocate new state(state struct), dont use  free here but in the destroy function above
EurovisionResult eurovisionAddState(Eurovision eurovision, int stateId,
                                    const char *stateName,
                                    const char *songName){
    if(eurovision == NULL || songName == NULL || stateName == NULL){
        return EUROVISION_NULL_ARGUMENT;
    }
    if(stateId < 0 ) {
        return EUROVISION_INVALID_ID;
    }
    if(!isValidName(stateName) || !isValidName(songName) ){
        return EUROVISION_INVALID_NAME;
    }
    State newState = malloc(sizeof(*newState));
    if(newState == NULL){
        return EUROVISION_OUT_OF_MEMORY;
    }

    newState->stateName = malloc(sizeof(char)*(strlen(stateName)+1));
    if(newState->stateName == NULL){
        free(newState);
        return EUROVISION_OUT_OF_MEMORY;
    }
    newState->stateSong = malloc(sizeof(char)*(strlen(songName)+1));
    if(newState->stateSong == NULL){
        free(newState->stateName);
        free(newState);
        return EUROVISION_OUT_OF_MEMORY;
    }

    if(eurovision->stateSize == 0){
        newState->stateId = stateId;
        newState->stateName= strcpy(newState->stateName,stateName);
        newState->stateSong = strcpy(newState->stateSong,songName);
        newState->next = NULL;
        newState->score = 0.0;
        newState->citizenSize = 0;
        eurovision->stateFirst = newState;
        eurovision->stateIterator = newState;
        eurovision->stateSize++;
        return EUROVISION_SUCCESS;
    }
    State previousState =  eurovision->stateFirst;
    eurovision->stateIterator = eurovision->stateFirst;
    for(int i = 0 ; i < eurovision->stateSize ; i++){
        if( stateId == eurovision->stateIterator->stateId ){
            return EUROVISION_STATE_ALREADY_EXIST;
        }
        previousState = eurovision->stateIterator;
        eurovision->stateIterator = eurovision->stateIterator->next;
    }
    newState->stateId = stateId;
    newState->stateName= strcpy(newState->stateName,stateName);
    newState->stateSong = strcpy(newState->stateSong,songName);
    newState->next = NULL;
    newState->score = 0.0;
    newState->citizenSize = 0;
    eurovision->stateSize++;
    previousState->next = newState;
    return EUROVISION_SUCCESS;
}

valgrind output :
==23285== HEAP SUMMARY:
==23285==     in use at exit: 228 bytes in 8 blocks
==23285==   total heap usage: 1,549 allocs, 1,541 frees, 30,098 bytes   allocated
==23285==
==23285== 70 (64 direct, 6 indirect) bytes in 1 blocks are definitely lost in loss record 6 of 8
==23285==    at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==23285==    by 0x400DBC: eurovisionAddJudge (eurovision.c:263)
==23285==    by 0x4040DC: testAddJudge (eurovisionTests.c:206)
==23285==    by 0x404E24: main (eurovisionTestsMain.c:17)
==23285==
==23285== 76 (64 direct, 12 indirect) bytes in 1 blocks are definitely lost in loss record 7 of 8
==23285==    at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==23285==    by 0x40090D: eurovisionAddState (eurovision.c:159)
==23285==    by 0x403B67: testAddState (eurovisionTests.c:172)
==23285==    by 0x404D8C: main (eurovisionTestsMain.c:15)
==23285==
 ==23285== 82 (64 direct, 18 indirect) bytes in 1 blocks are definitely lost in loss record 8 of 8
 ==23285==    at 0x4C29BC3: malloc (vg_replace_malloc.c:299)
==23285==    by 0x40090D: eurovisionAddState (eurovision.c:159)
==23285==    by 0x403B18: testAddState (eurovisionTests.c:171)
 ==23285==    by 0x404D8C: main (eurovisionTestsMain.c:15)


text:
Q: aptana spurious syntax errors what is beginning to drive me a bit crazy is that I googled "Aptana spurious syntax errors" ... and virtually nothing came up... I feel marooned.
I've tried refresh, opening and closing Aptana, even restarting my machine... nothing doing.  I've also tried to see if I can find a suitable "ignore this type of error" option in the configs...
The things that seem to be causing this are backticks ... even in comments! (but also in code)  and also square brackets ... which allow spaces around numbers... i.e. "[ 0 ]" causes a "syntax error", but it goes away if I change this to "[0]"... so yes, I found this question: Aptana flagging valid brackets as PHP syntax error
Googling and searching "aptana backticks" or "aptana back ticks" comes up with nothing!  Using the Aptana help came up with nothing!  Anyone got any suggestions?
later
a strange explanation... which I leave for anyone who encounters the same problem.  Inadvertently I had left an isolated backtick in the middle of a php file... rather than flagging this, Aptana signalled syntax errors all over the place.


text:
Q: How do I check if an item is in a list which is in a dictionary? How would I search a list within a dictionary and then retrieve the key?
The lists are values of a dictionary and I'm trying to find a specific item within those lists and then return the key.
For example:
wanted_fruit = "granny_smith"
fruits = {
     "oranges" : ["tangerine", "mandarin", "clementine", "blood_orange"],
     "apples" : ["golden_delicious", "gala", "granny_smith", "rome"],
     "melons" : ["watermelon", "honeydew", "cantaloupe"]
}

How would I get an output of apples (as "granny_smith" is within the apples list)?

A: There's no efficient way to do a search with the data structure you show. You'd need to scan through all the lists in the dictionary. Now, for a small data set that is still reasonably fast, but it would slow down a lot if you have huge amounts of data. If you're going to do a lot of these searches, you might want to reverse the data structure so that you can look up the keys you care about directly.
data = {
    "oranges" : ["tangerine", "mandarin", "clementine", "blood_orange"],
    "apples" : ["golden_delicious", "gala", "granny_smith", "rome"],
    "melons" : ["watermelon", "honeydew", "cantaloupe"]
}
reversed_data = {variety: fruit_type for fruit_type, varieties in data.items()
                                     for variety in varieties}

Now reversed_data["granny_smith"] will be "apples", and it's a very efficient dictionary lookup. You can do those kinds of checks a lot without needing to inefficiently search through the original data structure again and again.

A: Just loop over the dictionnary:
for fruit_type, fruit_lst in fruits.items():
  if wanted_fruit in fruit_lst:
     print(fruit_type)

A: wanted_fruit_category = next(
    (category_name for category_name, category_items in fruits.items()
                   if wanted_fruit in category_items),
    None
)

A generator expression is used to iterate through all of the items in the dictionary. It evaluates to None if none of the dictionary values contained your wanted_fruit

A: Try:
result = [k for k, v in fruits.items() if wanted_fruit in v]

print(result)
# Expected Output: ['apples']

Happy coding :)


text:
Q: New shell window with specified current dir Now i'm executing next command
gnome-terminal  --tab -e "run1"  --tab -e "run2"

But run1 and run2 not in my home dir, how can i point shell to right dir. "my_dir1/my_dir2/runX" - not a case.

A: The manual (man) is your friend.
man gnome-terminal reveals the option
--working-directory=DIRNAME


text:
Q: Setting up multiple alarms , restarting alarm app when phone restarts I am trying to create an app where there would be multiple alarm(according to the will of user,so not definite ) but the i am unable to find any assistance. I also my app to run even if the phone is restarted. so in short i want to know about the operations of the usual alarm app that runs in the android phone

A: You can use a BroadcastReceiver to start your service when your phone restarts. In your service then you can register your alarms.
Here you can find an example:
Autostart Service on Device Boot


text:
Q: Count the number of occurrences of a value on a multi-page spreadsheet The spreadsheet has many pages and more pages will be added in the future and I don't know the names of these future added. I can't just do:
=countif(Tab1!A:Z,Value1)+countif(Tab2!A:Z,Value1)+countif(Tab3!A:Z,Value1)...

because I don't know the names of these tabs to be added.
Is there a way to count the occurrences on new sheets without explicitly adding them in such a formula?

A: It seems that this can not be achieved using a formula. It must be written as a script. You can see an example at this question: COUNTIF Statements: Range Across All Sheets + Cell Reference as Criterion

A: I'm not sure if what you're trying to do is possible. But, I can help you with the getting the spreadsheet pages/sheets name part.
By using this sheets projection:
https://spreadsheets.google.com/feeds/worksheets/{spreadsheetId}/public/basic

you'll be able to get the list of all spreadsheet pages in xml format.


text:
Q: Loop over a cell array if file exists in folder and print to new document I want to loop over a cell array while reading in files within a working
folder. If that file exists, create and open new file called testcase.txt
print statement. If that file doesn't exist in working folder, do nothing
and move on to next iteration.
Here's what example looks like with search for one file
fid=fopen('testcase.txt','w');

if exists('abc.txt','file')
    abc.txt = 1;
    fprintf('test case successful');
else
    abc.txt = 0;
end

fclose(fid);

Here's a cell array example expanded over multiple cases looks like
I can't seem to get it to run properly. Can someone help me to get this
loop to work?
extension = {'abc.txt' 'def.txt' 'ght.txt'};
convertedfile = [abc.txt def.txt ght.txt];

fid=fopen('testcase.txt','w');

for i = extension
    if exist(['''' convertedfile ''''],'file')
        i = 1;
        fprintf('test case successful');
    else
        i = 0;
    end
end

fclose(fid);

A: Are you looking for something like this?
extension = {'abc.txt' 'def.txt' 'ght.txt'};
% convertedfile = [abc.txt def.txt ght.txt];

fid=fopen('testcase.txt','w');

for i = 1:length(extension)
    if ~exist(extension{i},'file')

        fprintf(fid,'test case successful\n');
    end
end
fclose(fid);

Also, you could print the text file for which it was successful using:
fprintf(fid,'%s: test case successful\n',extension{i});


text:
Q: Conflicting constraints on GIDSignInButton in Google Sign-In SDK 2.0.1 I'm trying to upgrade from Google Sign-In SDK 1.0.0 to 2.0.1 and ran into some conflicting constraints when trying to position an instance of the GIDSignInButton.
It seems like GIDSignInButton may define its own dynamic constrains which conflict with the ones I set in Interface Builder. I'm not able to verify this since the SDK is closed source.
The constraint warning can actually be reproduced with Google's own sample code on https://github.com/googlesamples/google-services/tree/81c831d85a67157746009fa2df81a683f860d21e/ios/signin.
Is there a work around to position this button or is this just a bug in SDK 2.0.1?

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7f9e0064b650 V:[UIView:0x7f9e0064b360(198)]>",
    "<NSLayoutConstraint:0x7f9e0064b830 UIView:0x7f9e0064b360.centerY == GIDSignInButton.centerY   (Names: GIDSignInButton:0x7f9e0046f000 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7f9e006603c0 h=--& v=--& GIDSignInButton.midY == + 97   (Names: GIDSignInButton:0x7f9e0046f000 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7f9e0064b830 UIView:0x7f9e0064b360.centerY == GIDSignInButton.centerY   (Names: GIDSignInButton:0x7f9e0046f000 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7f9e00476cd0 GIDSignInButton.width == 3.26531*GIDSignInButton.height   (Names: GIDSignInButton:0x7f9e0046f000 )>",
    "<NSLayoutConstraint:0x7f9e00476f20 H:[GIDSignInButton(160)]   (Names: GIDSignInButton:0x7f9e0046f000 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7f9e00660410 h=--& v=--& V:[GIDSignInButton(44)]   (Names: GIDSignInButton:0x7f9e0046f000 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7f9e00476cd0 GIDSignInButton.width == 3.26531*GIDSignInButton.height   (Names: GIDSignInButton:0x7f9e0046f000 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

Unable to simultaneously satisfy constraints.
    Probably at least one of the constraints in the following list is one you don't want. Try this: (1) look at each constraint and try to figure out which you don't expect; (2) find the code that added the unwanted constraint or constraints and fix it. (Note: If you're seeing NSAutoresizingMaskLayoutConstraints that you don't understand, refer to the documentation for the UIView property translatesAutoresizingMaskIntoConstraints)
(
    "<NSLayoutConstraint:0x7f9e0064b7e0 UIView:0x7f9e0064b360.centerX == GIDSignInButton.centerX   (Names: GIDSignInButton:0x7f9e0046f000 )>",
    "<NSLayoutConstraint:0x7f9e00657480 H:[UIView:0x7f9e0064b360]-(0)-|   (Names: '|':UIView:0x7f9e0064b050 )>",
    "<NSLayoutConstraint:0x7f9e006574d0 H:|-(0)-[UIView:0x7f9e0064b360]   (Names: '|':UIView:0x7f9e0064b050 )>",
    "<NSAutoresizingMaskLayoutConstraint:0x7f9e0065dda0 h=--& v=--& GIDSignInButton.midX == + 207   (Names: GIDSignInButton:0x7f9e0046f000 )>",
    "<NSLayoutConstraint:0x7f9e0046d5e0 'UIView-Encapsulated-Layout-Width' H:[UIView:0x7f9e0064b050(375)]>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x7f9e0064b7e0 UIView:0x7f9e0064b360.centerX == GIDSignInButton.centerX   (Names: GIDSignInButton:0x7f9e0046f000 )>

Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKit/UIView.h> may also be helpful.

A: I had the same issue and the solution I found was to embed the google sign-in button in another view and set the constraints on the container.
the only constraints i gave to the GIDSignInButton instance was center (x,y) in container cause otherwise it will still be shifted to the right.
I hope this helps

A: Google has fixed this bug in Google Sign-In SDK 2.1.0 (released on 6/17/2015).

Fixes Auto Layout issues with GIDSignInButton.


text:
Q: 13.10 Can't Adjust Dell Laptop Backlight I have a Dell Studio 1558. When I originally installed 13.04 on it, I had to modify my /etc/default/grub with the following:
GRUB_CMDLINE_LINUX_DEFAULT="acpi_backlight=vendor dell_laptop.backlight=0 quiet splash"

Doing that made everything work, the keyboard brightness buttons, the OSD in the top right corner, and the brightness slider in System Settings. However, upon upgrading to 13.10, I once again am unable to adjust the backlight. This is also the case if I use either of the following:
GRUB_CMDLINE_LINUX_DEFAULT="acpi_backlight=vendor quiet splash"
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

The backlight is stuck at a single brightness level, at a guess I think it's somewhere around 50%. The OSD still comes up if I push the keyboard buttons, but the bar only goes down one division from 100% and resets back to 100%, if I press decrease again. The slider in 'System Settings' does nothing.
Any help is greatly appreciated!

A: Try this in a terminal:
echo 4000 | sudo tee /sys/class/backlight/intel_backlight/brightness

4000 is the full brightness, and 0 is no brightness (screen completely dark), so you can choose any value in between as you like. Note that the path to the brigtness may be different on your computer, so adjust accordingly.
This works for me on Dell Studio 1558, Ubuntu 13.10 64 bit. Also you'll have to do this every-time you have to change brightness. It will reset when you restart the computer.
Good luck!

A: Doing both of the steps mentioned here fixed this issue with a Dell Studio 1558 and Ubuntu 13.10: http://ubuntuforums.org/showthread.php?t=2181534
Change /etc/default/grub
I used "sudo vim /etc/default/grub" but use whatever editor you're comfortable with but you will need to use sudo to edit it as the root user.
From:
GRUB_CMDLINE_LINUX="acpi_backlight=vendor"

To:
GRUB_CMDLINE_LINUX=""

Then run:
sudo update-grub

Add /usr/share/X11/xorg.conf.d/20-intel.conf
I used "sudo vim /usr/share/X11/xorg.conf.d/20-intel.conf" and then ran :set paste and hit i for insert and pasted in the contents.
Section "Device"
    Identifier  "card0"
    Driver      "intel"
    Option      "Backlight"  "intel_backlight"
    BusID       "PCI:0:2:0"
EndSection

Then reboot and login again and your function key with the brightness up/down should work again.


text:
Q: How to set atrribute defalutvalue system default image? I can't find c# winform default error image or null image address
how can find c# winform defalut null image?
[System.ComponentModel.Browsable(true),
    System.ComponentModel.Category("Default"),
    System.ComponentModel.Description("Set thr first custom background Image"),
    ***System.ComponentModel.DefaultValue(typeof(Image),"null")]***
    // Property for the background image to be drawn behind the button text.
    public Image BackgroundImageBefore
    {
        get
        {
            return this.backgroundImage;
        }
        set
        {
            this.backgroundImage = value;
        }
    }

'


text:
Q: How to Pause and Resume Downloading Files with ASIHTTP Request in iPhone I m using ASIHTTP Request sample source code for downloading urls.
My question is that how to pause and resume the downloading files.
Please Help.

A: Deprecation Notice
ASIHTTP was deprecated around 2011, if you want network connectivity now, you should look up AFNetworking for ObjC or Alamofire for Swift, or stick to the native support:
For native support, in iOS 7 Apple added the NSURLSession, which can start download tasks (NSURLSessionDownloadTask), and these can be cancelled and restarted, check the method  downloadTaskWithResumeData(_:) from NSURLSession, that has a very good explanation.
ASIHTTP is no longer needed, if you gotta are keeping a legacy app running, well, good luck.
Original Answer
Posted on 2011
ASI itself can resume a download from a file using [myASIRequest setAllowResumeForFileDownloads:YES];, check out the How-to-Use for an example.
Edit: Ok, there's no easy way to pause a download (a [myRequest pause] would be ideal). After reading and trying for a while, turns out that cancelling the request and resending it again is the only way.
For example, here's an example class I made:
@interface TestViewController : UIViewController <ASIHTTPRequestDelegate>
{
    ASIHTTPRequest *requestImage;
    UIImageView *imageViewDownload;
}

@property (nonatomic, retain) IBOutlet UIImageView *imageViewDownload;

- (IBAction)didPressPauseButton:(id)sender;
- (IBAction)didPressResumeButton:(id)sender;

To start (or restart) the download:
- (IBAction)didPressResumeButton:(id)sender
{
    if (requestImage)
        return;

    NSLog(@"Resumed");

    // Request
    requestImage = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:@"http://www.myheadhealth.com/_IMAGES/cheese.jpg"]];

    // Using a temporary destination path just for show.
    // Better pick a suitable path for your download.
    NSString *destinationDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"cheese.jpg"];
    NSString *temporaryDownloadPath = [NSTemporaryDirectory() stringByAppendingPathComponent:@"cheese.jpg-part"];

    requestImage.downloadDestinationPath = destinationDownloadPath;
    requestImage.temporaryFileDownloadPath = temporaryDownloadPath;
    requestImage.allowResumeForFileDownloads = YES;
    requestImage.delegate = self;
    [requestImage startAsynchronous];
}

In the exmaple above, I'm loading a random image of cheese I found, and storing a temporary download, and a full download.
Canceling the request will keep the contents of the temporary file intact, in fact, I made an UIImageView, and when pressing "Cancel" I could see a part of the downloaded file. If you want to try it out:
- (void)didPressPauseButton:(id)sender
{
    if (requestImage)
    {
        // An imageView I made to check out the contents of the temporary file.
        imageViewDownload.image = [UIImage imageWithContentsOfFile:requestImage.temporaryFileDownloadPath];

        [requestImage clearDelegatesAndCancel];
        requestImage = nil;

        NSLog(@"Canceled");
    }
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
    imageViewDownload.image = [UIImage imageWithContentsOfFile:request.downloadDestinationPath];

    requestImage = nil;
}


text:
Q: mixed predicator types for Random forest I am trying to build a classification model using Random forest for a data set with 5 predicator variables. two predicator variable are of continuous type, one can be a real value in the interval of [0, 1000] while the other one can be a real value of [-10, 10]; one predicator variable is of integer values of [10000, 15000]. In addition, the two remaining predicator variables are of categorical values, i.e., { A, B, C, D, E F} and {NY, LA, Chicago}. Are there any procedures required for pre-processing these different predicator types?

A: many of the exhaustive search algorithms will be biased towards variables with many values. separating the variable selection and split selection process seems to help this, as described in this paper. they have a package implemented in R as well. i don't know of a way to avoid this with mixed type data using the more common approaches. however, despite the fact that this problem results in bias, in my experience the predictive performance hasn't been hugely different, so your mileage may vary. it depends on what you are doing. i'd do some simulations either way. the same group has two bmc bioinformatics papers on conditional permutation importance that discuss these issues.


text:
Q: Securing GRPC connections with server.key and server.crt using protobuf-net grpc I'm trying to make secure grpc calls from the client side but I can't seem to get my code to work; here are the steps and implementations I've taken.
My specs: I'm running visual studio on mac m1 pro and I'm using Protobuf-net Grpc
Step 1 - Install OpenSSL
brew install openssl

Step 2 - Create a certificate and key
openssl req -x509 -newkey rsa:4096 -keyout server.key -out server.crt -days 365 -nodes

this asked a couple of questions. and then created the crt and key files.
I've also confirmed that certificate and key pair are created correctly by running the below commands.
openssl x509 -noout -modulus -in server.crt | openssl md5
openssl rsa -noout -modulus -in server.key | openssl md5

Implementations
Server:
Program.cs file
var builder = WebApplication.CreateBuilder(args);

X509Certificate2 cert = new X509Certificate2("/Users/asimgunduz/server.crt", "/Users/asimgunduz/server.key");

builder.WebHost.ConfigureKestrel(opt =>
{
    opt.Listen(IPAddress.Any, 5010, listenOptions =>
    {
        listenOptions.Protocols = HttpProtocols.Http1;
        listenOptions.UseHttps(cert);
    });

});

Client Side
 public static void RegisterGrpcService<TService>(this IServiceCollection Services) where TService : class
    {
        X509Certificate2 certificate = new X509Certificate2("/Users/asimgunduz/server.crt", "/Users/asimgunduz/server.key");

        var socketsHandler = new SocketsHttpHandler
        {
            AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
            PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
            KeepAlivePingDelay = TimeSpan.FromSeconds(60),
            KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
            EnableMultipleHttp2Connections = true,
        };

        socketsHandler.SslOptions.RemoteCertificateValidationCallback = (message, cert, chain, errors) =>
        {
            // Perform custom validation here and return a boolean indicating whether the certificate is valid
            return certificate.Equals(cert);
        };

        var hand = new GrpcWebHandler(GrpcWebMode.GrpcWeb, socketsHandler);

        //hand.HttpVersion = HttpVersion.Version11;

        Services.AddCodeFirstGrpcClient<TService>(x =>
        {
            x.ChannelOptionsActions.Add(x => new GrpcChannelOptions
            {
                HttpHandler = hand,

                MaxReceiveMessageSize = null, //30000000
                MaxSendMessageSize = null, //30000000
                Credentials = ChannelCredentials.Insecure,
                UnsafeUseInsecureChannelCallCredentials = true,
                ServiceConfig = new ServiceConfig { LoadBalancingConfigs = { new RoundRobinConfig() } }
            });

            x.Address = new Uri("http://localhost:5010");

        })
       .ConfigurePrimaryHttpMessageHandler(x => hand);
    }

    public static void RegisterGrpcServiceWithSsl2<TService>(this IServiceCollection services, string address) where TService : class
    {
        X509Certificate2 certificate = new X509Certificate2("/Users/asimgunduz/server.crt", "/Users/asimgunduz/server.key");

        var handler = new SocketsHttpHandler
        {
            SslOptions = new SslClientAuthenticationOptions
            {
                RemoteCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    X509Chain x509Chain = new X509Chain();
                    x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    bool isChainValid = x509Chain.Build(new X509Certificate2(cert));
                    return isChainValid;
                },
                ClientCertificates = new X509Certificate2Collection { certificate }
            },
            PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
            KeepAlivePingDelay = TimeSpan.FromSeconds(60),
            KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
            EnableMultipleHttp2Connections = true
        };

        var channel = GrpcChannel.ForAddress(address, new GrpcChannelOptions
        {
            HttpHandler = handler,
        });

        services.AddCodeFirstGrpcClient<TService>(x =>
        {
            x.Address = new Uri(address);
            x.ChannelOptionsActions.Add(options =>
            {
                options.HttpHandler = handler;
            });
        });
    }

When I run Server it throws the following exception
"The server mode SSL must use a certificate with the associated private key."
any help is much appreciated.

A: Aright after an hour of hard work, I've managed to make my code work:
just leaving here in case future me or someone else needs it..
Changes made in my code
(SERVER)
program.cs
I've changed port number from 5010 => 7178
//Created certificate with the below method
var certificate =
  X509Certificate2.CreateFromPemFile("/Users/asimgunduz/server.crt", Path.ChangeExtension("/Users/asimgunduz/server.crt", "key"));

//Verify is blueprints match
var verf = certificate.Verify();

//and finally add usehttps(with the created certificate)

builder.WebHost.ConfigureKestrel(opt =>
{
    opt.ListenLocalhost(7178, o =>
    {
        o.Protocols = HttpProtocols.Http1;
        o.UseHttps(certificate);
    });

});

and this is How I updated my extension methods in client side
        public static void RegisterGrpcServiceWithSsl2<TService>(this IServiceCollection services, string address) where TService : class
    {

        var certificate =
          X509Certificate2.CreateFromPemFile("/Users/asimgunduz/server.crt", Path.ChangeExtension("/Users/asimgunduz/server.crt", "key"));

        var socketsHandler = new SocketsHttpHandler
        {
            SslOptions = new SslClientAuthenticationOptions
            {
                RemoteCertificateValidationCallback = (sender, cert, chain, errors) =>
                {
                    X509Chain x509Chain = new X509Chain();
                    x509Chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
                    bool isChainValid = x509Chain.Build(new X509Certificate2(cert));
                    return isChainValid;
                },
                ClientCertificates = new X509Certificate2Collection { certificate }
            },
            PooledConnectionIdleTimeout = Timeout.InfiniteTimeSpan,
            KeepAlivePingDelay = TimeSpan.FromSeconds(60),
            KeepAlivePingTimeout = TimeSpan.FromSeconds(30),
            EnableMultipleHttp2Connections = true
        };

        var hand = new GrpcWebHandler(GrpcWebMode.GrpcWeb, socketsHandler);

        hand.HttpVersion = HttpVersion.Version11;

        services.AddCodeFirstGrpcClient<TService>(x =>
        {
            x.ChannelOptionsActions.Add(x => new GrpcChannelOptions
            {
                HttpHandler = hand,

                MaxReceiveMessageSize = null,
                MaxSendMessageSize = null,
                Credentials = ChannelCredentials.Insecure,
                UnsafeUseInsecureChannelCallCredentials = true,
                ServiceConfig = new ServiceConfig { LoadBalancingConfigs = { new RoundRobinConfig() } }
            });

            x.Address = new Uri(address);

        })
       .ConfigurePrimaryHttpMessageHandler(x => hand);

    }


text:
Q: Making a clone function without throwing CloneNotSupportedException exception in Java As part of our homework we are asked to implement an abstract class with a clone method. The frame for the function is given:
/**
 * @effects Creates and returns a copy of this.
 */
public Object clone() {
    // TODO: Implement this method

}

The Shape class has two fields:
private Point location;
private Color color;

At the instructions we're told that the method doesn't throw a CloneNotSupportedException exception, and are also asked why it is so. At all the examples we've seen on the internet the clone method does throw a CloneNotSupportedException.
Would you please point us to the reason why this clone method shouldn't throw that exception.
The method we have written is:
/**
 * @effects Creates and returns a copy of this.
 */

public Object clone() {
    Shape new_shape = (Shape)super.clone();
    new_shape.setColor(this.getColor());
    new_shape.location = (Point)location.clone();
    return new_shape;

}

It gives us an error on the (Shape)super.clone() part, saying:
Unhandled exception type CloneNotSupportedException, how should we create the clone method?

A: Your class should implement Clonable interface.
Also you can use Covariant Return Types in order to return Shape/Point instead of Object. This helps you to avoid unnecessary type casts.

A:
Unhandled exception type CloneNotSupportedException

That's because the clone() method in the Object is defined to throw CloneNotSupportedException:
protected Object clone() throws CloneNotSupportedException

See API doc: Object#clone()
To overcome that, you either need to handle it by using a try/catch block or redefine it by adding a throws clause.
Update:

At the instructions we're told that the method doesn't throw a CloneNotSupportedException exception, and are also asked why it is so.

IMO -

*

*You are overriding a method in a super class. Only the return type, method name, and the parameter types are considered as method signature. So, while overriding a method you can omit the throws clause in the subclass even though the method in the superclass has it.

*Whenever your class implements the Cloneable interface, it's telling the Object class that it is okay to make a clone of it. In such a case, a proper implementation of the clone method should call the super.clone method. Now, you can see that it's actually the clone method in the Object class that actually makes the copy. So, we should leave up to the Object.clone() to throw that CloneNotSupportedException. And it will do so if any class in hierarchy does not implement the Cloneable interface.

I hope that makes sense.
Even though it's kind of vast, in case you want to read about it more. It's explained in Effective Java.

A: The reason that other implementations throw the CloneNotSupportedException is that it is part of the existing clone() method of Object. Just because a method is defined to throw the exception does not mean it has to do so. When you implement your clone() method on Shape and its derived classes, do not throw the exception.
The reason that (Shape)super.clone() throws an exception is that this is the default behavior. Implement clone() on Shape.


text:
Q: import org.openide.filesystems.FileUtil I have just upgraded to Netbeans 7.3 and cannot import
org.openide.filesystems.FileUtil;

I get the message org.openide.filesystms does not exist.
Can someone help ?

A: The resolution is documented in this netbeans's bug


text:
Q: How to use Velocity NumberTool for big currency numbers I'm using the Joda Money.class for currency in my project.
I'm using the NumberTool for formatting numbers inside a Velocity template.
context.put("number", new NumberTool());

I convert Money values into ints for placing these values inside a Velocity template.
example:
// 123435         €1234.35
priceInCents = price.getAmountMinorInt();

I want to format this value inside the Velocity template as below:
1.234,35

How do I accomplish this?
I tried the following cases:
$number.format('#0,00', $price) //Output: 1234,35
$number.format('#0.00', $price) //Output: 123435.00
$number.format('#00,00', $price) //Output: 12,34,35
$number.format('#00.00', $price) //Output: 123435.00
$number.format('#000,00', $price) //Output: 12,34,35
$number.format('#000.00', $price) //Output: 123435.00

A: So I found my answer.
Make your own tool
    context.put("currency", new CurrencyTool());

Usage:
$currency.format($price)

Basics created tool:
/**
 * Tool for doing currency formatting
 */
@DefaultKey(value = "currency")
public final class CurrencyTool extends FormatConfig {

    /**
     * Constructor
     */
    public CurrencyTool() {
    }

    /**
     * @param money The {@link Money} object to format
     * @return
     */
    public String format(Money money) {
        // Get the currency as an integer
        final int value = money.getAmountMinorInt();

        // Determine the units and cents
        final int cents = value % 100;
        String units = "" + (value / 100);

        // Final formatted values
        String formattedCents = "";
        String formattedUnits = "";

        // Format the cents to a 2 decimal number
        formattedCents = cents < 10 ? "0" + cents : "" + cents;

        // Format the units to parts of 3 separated with a dot
        if (units.length() > 3) {
            // units is above 999, formatting required

            //Determine the length of the part that doesn't needs to be segmented
            //example: 12 of 12345234 (12.345.234)
            final int nonSegment = units.length() % 3;
            formattedUnits = units.substring(0, nonSegment);

            //place a dot for each segment
            //example: nonSegment (dot) 345 (dot) 234
            units = units.substring(nonSegment, units.length());
            for (String segment : units.split("(?<=\\G...)")) {
                formattedUnits = formattedUnits + "." + segment;
            }
        } else {
            // units is below 1000, no formatting required
            formattedUnits = units;
        }

        return formattedUnits + "," + formattedCents;
    }
}

A: $number.format("#,##0.00", "123456789.01") // 123,456,789.01

A: I have tried with this:
$number.format('¤#,##0.00', $numberValue)
and works ok


text:
Q: Change width of Responsive HTML Newsletter Template from Charles Mudy EDIT: Template can be found at https://github.com/charlesmudy/responsive-html-email-template
I like the template, however I am having issues changing the width and having it respond properly, and I do not know why. In a comment at the top, it is mentioned to change widths, simply do a find and replace on the following sizes:
    wrapper   : '500',
    columns   : '210',
    x-columns : [
                    left : '90',
                    right: '350'
            ]

However, changing the wrapper to 750, columns to 335 (half of 750, then minus 80 for padding and such, just like 500/210), and x-columns to 142 and 448 respectively, things are not working as intended.
As I shrink the browser, the template is not snapping to one column until 480px, leaving the right column partially out of view from 481-750px. If I revert back to the original sizes, it works find. I am not sure what I am missing.

A: You need to edit your @media rule as well. It is located on line 103 in the template.
You're adjusting the widths and max-widths of the template, but not accounting for the responsive design of the elements. Since you are essentially making all the elements larger you need to make your breakpoint larger as well. You can read more about media queries here.
Check out this fiddle.


text:
Q: How to automate helm package --sign non-interactively in bash I am writing a bash script on a machine without expect.
The script automates the build of a helm (v2.9.1) chart.
I've got to the part in the script where it runs a
helm package --sign --key 'mykey' --keyring 'path/to/keyring' -d chartdir chart
and because helm prompts for the passphrase of the gpg key I created in order to use provenance files (a requirement), I cannot script around the soliciting of the passphrase, which I would like to prompt for separately as the script is part of a CI/CD build chain.
I have tried using
yes $promptedPassPhrase | helm package --sign...
and I got
xrealloc: cannot allocate 18446744071562067968 bytes (237568 bytes allocated)
I also tried plain old
echo $promptedPassPhrase | helm package --sign...
and I got
Error: inappropriate ioctl for device
I also tried script and got the same response.  As I do not have expect on the server, I cannot expect my way round it, so I'm stumped as to how to automate the helm package command and am not going to use a key without a passphrase as it is bad practice.

A: I don't know how long this has been the case, or exactly which versions this works on, but this doc page says:

If your PGP private key has a passphrase, [...] You can set the HELM_KEY_PASSPHRASE environment variable to that passphrase in case you don't want to be prompted to enter the passphrase.

This works for me on v2.13.1. It looks like it was added in October of 2018, so my guess is that it was first available in v2.12.0-rc.1.
Although this doesn't directly answer the OP's question (since they asked about v2.9.1), it will hopefully help anyone who ends up here because they (like me the first time round) missed that line in the doc.


text:
Q: WSO2 - How to write a response from a DSS to a XML file I downloaded and installed wso2 esb and wso2 dss on my pc windows. Wso2 dss has been installed as part of wso2esb. the process I must realize is as follows:
-weep a set of rows from a db oracle
- Write on the resultset and write each line of the resultset into an xml file that I have a defined buffer;
for the first point i used wso2 dss now i want to create a wso2 esb proxy services calling the operation created with dss and insert the data in the xml file.
Can you tell me if there is an example on this? I attach my xml template file, can you suggest me how to insert the data read from the batabase into this file?
Thanks so much.
en<?xml version="1.0" encoding="utf-8"?>
<Z1BP_ALM_ORDER_HEADERS_I SEGMENT="1">
        <ORDERID>T0343FS15</ORDERID>
        <ORDER_TYPE>YT11</ORDER_TYPE>
        <PLANPLANT>2310</PLANPLANT>
        <MN_WK_CTR>
            <![CDATA[MAN_EST]]>
        </MN_WK_CTR>
        <PLANT>2310</PLANT>
        <PMACTTYPE>50</PMACTTYPE>
        <FUNCT_LOC>2310-000-202-001-04</FUNCT_LOC>
        <EQUIPMENT>000000000010000002</EQUIPMENT>
        <MAINTPLANT>2310</MAINTPLANT>
        <LOCATION>1</LOCATION>
        <START_DATE>20170523</START_DATE>
        <FINISH_DATE>20170524</FINISH_DATE>
        <PRIORITY>A</PRIORITY>
        <CURRENCY>EUR</CURRENCY>
        <SHORT_TEXT>TEST IDOC 1</SHORT_TEXT>
        <Z1BP_ALM_ORDER_HEADERS_I1 SEGMENT="1"/>
    </Z1BP_ALM_ORDER_HEADERS_I>
    <Z1BP_ALM_ORDER_PARTN_MUL SEGMENT="1">
        <ORDERID>T0343FS15</ORDERID>
        <PARTN_ROLE>VW</PARTN_ROLE>
        <PARTNER>00000003</PARTNER>
    </Z1BP_ALM_ORDER_PARTN_MUL>
    <Z1BP_ALM_ORDER_PARTN_MUL_UP SEGMENT="1"/>
    <Z1BP_ALM_ORDER_OPERATION SEGMENT="1">
        <ACTIVITY>0010</ACTIVITY>
        <CONTROL_KEY>PM01</CONTROL_KEY>
        <Z1BP_ALM_ORDER_OPERATION1 SEGMENT="1"/>
    </Z1BP_ALM_ORDER_OPERATION>
    <Z1BP_ALM_ORDER_OPERATION_UP SEGMENT="1"/>
    <Z1BP_ALM_ORDER_COMPONENT SEGMENT="1">
        <MATERIAL>
            <![CDATA[MAT_NO_LIST]]>
        </MATERIAL>
        <PLANT>2310</PLANT>
        <ITEM_CAT>N</ITEM_CAT>
        <ACTIVITY>0010</ACTIVITY>
        <PRICE>300</PRICE>
        <PRICE_UNIT>1</PRICE_UNIT>
        <REQUIREMENT_QUANTITY>1</REQUIREMENT_QUANTITY>
        <REQUIREMENT_QUANTITY_UNIT>ST</REQUIREMENT_QUANTITY_UNIT>
       <REQUIREMENT_QUANTITY_UNIT_ISO>PCE</REQUIREMENT_QUANTITY_UNIT_ISO>
    </Z1BP_ALM_ORDER_COMPONENT>

A: You can save the response to a property inside the synapse configuration and use file connectorr to write a content of that property to a file


text:
Q: Should Kyle be corrected, and if he doesn't, why? In a recent blog entry, Jeff Atwood quotes his sysadmin Kyle:

"Should the developers have access to the production environment, and if they do, to what extent?"

My understanding is that this sentence is only perfectly grammatical if it's parsed as:

"Should the developers have access to the production environment, and if they do [already have access to the production environment], to what extent [is it okay for them to have it]?"

However, that is not what Kyle is actually asking. It's fairly obvious that he expects the question to be parsed as:

"Should the developers have access to the production environment, and if they do [should], to what extent?"

And sure enough, that's exactly how I parsed it when I first read it. As in, I didn't even blink at the "do" kicking out a modal verb. It was only upon reading the sentence for a third or fourth time that it struck me as odd. It should also be noted that Kyle is a native speaker. So the construction can't be that ungrammatical after all, does it? Must we correct Kyle, and if we don't, why?

Edit: some of the people who have answered/commented say that they do, in fact,
read Kyle's question as:

*

*Should the developers have access to the production environment?

*If they already have access, to what extent is it OK for them to have it?

It looks like I have to explain why this reading makes little sense — at which I only hinted above — even when no context whatsoever is provided (and Kyle's post is well over a thousand words long).
This interpretation means that if developers already have access, the first question doesn't apply. We will throw it away just for them. But the first question is universal, it must not be thrown away. It is more general, more important. If we come to the conclusion that developers, in general, should not have access to the production environment, it also applies to those developers who already do have access. In fact, it applies to them more than to anyone else.
So, Kyle cannot possibly be asking: "Should the developers have access to the production environment? Oh, and if your developers already have access, never mind, forget that question, let's just discuss how much access is okay." Much rather, he is asking: "Should the developers have access to the production environment? And if and only if the answer to that question is 'yes', how much access should they have?"

A: I'm trying to capture a vague thought flitting around in my head; apologies if the result is incomprehensible.
I think we accept the should-does construction because there are situations where "do" is the appropriate question word, even though the verb isn't (or doesn't appear to be) "do":

He loves hiking, doesn't he?

The affirmative of this is "He does love hiking" --> hence the "do" in the question.
So I think what happens is that our brain tries to autocorrect the non-parallel constructions by substituting "do" for the modal verb, and if the result is grammatical, we accept it.

Should Kyle be corrected, and if he doesn't, why?

"Kyle does be corrected" doesn't work, so the autocorrect fails.

Should the developers have access to the production environment, and if they do, to what extent?

"Do the developers have access" is perfectly reasonable grammatically, so we don't even blink at this unless someone points it out. [Note that the autocorrect only applies to the grammar: I interpreted this as Kyle intended, i.e. "should they have access, and if yes, to what extent?"]

So the construction can't be that ungrammatical after all, does it?

"Does be ungrammatical" - nope.

Must we correct Kyle, and if we don't, why?

"Don't correct Kyle" - sure, no problem.

Now we just need to wait for some pedant to come up with a suitable counterexample, and the whole house-of-cards theory will come crashing down... <grin>

A: I think this statement suffers in part from being able to be interpreted in more than one way.  I don't know the context in which it was said, but it is feasible that some or all of the developers already had access, and that access (or the extent of it) was being questioned:
"Should the developers have access to the production environment, and if they do, to what extent?"
Read as:
"Should the developers (even) have access to the production environment, and if (some of them already) do, to what extent (should they have it)?"
I'll admit that was not my initial reading of it, but it does make sense.  My initial reading of it was assuming no developers currently have access:
"Should the developers have access to the production environment, and if they do, to what extent?"
Read as (simplest interpretation/better restatement of intent):
"Should the developers have access to the production environment, and, if so, to what extent should they have access?"
However, what I think is implied by the way it is phrased is:
"Should the developers have access to the production environment, and if they do (at some future point have access because we have decided they should and have given them access), to what extent (should they have access)?"
I think it is the shift in time from now to a later point that causes most of the confusion because both points are referred to with present tense verbs.  If you assume no developers currently have access to production, the statement is asking in the present if they should.  Then, in the same breath, the statement is referring to a future point when they have access or might have access also in the present.  I don't think it's technically incorrect, but much of the meaning has to be inferred since it relies on the reader to supply the missing words that could have provided clarification.

A: Compare the sentence with

(?) If the developers should have access to the production environment, they should have limited access.

If already introduce a conditional sentence, and should is not necessary.
The sentence should be written as

If the developers have access to the production environment, they should have limited access.

I interpret the sentence you wrote as

Should the developers have access to the production environment, and if they do [have access to the production environment], to what extent [is it okay for them to have it]?

In the first part of the question asks if developers should have access to production environment; the second part takes the assumption the developers have already access to the production environment, and asks to which extension should the access be allowed.

A: I think the problem with this sentence is that, unlike many present tense verbs, "have access" can't be used for the future. For example, if the sentence was

Should the developers go to the meetings, and if they do, should they have a vote?

then the implied "do go" fits the future fine.
But "have" is exceptional; you can't use the present tense of "have" in the future; it's replaced by "get". For instance, "tomorrow I go to school" is fine, but "tomorrow I have a car" is not; you should say "tomorrow I will have a car" or "tomorrow I get a car".
The question becomes whether the "do" permits the sentence to shift into the future, even though present tense "have" isn't used for future events. If it does, then the expanded sentence is really something like

Should the developers have access to the production environment, and if they get access, to what extent?

If it doesn't, you would have to use "should" or "will" instead of "do". From people's reactions to this question, it seems many people think this shift is grammatically implied by the "do". However, replacing "do" by "should" is clearly the better option.


text:
Q: Most significant input dimensions for GPy.GPCoregionalizedRegression? I have trained successfully a multi-output Gaussian Process model using an GPy.models.GPCoregionalizedRegression model of the GPy package. The model has ~25 inputs and 6 outputs.
The underlying kernel is an GPy.util.multioutput.ICM kernel consisting of an RationalQuadratic kernel GPy.kern.RatQuad and the GPy.kern.Coregionalize Kernel.
I am now interested in the feature importance on each individual output. The RatQuad kernel provides an ARD=True (Automatic Relevance Determination) keyword, which allows to get the feature importance of its output for a single output model (which is also exploited by the get_most_significant_input_dimension() method of the GPy model).
However, calling the get_most_significant_input_dimension() method on the GPy.models.GPCoregionalizedRegression model gives me a list of indices I assume to be the most significant inputs somehow for all outputs.
How can I calculate/obtain the lengthscale values or most significant features for each individual output of the model?

A: The problem is the model itself. The intrinsic coregionalized model (ICM) is set up such, that all outputs are determined by a shared underlying "latent" Gaussian Process. Thus, calling get_most_significant_input_dimension() on a GPy.models.GPCoregionalizationRegression model can only give you one set of input dimensions significant to all outputs together.
The solution is to use a GPy.util.multioutput.LCM model kernel, which is defined as a sum of ICM kernels with a list of individual (latent) GP kernels. It works as follows
import GPy

# Your data
# x = ...
# y = ...

# # ICM case
# kernel = GPy.util.multioutput.ICM(input_dim=x.shape[1],
#                                   num_outputs=y.shape[1],
#                                   kernel=GPy.kern.RatQuad(input_dim=x.shape[1], ARD=True))

# LCM case
k_list = [GPy.kern.RatQuad(input_dim=x.shape[1], ARD=True) for _ in range(y.shape[1])]
kernel = GPy.util.multioutput.LCM(input_dim=x.shape[1], num_outputs=y.shape[1],
                                              W_rank=rank, kernels_list=k_list)

A reshaping is of the data is needed (This is also necessary for the ICM model and thus independent of the scope of this questions, see here for details)
# Reshaping data to fit GPCoregionalizedRegression
xx = reshape_for_coregionalized_regression(x)
yy = reshape_for_coregionalized_reshaping(y)

m = GPy.models.GPCoregionalizedRegression(xx, yy, kernel=kernel)
m.optimize()

After converged optimization one can call get_most_significant_input_dimension() on an individual latent GPs (here output 0).
sig_inputs_0 = m.sum.ICM0.get_most_significant_input_dimensions()

or looping over all kernels
sig_inputs = []
for part in self.gpy_model.kern.parts:
    sig_inputs.append(part.get_most_significant_input_dimensions())


text:
Q: Why does SQL-Server save duplicate data for a single entry? I've developed a CRUD based web application in php. It's a form whose input data gets saved in a sql server database.
Even when the user fills it once, the database is saving multiple entries for it.
The problem is in the database it seems as the form gets submitted successfully.
Can anyone help?
Thanks
Here's the code:
<?php
ob_start();
require_once 'db-connect.php';
require_once 'email.php';

if(isset($_POST['pEmail'])){
    $fName = filter_input(INPUT_POST, "fName") ? filter_input(INPUT_POST, 'fName') : null;
    $lName = filter_input(INPUT_POST, "lName")? filter_input(INPUT_POST, 'lName') : null;
    $mName = filter_input(INPUT_POST, "mName")? filter_input(INPUT_POST, 'mName') : null;
    $tempRace = filter_input(INPUT_POST, "race", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $race = (is_array($tempRace)) ? implode(',', $tempRace) : null;
    $hEthnicity = filter_input(INPUT_POST, "hEthnicity") ? filter_input(INPUT_POST, 'hEthnicity') : null;
    $gender = filter_input(INPUT_POST, "gender") ? filter_input(INPUT_POST, 'gender') : null;
    $age = filter_input(INPUT_POST, "age") ? filter_input(INPUT_POST, 'age') : null;
    $education = filter_input(INPUT_POST, "education") ? filter_input(INPUT_POST, 'education') : null;
    $gpa = filter_input(INPUT_POST, "gpa") ? filter_input(INPUT_POST, 'gpa') : null;
    $hPhone = filter_input(INPUT_POST, "hPhone") ? filter_input(INPUT_POST, 'hPhone') : null;
    $cPhone = filter_input(INPUT_POST, "cPhone") ? filter_input(INPUT_POST, 'cPhone') : null;
    $pEmail = filter_input(INPUT_POST, "pEmail") ? filter_input(INPUT_POST, 'pEmail') : null;
    $aEmail = filter_input(INPUT_POST, "aEmail") ? filter_input(INPUT_POST, 'aEmail') : null;
    $inputAddress = filter_input(INPUT_POST, "inputAddress") ? filter_input(INPUT_POST, 'inputAddress') : null;
    $inputCity = filter_input(INPUT_POST, "inputCity") ? filter_input(INPUT_POST, 'inputCity') : null;

    $conn = DB::databaseConnection();
    $conn->beginTransaction();
    $sql = "INSERT INTO dbo.premedical ( FName,LName, MidInitial, Race, Ethnicity, Gender, Age, SchoolYear, Gpa, HPhone, CPhone, PEmail, AEmail, MailAddress, MailCity) VALUES
            ( :fName,:lName, :mName, :race, :hEthnicity, :gender,:age, :education, :gpa, :hPhone, :cPhone, :pEmail, :aEmail, :inputAddress, :inputCity)";

    $q = $conn->prepare($sql);
    $q->execute(array($fName,  $lName, $mName, $race, $hEthnicity, $gender, $age,   $education, $gpa, $hPhone, $cPhone, $pEmail, $aEmail, $inputAddress, $inputCity));

    if ($q->execute()) {
        $conn->commit();

        if (Form::mailer($fName,  $lName, $mName, $race, $hEthnicity, $gender, $age,   $education, $gpa, $hPhone, $cPhone, $pEmail, $aEmail, $inputAddress, $inputCity)) {
            echo '
            <script >
                alert("Thank you for registration.");
            </script>';
        }

        return true;
    } else {
        echo '
        <script>
            alert("Error, please try submitting again. Error code 1");
            window.history.back();
        </script>';
    }
}
?>

A: Calling $q->execute fires off the execute procedure, even if you're using it in a logic check - so it's executing twice. You should update it to something like:
<?php
ob_start();
require_once 'db-connect.php';
require_once 'email.php';

if(isset($_POST['pEmail'])){
    $fName = filter_input(INPUT_POST, "fName") ? filter_input(INPUT_POST, 'fName') : null;
    $lName = filter_input(INPUT_POST, "lName")? filter_input(INPUT_POST, 'lName') : null;
    $mName = filter_input(INPUT_POST, "mName")? filter_input(INPUT_POST, 'mName') : null;
    $tempRace = filter_input(INPUT_POST, "race", FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);
    $race = (is_array($tempRace)) ? implode(',', $tempRace) : null;
    $hEthnicity = filter_input(INPUT_POST, "hEthnicity") ? filter_input(INPUT_POST, 'hEthnicity') : null;
    $gender = filter_input(INPUT_POST, "gender") ? filter_input(INPUT_POST, 'gender') : null;
    $age = filter_input(INPUT_POST, "age") ? filter_input(INPUT_POST, 'age') : null;
    $education = filter_input(INPUT_POST, "education") ? filter_input(INPUT_POST, 'education') : null;
    $gpa = filter_input(INPUT_POST, "gpa") ? filter_input(INPUT_POST, 'gpa') : null;
    $hPhone = filter_input(INPUT_POST, "hPhone") ? filter_input(INPUT_POST, 'hPhone') : null;
    $cPhone = filter_input(INPUT_POST, "cPhone") ? filter_input(INPUT_POST, 'cPhone') : null;
    $pEmail = filter_input(INPUT_POST, "pEmail") ? filter_input(INPUT_POST, 'pEmail') : null;
    $aEmail = filter_input(INPUT_POST, "aEmail") ? filter_input(INPUT_POST, 'aEmail') : null;
    $inputAddress = filter_input(INPUT_POST, "inputAddress") ? filter_input(INPUT_POST, 'inputAddress') : null;
    $inputCity = filter_input(INPUT_POST, "inputCity") ? filter_input(INPUT_POST, 'inputCity') : null;

    $conn = DB::databaseConnection();
    $conn->beginTransaction();
    $sql = "INSERT INTO dbo.premedical ( FName,LName, MidInitial, Race, Ethnicity, Gender, Age, SchoolYear, Gpa, HPhone, CPhone, PEmail, AEmail, MailAddress, MailCity) VALUES
            ( :fName,:lName, :mName, :race, :hEthnicity, :gender,:age, :education, :gpa, :hPhone, :cPhone, :pEmail, :aEmail, :inputAddress, :inputCity)";

    $q = $conn->prepare($sql);
    $result = $q->execute(array($fName,  $lName, $mName, $race, $hEthnicity, $gender, $age,   $education, $gpa, $hPhone, $cPhone, $pEmail, $aEmail, $inputAddress, $inputCity));

    if ($result) {
        $conn->commit();

        if (Form::mailer($fName,  $lName, $mName, $race, $hEthnicity, $gender, $age,   $education, $gpa, $hPhone, $cPhone, $pEmail, $aEmail, $inputAddress, $inputCity)) {
            echo '
            <script >
                alert("Thank you for registration.");
            </script>';
        }

        return true;
    } else {
        echo '
        <script>
            alert("Error, please try submitting again. Error code 1");
            window.history.back();
        </script>';
    }
}
?>


text:
Q: Inserting multiple rows from an array of arrays in postgreSQL where arrayA[0] =>arrayB[arr1[]], arrayA[1]=>arrayB[arr2[]] I have this scenario I wish to implement using the query directly in postgresql.
I have user inputs in an array and the size of these arrays can vary. A sample user input is given below:
arrayA=[1,2,3];
arrayB=[[11,22,33],[12,23,34],[4,5,6]];
In the table I need to insert the above data in the following manner
Table A
id dataA dataB
1    1     11
2    1     22
3    1     33
4    2     12
5    2     23
6    2     34
7    3     4
8    3     5
9    3     6

I have tried using unnest() but I'm not able to get the output I want. I'm not sure how to use it to get the required output or if it is the right way to use it. Can someone please help me with this!!

A: This is a bit tricky due to the two dimensional array, but the following works with your two sample arrays:
select row_number() over (order by a.idx, b.idx) as id,
       a.data_a,
       b.data_b
from unnest(array[1,2,3]) with ordinality as a(data_a, idx)
  cross join lateral unnest( (array[ [11,22,33], [12,23,34], [4,5,6]])[a.idx:a.idx][1:]) with ordinality as b(data_b,idx);

Online example


text:
Q: Browserify requiring variable is undefined I recently upgraded a whole frontend TypeScript project to use modules (import/export). I'm using browserify with tsify to compile it. However, the outputted bundle.js file is unable to run, giving me the error:
Uncaught TypeError: Cannot read property 'myvariable ' of undefined

myvariable is loaded through:
import { myvariable } from './globalvars';

And in globalvars it's defined as:
export let myvariable = 'hello world!';

Logging out myvariable is gived undefined, and logging out just the require statement just logs
{__esmodule: true }

I tried switching the whole project to CommonJS, so using require() and module.exports(), but I get the exact same issue.
THEN I tried using Webpack, used a typescript config and that is also unrunnable.
I also tried piping the sources through babel before bundling, same issue.
Here is the gulp task I wrote for compiling:
gulp.task('compile-scripts', function (finished) {
    console.log('Compiling scripts.');
    browserify({
            standalone: 'main'
        })
        .add('src/scripts/scriptloader.ts')
        .plugin("tsify", {
            noImplicitAny: false,
            module: 'CommonJS'
        })
        .transform(babelify)
        .bundle()
        .pipe(source('bundle.js'))
        .pipe(gulp.dest('debug/js')).on('end', function () {
            finished();
        });
});

Am I doing something wrong here? I've spent two days on this and am quite frustrated. Thanks!


text:
Q: SQL database design - manage read and write user permissions on an entity I would like to enforce user permission to read and write folder and file entities.
By read I mean SELECT and by write I mean INSERT or UPDATE.
I'm not sure how to model this,and would like to learn what is the appropriate way to achieve the requirements as follow:
A company should have (or not) permission to read folders and the files related to it.
A user should have (or not) permission to read the folder his company has permission on and have (or not) permission to write file.
Meaning reading is a permission in a company scale and writing is a permission in a user scale.

EDIT
The issue I'm struggling with is the hierarchy of folder and file.
By the current requirements I can manage the permissions in the application level so that the security doesn't have to be in the database level, but if so, as far as I understand I'll need to add more information to the tables - columns or junction table for readers and writers.

*

*What is the appropriate way - security on the database or app level?

*If on the app level, what adjustments should be made in the design to handle the hierarchy?

These are the entities I currently have:
 CREATE TABLE "company" (
                "id" SERIAL PRIMARY KEY NOT NULL,
                "name" varchar (50) NOT NULL
            )

 CREATE TABLE "user" (
                "id" SERIAL PRIMARY KEY NOT NULL,
                "company_id" integer NOT NULL REFERENCES "company"(id),
                "full_name" varchar (50) NOT NULL,
                "email" varchar (50) UNIQUE NOT NULL,
                "password_hash" varchar NOT NULL
            )

 CREATE TABLE "project" (
                "id" SERIAL PRIMARY KEY NOT NULL,
                "name" varchar (50) NOT NULL
             )

 CREATE TABLE "folder" (
                "id" SERIAL PRIMARY KEY NOT NULL,
                "name" varchar (50) NOT NULL,
                "project_id" NOT NULL REFERENCES "project"(id)
             )
 CREATE TABLE "file" (
                "id" SERIAL PRIMARY KEY NOT NULL,
                "name" varchar (50) NOT NULL,
                "folder_id" NOT NULL REFERENCES "folder"(id)
             )

 CREATE TABLE "project_company" (
                "id" SERIAL NOT NULL,
                "project_id" integer NOT NULL REFERENCES "project"(id),
                "company_id" integer NOT NULL REFERENCES "company"(id),
                 PRIMARY KEY (project_id, company_id)
             )


text:
Q: How to start jboss7.1.1 server in windows 8 64 bit? How to start the jboss server ? i have seen documentation says standard.bat and domain.bat. I'm getting confusing , Please advise which .bat to start the server and need to deploy the jbpm project.

A: First Edit the service.bat. Then go ahead with the following instructions:

*

*JBoss includes a batch file named `standalone.bat` (in the bin folder) that will start the JBoss AS. Please ensure that this script will run JBoss as you like.

* Start AlwaysUp.

*Select Application > Add to open the Add Application window

*On the General tab:

*

*In the Application field, enter the full path to the standalone.bat
    file (C:\JBoss\bin\standalone.bat for us).

*In the Name field, enter the name that you will call the application
   in AlwaysUp.

*If the target PC is dedicated to running JBoss, boost the server's priority to ensure that Windows will grant  it the maximum amount of resources on the host PC.

* On the LogOn tab:

*
* Enter the user name and password of the account in which you setup JBoss AS.

*  If you wish to hide the DOS/command window that comes up when you run JBoss from the batch file (recommended), check the When a user logs on, don't show the application's windows and tray icons (if any) box at the bottom.

*Click over to the Startup tab and check the Ensure that the Windows Networking components have started box. This informs AlwaysUp that JBoss needs the TCP/IP networking stack to operate.

*Click over to the Extras tab. If you wish to capture the text normally displayed on the command window created by standalone.bat (recommended), check the Capture output to this log file box and specify the full path to a file. We have specified C:\JBoss\jboss-log.txt.

*Click the Save >> button. In a couple of seconds, an application called JBoss will show up in the AlwaysUp window. It is not yet running though.

*To start JBoss, choose Application > Start "JBoss".

That's it you are done!
Ref# Link

A: To put it simple, Standalone.bat is cases where you don't use clusters. Domain.bat in case of clusters.
My guess is, in your case standalone.bat should be good enough.


text:
Q: How do I find the area of the shaded region between $y=3x^2$ and $y=24-6x$?
So first off, I know that I have:
$y=3x^2$ and $y=24-6x$
Do I first set these equations equal to each other? If so, then I get:
$(3x^2)+6x-24=0$.
Therefore, I would get $x=-4$ or $x=-2$
Is this correct so far?
If so, then I know I would put these numbers over and below the integral symbol.
If all of this is correct so far, then my biggest question is this; How do I know which numbers to put above and below the integral symbol, and how do I know what equation to put into the integral function part, in order to take the anti derivative and find the area?
Disclaimer: I am new to this online community, and so if you see something in my question/post that should not belong, or that you do not like, please tell me before down-voting my post. I am not trying to get someone to strictly do homework for me. I am trying to learn so that I can replicate it on similar problems. I want to be respectful. My class is online, so asking specific questions in class is a challenge, as there are no interactive lectures.

A: You didn't solve the quadratic equation correctly: $3x^2=24-6x$ gives you $x=-4$ or $x=2$. Then you can check that the two curves meet at $(2,12)$.
In general, the definite integral $\int_a^b f(x)\ dx$ gives you the area of the region under the curve provided by $y=f(x)$. Here, you have $a=0$, $b=4$ and
$$
f(x)=
\begin{cases}
3x^2,& 0\leqslant x\leqslant 2,\\
24-6x, & 2\leqslant x\leqslant 4.
\end{cases}
$$
Remember that integration is "additive":
$$
\int_{a}^bf(x)\ dx = \int_a^cf(x)\ dx+\int_c^bf(x)\ dx.
$$
Here you have $c=2$.

A: We already know that area of a rectangle is the product of it's sides. Now using the same approach we draw two stripes of Differential (infinitesimally small) thickness $dx$ and $dy$. Look at the below image (please excuse the bad image quality).

Now as you can see in the picture there is a mini rectangle formed by the intersection of those stripes and the dimensions of the rectangle is $dx$ and $dy$. Hence we can the area of the differential rectangle is $dA=dxdy$. So now we the area of the differential rectangle also called the differential area and all we have to do is move the strips from one extreme (limit) to the other so that we can get the area of all other rectangles and add them.
Because we are moving both the strips and we have two differential lengths $dx$ and $dy$, we have to do double integration to integrate the area by one strip ($dx$) from left to right and the other strip ($dy$) from down to top. Hence we have :
$A=\begin{align*}\int_{x_{1}}^{x_{2}}\int_{y_{1}}^{y_{2}}dA \end{align*}$
Now all we have to do is figure out the limits. As mentioned by @user587192 your point of cutoff is $(2,12)$. The function varies for different $x$. So we cannot apply the above formulae directly as the function $y$ changes after a certain $x$. Hence we break it off at $c=2$.
$A=\begin{align*}\int_{x_{1}}^{x_{2}}\int_{y_{1}}^{y_{2}}dA =\int_{x_{1}}^{c}\int_{y_{1}}^{y_{2a}}dA + \int_{c}^{x_{2}}\int_{y_{1}}^{y_{2b}}dA \end{align*}$
$y_{2a}$ and $y_{2b}$ are different functions before and after the breakoff point $c$. So finally it becomes-
$A=\begin{align*}\int_{0}^{2}\int_{0}^{3x^2}dydx + \int_{2}^{4}\int_{0}^{24-6x}dydx \end{align*}$
Which ultimately becomes-
$A=\begin{align*}\int_{0}^{2}3x^{2}dx + \int_{2}^{4}(24-6x)dx. \end{align*}$
I hope you understand it better now.


text:
Q: How to display custom Post in WordPress? I am not sure how to use custom posts in Wordpress. I have tried them with the plugin's but, the problem here is when I have deactivated plugins which are not useful then the related posts are going down. I want to make them available. Is there any easy way to post them?

A: You can add custom post type in WordPress by placing this in you theme functions file, you can also place this in must use plugin to for using it in all themes.
function register_custom_post_type()
{
    register_post_type(
        'team',
        array(
            'supports'      => array(
                'title',
                'editor',
                'author',
            ),
            'taxonomies'          => array(
                'category',
            ),
            'labels'      => array(
                'name'          => __('Team', 'Our Team'),
                'singular_name' => __('Team', 'Our Team'),
                'menu_name'           => __('Team', 'Our Team'),
                'all_items'           => __('All Team Members', 'Our Team'),
                'view_item'           => __('View Team Member', 'Our Team'),
                'add_new_item'        => __('Add New Member', 'Our Team'),
                'add_new'             => __('Add New', 'Our Team'),
                'edit_item'           => __('Edit Member', 'Our Team'),
                'update_item'         => __('Update Member', 'Our Team'),
                'search_items'        => __('Search Member', 'Our Team'),
                'not_found'           => __('Not Found', 'Our Team'),
                'not_found_in_trash'  => __('Not found in Trash', 'Our Team'),
            ),
            'public'      => true,
            'has_archive' => true,

        )
    );
}
add_action('init', 'register_custom_post_type');

In view use the normal WordPress loop, just add this to your arguments,
$args = array(
  'post_type'   => 'team',
  'post_status' => 'publish'
 );

$team= new WP_Query( $args );

A: The problem with using a plugin is that your custom post types will disappear when the plugin is deactivated. Any data you have in those custom post types will still be there ,but your custom type will be unregistered and will not be accessible from the admin area.
You can use below code for the custom posts:
$args = array( 'post_type' => 'blog', 'post_per_page ' => 10 ); $loop = new WP_Query(args ); While ( $loop-> have_posts() ): $loop->the_post(); the_title(); echo'<div class = " entry-content " >'; the_content(); echo''; endwhile;
Reference :
https://www.wpbeginner.com/wp-tutorials/how-to-create-custom-post-types-in-wordpress/


text:
Q: How do you evaluate an exponential term that contains both $-\infty$ and $+\infty$? What does $\int_{0}^{\infty} e^{y(iu-\alpha)}dy = ?$ Please note $i$ is a complex variable, $\alpha$ and $u $ are constants.
I know this integral evaluates to:
$$\left.\frac{e^{y(iu-\alpha)}}{iu-\alpha}\right|_0^\infty$$
I'm unsure how this evaluates due to the terms inside the parenthesis of the exponetial for which $\infty$ will have to be distributed to.  So you end up with a $-\infty$ and $+\infty$ term inside that exponential, which is throwing me off.  How do you evaluate and make sense out of this?

A: I am assuming that
$\alpha$ is real.
Write
$e^{y(iu-\alpha)}
=e^{iuy}e^{-y\alpha}
$.
If $\alpha>0$,
$e^{-y\alpha}
\to 0
$,
so the limit at
$\infty$
is $0$.
If $\alpha=0$,
$e^{iuy}
=\cos(uy)+i\sin(uy)
$
oscillates as
$y \to \infty$,
so the limit does not exist.
If $\alpha < 0$,
it blows up as
$y \to \infty$.


text:
Q: Find sum of real roots of the equation $\sqrt{8-x}=x-2$
Solve the equation $\sqrt{8-x}=x-2.$

I got the answer to the question as $x= -1$ or $x= 4$. However, the answer key says the actual answer to the question is $4$ only. What am I missing here?

A: Using the fact that $\sqrt{x^2}=|x|$ where | . | refers to the absolute value, we can apply this to your specific problem to see that:

*

*$\sqrt{9}=\sqrt{3^2}=|3|=3$
or

*

*$\sqrt{9}=\sqrt{(-3)^2}=|-3|=3$
Therefore, since $\sqrt{9}\neq-3$, we conclude that $x=-1$ cannot be a valid solution, and so the correct answer is only $x=4$, as stated in your answer.

A:
While it is commonplace to solve an equation such as $ \ \sqrt{8 - x} \ = \ x - 2 \ $ by first "squaring" both sides, it should be understood that this has the effect of altering the properties of the functions represented on each side of the equation.  The curve for the function $ \ y \ = \ x - 2 \ $ (blue curve in graph at left) is a straight line which does not enter the second quadrant, so there is no negative value of $ \ x \ $ that can produce a positive value for $ \ y \ \ . $  The curve (in red) for $ \ y \ = \ \sqrt{8 - x} \ \ , $  on the other hand, can only produce positive values of $ \ y \ $ for $ \ x \ < \ 8 \ \ , $ as square-roots of positive real numbers are only defined to be positive.  So the properties of these functions tell us that there can be no intersection of their curves for $ \ x \ < \ 0 \ \ . $
The act of "squaring" the functions (which enables the solution $ \ (x - 2)^2 \ = \ x^2 - 4x + 4 \ = \ 8 - x $ $ \Rightarrow \ x^2 - 3x - 4 \ = \ (x - 4)·(x + 1) \ = \ 0 \ ) \ $ alters ("transforms") the straight line function into an "upward-opening" parabola with its vertex at $ \ (2 \ , \ 0 ) \ $ and its $ \ y-$intercept at $ \ (0 \ , \ 4) \ \ , $ so that its function curve (green in the graph at right) now extends into the second quadrant, permitting it to intersect with the straight line (orange) for $ \ (\sqrt{8 - x})^2 \ \ . $  This intersection at $ \ (-1 \ , \ 9) \ $ is then an artifact ("spurious solution") of the "squaring" transformation: any negative-value solution for $ \ x \ $ is already "rejected" for the original functions.

A: To solve you need to square the given equation.
When you square the right side you get same result for x -2 and 2 - x , therefore you get solutions for both cases. This is why you need to avoid squaring of equations when you are solving. But if there is no other option you can square but you have to check validity of your solutions by substituting those to the original equation.


text:
Q: Remove file from plupload queue? I am  trying to limit the file extensions that can uploaded through plupload.
because the filters do not work properly with the HTML5 runtime I cannot use them. hence I have the below code binded to the FilesAdded event
var extensionArray = ['pdf', 'doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx'];
uploader.bind('FilesAdded', function (up, files) {
    var invalid = 0;
    for (var i in files) {
        var extension = files[i].name
                                .substr((files[i].name.lastIndexOf('.') + 1))
                                .toLowerCase();

        if (extension == '' || -1 === $.inArray(extension, extensionArray)) {
            uploader.splice(i, 1); //also tried uploader.removeFile(files[i])
            invalid++;
            continue;
        }
        //dom manipulation to add file occurs here
    }
});

But, whilst this is stopping the dom manipulation occuring for any invalid files, it does not seem to be actually removing the item from the queue as when I initiate the upload they are all sent across!
This is happening on both the HTML5 and the Flash Runtime. I have not tested the others yet.
Binding to the FilesRemoved event, it is never triggered! but inserting console.log('Invalid files detected'); just before uploader.splice(... it is outputted to the console, so that line is getting called.

A: Short Version: You need to bind to the filesAdded event after calling the init() function.
my first step for debugging was to grab the uncompressed version off github18 Nov 2012. Once I had that I could trace the issue.
So the primary issue seemed to be that the call to removeFile() was never getting called, but why?
removeFile() was defined as:
removeFile: function (file) {
    var i;

    for (i = files.length - 1; i >= 0; i--) {
        if (files[i].id === file.id) {
            return this.splice(i, 1)[0];
        }
    }
}

Ok, pretty simple, this loops through the files array and if there is a file that has the matching ID then we call the splice function.
So, what does splice look like?
splice() was defined as:
splice:function (start, length) {
    var removed;

    // Splice and trigger events
    removed = files.splice(start === undef ? 0 : start, length === undef ? files.length : length);

    this.trigger("FilesRemoved", removed);
    this.trigger("QueueChanged");

    return removed;
}

Right, so that is where the FilesRemoved event should have been triggered, so why wasn't it?
Back in the removeFile() function, as noted, it only calls splice if a matching id is found.
So, the next step was to find out if the removeFile function was even being called.
Inserting console.log('removeFile called', files); as the first line gave us the output:   removeFile called []
Hmmm, an empty array!
Ok then, Looks like us binding to the FilesAdded event is stopping it's usual behavior, no problem. let's just add uploader.files.push(file) to our FilesAdded binding. and lo and behold. when we click start, only the correct files are sent.
It's working... but not quite.
I had a couple of extra bindings in there, just for debugging purposes, one of those was on QueueChanged. this logged the amount of files in the queue each time there was a change.
What I noticed was that the number of files in the queue was not actually reflecting that there was files removed from the queue.
So, a quick console.log(uploader.files.length) and this confirmed that there was something else going on here.
Next step was to look at what the default action was for adding files.
Looking I noticed that the developers decided to bind to the event as well, doing this inside the init function. An odd choice looking at it from my perspective. But that's their choice.
So, looking inside their binding they also had a files.push(file) meaning that we were getting all files + duplicates of the correct files in the array.
Noting that the binding was happening in the init(), function, I removed the uploader.files.push(file) from my binding, moved the init() call to before my FilesAdded binding. and now everything works well.

A: uploader=newplupload.Uploader({
//-----
});

uploader.bind('FilesAdded',function(up,files)
{
//----
up.refresh();//RepositionFlash/Silverlight
});

uploader.bind('QueueChanged',function(up,files){

//#doc-filelist is the id of dive, which shows the Queue
$('#doc-filelist').html('');

$.each(uploader.files,function(i,file){
$('#doc-filelist').append(
'
'+
file.name+'('+plupload.formatSize(file.size)+')'+
'<spanclass="remove_file"data-file="'+i+'">X'+
'
');
});

if(uploader.files.length==0){
 // #uploadfiles button for start upload
$('#uploadfiles').addClass('disabled');
}

});

 uploader.bind('UploadComplete', function (up, file) {
    up.splice();
    up.refresh();

});

$('.relevant-document').on('click','.remove_file',function(e){

uploader.splice($(this).attr('data-file'),1);

uploader.refresh();
});