text:
Q: TypeError when calling socket.connect(...) I keep getting an error while running a relatively simple TCP client. The troublesome line is the call to socket.connect(..) which looks to through a TypeError. Any ideas why? I've put in hard coded values for now for host and port for now.
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 846, in emit
    msg = self.format(record)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 723, in format
    return fmt.format(record)
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 464, in format
    record.message = record.getMessage()
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 328, in getMessage
    msg = msg % self.args
TypeError: not all arguments converted during string formatting
Logged from file run_42bets.py, line 70

# ------

#!/usr/bin/python

import importlib
import logging
import optparse
import os
import socket

SCRIPT_NAME = os.path.basename(__file__)
VERSION = SCRIPT_NAME + ' 1.0'

class TCPCommandSender:
    """Wrapper around TCP client for sending commands"""
    def __init__(self, host, port):
        """Setup connection to host:port"""
        logging.info("Connecting to server %s:%s", host, port)

        self.__host = host
        self.__port = port

        self.__socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.__socket.connect(("127.0.0.1", 2000))

    def __enter__(self):
        """Return TCPCommandSender instance"""
        return TCPCommandSender

    def __exit__(self, type, value, traceback):
        """Tear down connection if connected"""
        if self.__socket:
           logging.info("Disconnecting from server %s:%s", self.__host, self.__port)
           self.__socket.close()

    def send(self, cmd):
        """Send admin command to server and return received message"""
        try:
            self.__socket.sendall(cmd)
            return self.__socket.recv(1024)
        except socket.error, msg:
            logging.critical("Failed to send admin cmd; reason=%s", msg)
            return "ERROR"

def main():
    #customise logging
    logging.basicConfig(filename=SCRIPT_NAME + '.log',
                        filemode='a',
                        format='%(asctime)s %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        level=logging.INFO)

    logging.info("Starting %s", SCRIPT_NAME)

    #define command line arguments
    parser = optparse.OptionParser("Usage: %prog [options]", version=VERSION)
    parser.add_option('--host', dest='host', help='Server to send commands to', type='string')
    parser.add_option('--port', dest='port', help='Server admin port to send commands to', type='int')
    parser.add_option('--config', dest='config', help='Python configuration module to configure algo', metavar='FILE')
    (options, args) = parser.parse_args()

    #check we have all required command line arguments
    if options.host and options.port and options.config:
        try:
            with TCPCommandSender(options.host, options.port) as cmd_sender:
                try:
                    logging.info("Running configuration module %s", options.config)
                    logging.info("Finished configuration module %s", options.config)
                except:
                    logging.critical("Error while running configuration module %s", options.config)
        except EnvironmentError, msg:
            logging.critical("Failed to connect to server %s:%s", options.host, options.port, msg)
    else:
        parser.error("Incorrect number/set of arguments provided, see --help")

    logging.info("Ending %s", SCRIPT_NAME)

if __name__ == "__main__":
    main()

A: Your problem is this line:
logging.critical("Failed to connect to server %s:%s", options.host, options.port, msg)

Python is complaining that you gave it three things to put into the string (options.host, options.port, and msg), but you only gave it two places to put them (only two %s).


text:
Q: Why does the following probability identity hold (probability of at least one sucess) Assume we have a coin, which has probability $p$ for showing heads. Why does it hold that
$$P(at ~least ~one ~head) = P(first ~flip ~is ~head) + P(second~flip~is~head)\cdot P(first~flip~is~tail) + P(third~flip~is~head)\cdot P(first~and~second~flip~is~tail)?$$
I know it would be simpler to write it as $1-P(no~tails)$, but I was wondering why this works? Do we need to assume independence of the single flips here?
Thanks in advance

A: Flipping 3 times a coin the sample space is the following
$$\Omega=\{TTT;HTT;THT;TTH;HHT;HTH;THH;HHH\}$$
The probability to get "at least one H" is
$$1-\mathbb{P}(TTT)=\mathbb{P}(HTT)+\mathbb{P}(THT)+\mathbb{P}(TTH)+\mathbb{P}(HHT)+\mathbb{P}(HTH)+\mathbb{P}(THH)+\mathbb{P}(HHH)$$
EDIT: your equation holds because it is only a different partition of the sample space
$$\underbrace{\mathbb{P}(HTT)+\mathbb{P}(HTH)+\mathbb{P}(HHT)+\mathbb{P}(HHH)}_{\text{=first flip H}}+\underbrace{\mathbb{P}(THT)+\mathbb{P}(THH)}_{\text{=First T, second H}}+\underbrace{\mathbb{P}(TTH)}_{\text{FIrst and Second T, third H}}$$

but this is wrong

I know it would be simpler to write it as $1−P(no tails)$

The correct one is
$$\mathbb{P}[\text{at least one H}]=1-\mathbb{P}[\text{no Heads}]$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to properly rewrite $.fn.position function I need to make default collision = "fit" everywhere instead of "flip". So I decided to rewrite the $.fn.position function. However, something breaks and it does not work: The  element does not move and no error is displayed. It just does nothing. I have no clue why. Here is what I wrote:
(function($) {
    var orig = $.fn.position;
    $.fn.position = function(options){
        if ( options ){if ( !options.collision ){
            options.collision = "fit";
        }}
        return orig.apply(this, options);
    }
})(jQuery);

Looks ok to me. If there is a better way to do it or how to fix this thing please help.
Thank you
EDIT:
I am an idiot. Gotta use arguments with the orig apply.:
(function($) {
    var orig = $.fn.position;
    $.fn.position = function(options){
        if ( options ){
            if ( !options.collision ){
                options.collision = "fit";
            }
        }
        return orig.apply(this, arguments);
    }
})(jQuery);

A: You are not defaulting the value when there's no options
(function($) {
    var orig = $.fn.position;
    $.fn.position = function(options){
        if (!options) {
             options = {collision: "fit"}
        }

        if ( !options.collision ){
            options.collision = "fit";
        }
        return orig.apply(this, options);
    }
})(jQuery);

A: It would be better to use extend method:
(function($) {
    var orig = $.fn.position;
    $.fn.position = function(options) {
       options = $.extend({collision: "fit"}, options);
       return orig.apply(this, options);
    }
})(jQuery);


text:
Q: How to interpret zero order correlation and higher order partial correlation? I have performed correlation analysis between y and seven different variables (x1,x2,x3,x4,x5,x6,x7). In some cases, result shows zero order correlation is positive and partial correlation is negative (for ex. y & x3). How can I explain this result? My results are:
control variables----------zero order corr (partial corr) between y & x1,x2.....x7
x2,x3,x4,x5,x6,x7----------y & x1 =   0.88 (0.41)
x1,x3,x4,x5,x6,x7----------y & x2 =   0.85 (0.08*)
x1,x2,x4,x5,x6,x7----------y & x3 =   0.77 (-0.19)
x1,x2,x3,x5,x6,x7----------y & x4 =   0.44 (0.23)
x1,x2,x3,x4,x6,x7----------y & x5 =   0.38 (-0.02*)
x1,x2,x3,x4,x5,x7----------y & x6 =  -0.23 (-0.13)
x1,x2,x3,x4,x5,x6----------y & x7 =  -0.57 (-0.19)

*

*indicates insignificant partial correlation.

Thank you.

A: Let me use your $y$ and $x_3$ values. If you look only at the direct effect of $x_3$ on $y$, you will see a strong positive correlation. However, this ignores the other variables that may/may-not be influencing $y$.
If you account for the other variables, you have to account for the influence those variables have on $y$ and on $x_3$. In this case, you see that $x_3$ actually has a negative relationship WHEN the effect of the other variables has been "partialled" out. Conceptually, if you take the residuals from predicting $y$ form everything by $x_3$ and the residuals from predicting $x_3$ with everything (but $y$, of course), these residuals have a negative correlation.
One additional way to think about this is from a causal perspective (so extreme caution must be taken in presenting such an interpretation). $x_3$ may have some influence on the other variables (often called multicollinearity in this context). From the causal perspective, this means if you change $x_3$, you change the other variables, too.  Now, when you model the TOTAL effects from $x_3$ on $y$, you have to account for the direct effect (which appears to be negative) and the indirect effect of $x_3$ influencing the other variables which in turn influence $y$. When you combine the negative direct impact with the indirect effects, you end up with an overall "positive" impact.
Hope this helps.


text:
Q: "has the same colour" vs "is the same colour" Am I right both sentences are correct and usable?

Andy's car has the same colour as Laura's car.
Andy's car is the same colour as Laura's car.

TIA

A:
[1] Andy's car has the same colour as Laura's car.
[2] Andy's car is the same colour as Laura's car.

[1] is not at all natural. We don't normally use the verb "have" to describe the colour of a car.
[2] is fine, though you can drop "car" from the comparative clause. Note that comparative clauses are normally obligatorily reduced in some way relative to the structure of main clauses.
We understand: Andy's car is x colour; Laura's car is y colour; x=y

A: Your first sentence is correct & formal.
But your second sentence is absolutely ok.
In your second sentence, you could also use a PP, 'of the same colour' instead of 'the same colour' :

"Andy's car is of the same colour as Laura's car."

You could omit the noun 'car' after 'Laura's' :

"Andy's car is of the same colour as Laura's."

(Laura's = Laura's car).


text:
Q: How can I understand if a logger exists in common logging? I use Common.Logging in my application and I created a separate logger to write some debug info.
I can retrieve my logger using
LogManager.GetLogger("MyCustomLogger");

However, if this logger is not found I get the root one. I wish that if the logger is not found, nothing will be logged. I cannot remove the root logger because of the structure of my application.
How can I achieve this behavious using Common.Logging?
The config is
<common>
    <logging>
      <factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4net1213">
        <!-- Common Logging assumes that log4net is initialized -->
        <arg key="configType" value="EXTERNAL"/>
      </factoryAdapter>
    </logging>
  </common>

  <log4net>
    <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log/debug.txt"/>
      <appendToFile value="true"/>
      <maximumFileSize value="10000KB"/>
      <rollingStyle value="Size"/>
      <maxSizeRollBackups value="5"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} [%t] %-5p %c - %m%n"/>
      </layout>
    </appender>

    <appender name="MyCustomLogAppender" type="log4net.Appender.RollingFileAppender">
      <file value="Log/queries.txt" />
      <appendToFile value="true" />
      <maximumFileSize value="50000KB" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d{yyyy-MM-dd HH:mm:ss.fff} [%t] %-5p %c - %m%n" />
      </layout>
    </appender>
    <!-- levels: DEBUG, INFO, WARN, ERROR, FATAL -->
    <root>
      <level value="DEBUG"/>
      <appender-ref ref="FileAppender"/>
    </root>

    <logger name="MyCustomLog" additivity="false">
      <level value="DEBUG" />
      <appender-ref ref="MyCustomLogAppender" />
    </logger>
  </log4net>

A: I got the same problem. I wanted to return if the specified logger was not configured.
The solution I found :
private static ILog _log;

protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{

    if (LogManager.Exists("MyCustomLoggerName") == null)
        return;

    if (_log == null)
        _log = LogManager.GetLogger("MyCustomLoggerName");

    ...
}

I couldn't declare private static readonly ILog _log = LogManager.GetLogger("MyCustomLoggerName"); because then LogManager.Exists("MyCustomLoggerName") returned something...
In the log4net.config file, I set additivity="false" for this logger.


text:
Q: Facebook SDK 4.0 - Composer Not Finding Repository I'm trying to download the facebook/php-sdk-v4 repository into my project, running the "php composer.phar update" command.
I recently added this to the require section of my composer.json file:
"facebook/php-sdk-v4": "4.0.*",
Upon running the update command, I am given the following error:
---> Your requirements could not be resolved to an installable set of packages.
      Problem 1
      - The requested package facebook/php-sdk-v4 1.0.0 could not be found.
It seems that I have set it up exactly according to the Facebook Graph API instructions as listed on this page:
https://developers.facebook.com/docs/php/gettingstarted/4.0.0
But... It's still unable to find the repository.
Does anybody know the name of the Facebook SDK 4.0 repository or see any reason why this process I am following isn't working?
Thanks for listening!


text:
Q: How to apply changes to two different input field with one function I'm creating a performance comparing widget in Angular. It will compare performance of this Calendar year with Previous Calendar Year and this Year-to-date with Previous Year-to-date. I'll take care of all those mathematics. I've created a stackblitz also. But let me explain the code also. I have created two dropdowns using simple HTML select and option tags. And I've one more component app-monthpicker. This is what I mean:

Both dropdowns are reading options from same array in typescript:
modes = ['Calendar Year', 'Year to date'];

And then there is a predefined range for each option.

*

*For Calendar year, range is '01-01-2020 to 12-31-2020';

*For Year-to-date, range is '01-01-2020 to 02-07-2020';

These ranges are set in app-monthpicker. Let them be hard-coded.
Now, both the dropdowns are bound with same variable. Here's the code:

Time selection widget

  Primary:

  <select [(ngModel)]="primaryMode" (change)="modeChangeHandler($event)">
    <option *ngFor="let mode of modes" [ngValue]="mode">{{mode}}</option>
  </select>

  <app-monthpicker></app-monthpicker>

  Secondary:

  <select [(ngModel)]="secondaryMode" (change)="modeChangeHandler($event)">
    <option *ngFor="let mode of modes" [ngValue]="mode">Previous {{mode}}</option>
  </select>

  <app-monthpicker></app-monthpicker>

and here's my method modeChangeHandler:
@ViewChild(MonthpickerComponent, {static: false}) monthpicker: MonthpickerComponent;

constructor() {}

ngOnInit(): void {
}

modeChangeHandler() {
    if (this.primaryMode === this.modes[0] || this.secondaryMode === this.modes[0]) {
        this.initCalendarYear();
    } else if (this.primaryMode === this.modes[1] || this.secondaryMode === this.modes[1]) {
        this.initYearToDate();
    } else {
      console.log("Default case");
    }
}

initCalendarYear() {
    this.monthpicker.startRange = '01-01-2020';
    this.monthpicker.endRange = '12-31-2020';
}

initYearToDate() {
    this.monthpicker.startRange = '01-01-2020';
    this.monthpicker.endRange = '02-07-2020';
}

My problem is that my Second dropdown is not changing the values even though they are bounded to same variables. It is still changing the range of above input field and not its own.

A: One possible solution is to use the Angular template syntax and Ids
I added #primary and #secondary to the monthPickers to specify which one was it and so I can reference them from the component and added an id to both the selectors, which I will use to identify the target of the event when triggered.

Time selection widget

        Primary:

        <select id="primarySelect" [(ngModel)]="primaryMode" (change)="modeChangeHandler($event)">
           <option *ngFor="let mode of modes" [ngValue]="mode">{{mode}}</option>
        </select>

        <app-monthpicker #primary></app-monthpicker>

        Secondary:

        <select id="secondarySelect" [(ngModel)]="secondaryMode" (change)="modeChangeHandler($event)">
           <option *ngFor="let mode of modes" [ngValue]="mode">Previous {{mode}}</option>
        </select>

        <app-monthpicker #secondary></app-monthpicker>

and on the component I made the following changes:
replaced the viewChild with:
 @ViewChild("primary", { static: true }) primaryMonthPicker: MonthpickerComponent;
 @ViewChild("secondary", { static: true }) secondaryMonthPicker: MonthpickerComponent;

and updated the event handler and functions called, passing the target id to identify which calendar to update.
 modeChangeHandler(event) {
    if (
      this.primaryMode === this.modes[0] ||
      this.secondaryMode === this.modes[0]
    ) {
      this.initCalendarYear(event.target.id);
    } else if (this.primaryMode === this.modes[1]) {
      this.initYearToDate(event.target.id);
    } else {
      console.log("Default case");
    }
  }

  initCalendarYear(target: string) {
    if (target === "primarySelect") {
      this.secondaryMonthPicker.startRange = "01-01-2020";
      this.primaryMonthPicker.endRange = "12-31-2020";
    } else if (target === "secondarySelect") {
      this.primaryMonthPicker.startRange = "01-01-2020";
      this.secondaryMonthPicker.endRange = "12-31-2020";
    }
  }

  initYearToDate(target: string) {
    if (target === "primarySelect") {
      this.primaryMonthPicker.startRange = "01-01-2020";
      this.primaryMonthPicker.endRange = "02-07-2020";
    } else if (target === "secondarySelect") {
      this.secondaryMonthPicker.startRange = "01-01-2020";
      this.secondaryMonthPicker.endRange = "02-07-2020";
    }
  }

Full example available @ StackBlitz


text:
Q: How to keep the parameters' values of the Animator when it attached GameObject became disable? When I disable a GameObject, I found all values inside the Animator become to default. So is any ways to keep them, or recover them after enabled the GameObject?
Or the only way can do this is manually save them?

A: Well, there is a way I found that can solve this problem without manually save each parameter.
Firstly, by using Animator.parameters (Documentation), we can get all parameters in the Animator. Note that it does not include the value.
Animator.parameters is an array of the classAnimatorControllerParameter, which includes a property called AnimatorControllerParameterType type, which is an enum:
public enum AnimatorControllerParameterType
{
    Float = 1,

    Int = 3,

    Bool = 4,

    Trigger = 9
}

So now, we can simply call the methods such as GetBool, GetFloat in a loop to get all the variable, then use another loop to set them  by calling the method such as SetBool and SetFloat


text:
Q: Program that will ask the user to enter size of the array, show all the values entered and tell if its positive or negative I have this assignment for tomorrow and I'm a beginner please help. Must be JOptionpane :O I was wondering if I can use if else statement in showmessagedialog. Error says incompatible types required: int ( for holder=holder + "\n" + aw[x];
Here's what I've done so far(SORRY I'M A BEGINNER PLS UNDERSTAND):
public static void main(String[] args) {
 String s;
 int size;
 int size2;
 int holder;
 s = JOptionPane.showInputDialog("Enter the size of the array");
 size = Integer.parseInt(s);
 String aw[]= new String[size];

 for (int x=0; x<=aw.length-1; x++){
     aw[x]=JOptionPane.showInputDialog("Enter value for array[" + x + "]");
     size2 = Integer.parseInt(aw[x]);
 }
    for (int x=0; x<=aw.length-1;x++)
    {
        holder=holder + "\n" + aw[x];

    }
JOptionPane.showMessageDialog(null, if (holder<0)  { holder + " is negative" }  else holder " is positive");

}

}'

A: holder is declared as an int, but in
holder=holder + "\n" + aw[x];

you try to assign it a String.

A: Use String to store your messge
String msg;
if (holder<0)
{
    msg = holder + " is negative";
}
else
{
     msg = holder " is positive";
}
JOptionPane.showMessageDialog(null,msg);

showMessageDialog function expects the second parameter to be String

A: Something you can not do:
1 Variable holder you declare is int type. It can not be used to do `+`` operation.
2 Two for -loop is not neccessary.
3 You forget to check whether the number entered is zero, you just have positive and negative logic.
4 When trying to use + opeartion for strings. Please use append method of StringBuilder.
Here is the code made based on the above 3 items.
 public static void main(String[] args) {
    String s;
    int size;
    int size2;
    int holder = 0;

    s = JOptionPane.showInputDialog("Enter the size of the array");
    size = Integer.parseInt(s);
    String aw[] = new String[size];

    StringBuilder sb = new StringBuilder();
    for (int x = 0; x <= aw.length - 1; x++) {
        aw[x] = JOptionPane.showInputDialog("Enter value for array[" + x
                + "]");
        size2 = Integer.parseInt(aw[x]);

        if(size2 ==0)
        {
            sb.append(aw[x]).append(" is zero").append('\n');
        }else if(size2 >0)
        {
            sb.append(aw[x]).append(" is positive").append('\n');
        }else
        {
            sb.append(aw[x]).append(" is negative").append('\n');
        }
    }
    JOptionPane.showMessageDialog(null, sb.toString());

  }

A: The best approach is:
final String msg = holder == 0 ? "is zero" : (holder > 0 ? "is positive" : "is negative");
JOptionPane.showMessageDialog(null,msg);


text:
Q: If $A\subseteq B$ then $\cup A\subseteq \cup B$ If $A\subseteq B$ then $\cup A\subseteq \cup B$
My try:
If $x\in \cup A$ if there is $C \in A$ such that $x\in C$
Using the hypothesis: $A\subseteq B$,
$C\in B$ then
$x\in B$ then
$x\in \cup B$

A: To prove this, you just need to work from the definitions.

*

*You're assuming that $A \subseteq B$, so you know that if $a \in A$, then $a \in B$.

*You need to prove that $\bigcup A \subseteq \bigcup B$. By the definition of $\subseteq$, this means you need to prove that, for all $x$, if $x \in \bigcup A$ then $x \in \bigcup B$.
So assume $x \in \bigcup A$. Then:

*

*By definition of $\bigcup A$, it follows that $x \in a$ for some $a \in A$;

*Next, look at how you can apply the assumption that $A \subseteq B$;

*Finally, use the definition of $\bigcup B$ to deduce that $x \in \bigcup B$.

By definition of $\subseteq$, it follows that $\bigcup A \subseteq \bigcup B$.


text:
Q: Converting Text Received via JMS into XML I am trying to convert a message which i receive through JMS, which is in this form "Harry PotterJ.K.Rowling1995"
This is stored as a String. For example String contents.
How do i convert this String contents into an XML file.
Thanks you so much for your help in advance.

A: Smart ass answer:
String xmlString = "<myNewXmlString>" + myString + "</mynewXmlString>";
If it's more complicated you may want to look at this:
http://xerces.apache.org/xerces-j/
You probably also need some delimiter (a comma or colon separating the values) of the string to know What is a title, author and year.  You'd then need separate tags for each.  Another way to solve that is to use fixed width columns.  So authors are 50, titles are 50, and years are 4.  There are really three steps here: tokenizing the string, parsing the string into a data structure, and outputting the data structure to XML.
There are lots of automated tools that can convert a data structure like this:
class Book {
 String title;
 String author;
 Date year;
}

into XML as well.
See: http://jackson-users.ning.com/profiles/blogs/experimental-support-for


text:
Q: Forecasting Quarterly Time Series Data? I've gotten very confused reading all the articles about forecasting time series data with seasonality on Medium and other sources.   It seems that many provide useful background and importance of stationarity, decomposition, etc. but don't carry this forward with actual examples for quarterly financial data.
Problem: Am trying to forecast standard time series data for fast growth SaaS/cloud companies using a proven and robust fitted model ideally with Python and statsmodels.
What have I tried?  I've had success using FBProphet 's open source framework.  But, I find it to be a black box and don't understand how it arrives at its predictions.    Using cross validation, I arrived iteratively at the following optimized parameters:
best_params = {'changepoint_prior_scale': 0.6,
             'changepoint_range': 0.8,
             'daily_seasonality': False,
             'growth': 'logistic',
             'holidays_prior_scale': 0,
             'mcmc_samples': 0,
             'n_changepoints': 10,
             'seasonality_prior_scale': 0.015,
             'weekly_seasonality': False}

I'm trying to get inside the black box and use something more "raw" such as statsmodels but I am confused by statsmodels docs on which model to use (SARIMAX, ARIMA, ThetaModel, etc.).   My data does show exponential growth and many show quarterly seasonality.
Example revenues for CRM (Salesforce):
data = pd.DataFrame({Timestamp('2003-01-31 00:00:00'): 15600000.0,  Timestamp('2003-04-30 00:00:00'): 18900000.0,  Timestamp('2003-07-31 00:00:00'): 21600000.0, Timestamp('2003-10-31 00:00:00'): 25400000.0,  Timestamp('2004-01-31 00:00:00'): 30100000.0,  Timestamp('2004-04-30 00:00:00'): 34800000.0, Timestamp('2004-07-31 00:00:00'): 40600000.0,  Timestamp('2004-10-31 00:00:00'): 46400000.0,  Timestamp('2005-01-31 00:00:00'): 54600000.0, Timestamp('2005-04-30 00:00:00'): 64200000.0,  Timestamp('2005-07-31 00:00:00'): 71900000.0,  Timestamp('2005-10-31 00:00:00'): 82700000.0, Timestamp('2006-01-31 00:00:00'): 91100000.0,  Timestamp('2006-04-30 00:00:00'): 104700000.0,  Timestamp('2006-07-31 00:00:00'):
118100000.0,  Timestamp('2006-10-31 00:00:00'): 130100000.0,  Timestamp('2007-01-31 00:00:00'): 144200000.0,  Timestamp('2007-04-30 00:00:00'): 162400000.0,  Timestamp('2007-07-31 00:00:00'):
176600000.0,  Timestamp('2007-10-31 00:00:00'): 192800000.0,  Timestamp('2008-01-31 00:00:00'): 216900000.0,  Timestamp('2008-04-30 00:00:00'): 247600000.0,  Timestamp('2008-07-31 00:00:00'):
263100000.0,  Timestamp('2008-10-31 00:00:00'): 276500000.0,  Timestamp('2009-01-31 00:00:00'): 289600000.0,  Timestamp('2009-04-30 00:00:00'): 304900000.0,  Timestamp('2009-07-31 00:00:00'):
316100000.0,  Timestamp('2009-10-31 00:00:00'): 330500000.0,  Timestamp('2010-01-31 00:00:00'): 328400000.0,  Timestamp('2010-04-30 00:00:00'): 376800000.0,  Timestamp('2010-07-31 00:00:00'):
394400000.0,  Timestamp('2010-10-31 00:00:00'): 429100000.0,  Timestamp('2011-01-31 00:00:00'): 456900000.0,  Timestamp('2011-04-30 00:00:00'): 504400000.0,  Timestamp('2011-07-31 00:00:00'):
546000000.0,  Timestamp('2011-10-31 00:00:00'): 584300000.0,  Timestamp('2012-01-31 00:00:00'): 631900000.0,  Timestamp('2012-04-30 00:00:00'): 695500000.0,  Timestamp('2012-07-31 00:00:00'):
731600000.0,  Timestamp('2012-10-31 00:00:00'): 788400000.0,  Timestamp('2013-01-31 00:00:00'): 834700000.0,  Timestamp('2013-04-30 00:00:00'): 892600000.0,  Timestamp('2013-07-31 00:00:00'):
957100000.0,  Timestamp('2013-10-31 00:00:00'): 1076000000.0,  Timestamp('2014-01-31 00:00:00'): 1145200000.0,  Timestamp('2014-04-30 00:00:00'): 1226800000.0,  Timestamp('2014-07-31 00:00:00'):
1318600000.0,  Timestamp('2014-10-31 00:00:00'): 1383700000.0,  Timestamp('2015-01-31 00:00:00'): 1444600000.0,  Timestamp('2015-04-30 00:00:00'): 1511200000.0,  Timestamp('2015-07-31 00:00:00'):
1634700000.0,  Timestamp('2015-10-31 00:00:00'): 1712000000.0,  Timestamp('2016-01-31 00:00:00'): 1809400000.0,  Timestamp('2016-04-30 00:00:00'): 1916600000.0,  Timestamp('2016-07-31 00:00:00'):
2036600000.0,  Timestamp('2016-10-31 00:00:00'): 2144800000.0,  Timestamp('2017-01-31 00:00:00'): 2339000000.0,  Timestamp('2017-04-30 00:00:00'): 2397000000.0,  Timestamp('2017-07-31 00:00:00'):
2577000000.0,  Timestamp('2017-10-31 00:00:00'): 2701000000.0,  Timestamp('2018-01-31 00:00:00'): 2865000000.0,  Timestamp('2018-04-30 00:00:00'): 3006000000.0,  Timestamp('2018-07-31 00:00:00'):
3281000000.0,  Timestamp('2018-10-31 00:00:00'): 3392000000.0,  Timestamp('2019-01-31 00:00:00'): 3603000000.0,  Timestamp('2019-04-30 00:00:00'): 3737000000.0,  Timestamp('2019-07-31 00:00:00'):
3997000000.0,  Timestamp('2019-10-31 00:00:00'): 4513000000.0,  Timestamp('2020-01-31 00:00:00'): 4851000000.0,  Timestamp('2020-04-30 00:00:00'): 4865000000.0,  Timestamp('2020-07-31 00:00:00'):
5151000000.0})

When I try to see seasonal decomposition using statsmodels:
from statsmodels.tsa.seasonal import seasonal_decompose
results = seasonal_decompose(data)
results.plot()

Where do I go from here?   What does this tell me?  Do I have multiplicative or additive seaonality?   do I need to take exponential trend out via np.log(data).   Which model to fit?  What further tests are needed?
what if I have other companies with less sesonality?   Could you recommend a process for me to test my input data to deterime which model to fit?


text:
Q: How to return several files for ACTION_GET_CONTENT? After passing through the system file manager, the file manager I made is able to return a file when asked (say, by K9 email client) through ACTION_GET_CONTENT with this:
Uri uri = SearchOut.getUriFromFile(this, context.getPackageName(), file);
Intent intent = new Intent();
intent.setDataAndType(uri, getContentResolver().getType(uri));
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
setResult(Activity.RESULT_OK, intent);

K9 gets the file normally.
My file manager is also able to share multiple files with this:
ArrayList<Uri> urilist = ...
Intent shareIntent = new Intent(Intent.ACTION_SEND_MULTIPLE);
shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
shareIntent.putParcelableArrayListExtra(Intent.EXTRA_STREAM, urilist);
shareIntent.setType("application/octet-stream");
context.startActivity(Intent.createChooser(shareIntent, "Sharing files..."));

Then I can open K9 and loads all the files.
So how do I return SEVERAL files to K9 when they are requested through ACTION_GET_CONTENT?
As I wrote above, I know how to send several files with K9, or return 1 file when K9 asks, but I don't know how to return several files when K9 asks. The system file manager does return several files and K9 loads all of them happily.

A: I solved the problem using ClipData (needs API >= 16). Not sure if it is the best way to build the ClipData, though:
ClipData clipData = null;
for (Uri u : getSelectedFilesToArrayOfUri()) {
    if (clipData == null)
        clipData = ClipData.newRawUri(null, u);
    else
        clipData.addItem(new ClipData.Item(u));
}
intent.setClipData(clipData);
intent.setType("application/octet-stream");
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
setResult(Activity.RESULT_OK, intent);


text:
Q: How to order a controller by a virtual attribute that takes a param? I'm trying to order a "Post" index by the last activity date by the current_user or the current_user's friends. The post can be created or reposted (a different model).
Using my current approach, I get "undefined method `last_friend_update' for #Class:0x000000023a0e38"
Models
Post Model:
class Post < ActiveRecord::Base
  belongs_to :user
  has_many :reposts
  has_many :resposters, :through => :resposts, :source => :user

  def self.from_users_followed_by(user)
    followed_user_ids = user.friend_ids
    repost_ids = user.reposts.map(&:post_id)
    friend_reposts_ids = user.friend_reposts.map(&:post_id)
    comment_ids = user.comments.map(&:post_id)
    friend_comment_ids = user.friend_comments.map(&:post_id)
    where(['user_id IN (:followed_user_ids) OR user_id = :user_id
            OR id IN (:repost_ids) OR id IN (:friend_reposts_ids)
            OR id IN (:comment_ids) OR id IN (:friend_comment_ids)',
      {followed_user_ids: followed_user_ids, user_id: user,
       repost_ids: repost_ids, friend_reposts_ids: friend_reposts_ids,
       comment_ids: comment_ids, friend_comment_ids: friend_comment_ids}])
  end

def self.last_friend_update(user)
    post_date = :created_at.to_s
    user_repost_date = user.reposts.where(['post_id = :post_id',{post_id: :id}]).map(&:created_at).max.to_s
    friends_repost_date = user.friend_reposts.where(['post_id = :post_id',{post_id: :id}]).map(&:created_at).max.to_s
    user_comment_date = user.comments.where(['post_id = :post_id',{post_id: :id}]).map(&:created_at).max.to_s
    friend_comment_date = user.friend_comments.where(['post_id = :post_id',{post_id: :id}]).map(&:created_at).max.to_s
    most_recent_date = [post_date, user_repost_date, user_comment_date, friend_comment_date].max.to_s
  end

User Model
class User < ActiveRecord::Base
  has_many :posts
  has_many :friendships, dependent: :destroy
  has_many :friends, :through => :friendships
  has_many :reposts
  has_many :reposted_posts, :through => :reposts, :source => :post
  has_many :friend_posts, :through => :friendships, :source => :posts
  has_many :friend_reposts, :through => :friendships, :source => :reposts
end

Friendship Model:
class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User"
  has_many :posts, :foreign_key => "user_id", :primary_key => "friend_id"
  has_many :reposts, :foreign_key => "user_id", :primary_key => "friend_id"
  has_many :comments, :foreign_key => "user_id", :primary_key => "friend_id"
end

Posts Controller
class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]

  # GET /posts
  # GET /posts.json
  def index
    if user_signed_in?
      @posts = Post.from_users_followed_by(current_user).sort_by("#{Post.last_friend_update(current_user)}")
    else
      @all_posts = Post.all.order("created_at desc")
    end
  end

  private
  def post_params
    params.require(:post).permit(:user_id, :url, :summary, :title, :last_friend_udpate)
  end
end

Update
Post Model
  def last_friend_update(user)
    # setting some initial variables here, so they won't error if null later
    post_date = self.created_at.to_datetime
    user_repost_date = "01-01-1960".to_datetime
    friends_repost_date = "01-01-1960".to_datetime
    user_comment_date = "01-01-1960".to_datetime
    friend_comment_date = "01-01-1960".to_datetime
    # Getting most recent dates for the current_user and their firends on the post
    user_repost_maxdate = user.reposts.where(['post_id = :post_id',{post_id: self.id}]).map(&:created_at).max
    friends_repost_maxdate = user.friend_reposts.where(['post_id = :post_id',{post_id: self.id}]).map(&:created_at).max
    user_comment_maxdate = user.comments.where(['post_id = :post_id',{post_id: self.id}]).map(&:created_at).max
    friend_comment_maxdate = user.friend_comments.where(['post_id = :post_id',{post_id: self.id}]).map(&:created_at).max
    # If there are recent dates for activities, set the variables as such
    unless user_repost_maxdate.nil?
      user_repost_date = user_repost_maxdate.to_datetime
    end
    unless friends_repost_maxdate.nil?
      friends_repost_date = friends_repost_maxdate.to_datetime
    end
    unless user_comment_maxdate.nil?
      user_comment_date = user_comment_maxdate.to_datetime
    end
    unless friend_comment_maxdate.nil?
      friend_comment_date = friend_comment_maxdate.to_datetime
    end
    # get the max of the activity date_times.
    [post_date.to_datetime, user_repost_date.to_datetime, friends_repost_date, user_comment_date.to_datetime, friend_comment_date.to_datetime].max
  end

Post Controller section:
# sort_by lets me use the block format, while order_by did not.
# I reverse at the end to have the most recent post at the top.
@posts = Post.from_users_followed_by(current_user).sort_by{ |post| post.last_friend_update(current_user) }.reverse

A: In the model you've got last_friend_udpate, in the post params you have last_friend_udpate, but in the index you have last_friend_update


text:
Q: confused by C# type conversion I'm new to C# but familiar with vb.net
my setVendor functions expects an int and a string
why does this work
shopify.setVendor(System.Convert.ToInt32(reader["ProductID"]), System.Convert.ToString(reader["Vendor"]));

but this fails for both parameters:
shopify.setVendor(int.Parse(reader["ProductID"]), reader["Vendor"].ToString);

very confused. It wants a string and I give it a string but it doesn't accept it . . . error converting string to int

A: There's an overload of Convert.ToInt32 which accepts object. There's no such overload for int.Parse. The argument must be a string at compile time. You would need:
shopify.setVendor(int.Parse(reader["ProductID"].ToString()),
                  reader["Vendor"].ToString());

(Note the change from ToString to ToString() for the second argument... previously you were specifying the ToString method group which is used to create delegates; with the change you're calling ToString instead.)
Or:
// This only works if the value *is* a string
shopify.setVendor(int.Parse((string) reader["ProductID"]),
                  reader["Vendor"].ToString());

Ideally, however, you'd get back the values in the correct forms already, so you could use:
shopify.setVendor((int) reader["ProductID"], (string) reader["Vendor"]);

Or:
// Set up productIdColumn and vendorColumn first
shopify.setVendor(reader.GetInt32(productIdColumn), reader.GetString(vendorColumn));

Also note that setVendor is not a conventional .NET method name.

A: Well, for your first question
System.Convert.ToInt32(...) and System.Convert.ToString(...) convert the supplied arguments to int and string respectively which is in the correct format as expected by your code.
Secondly, it should be ToString() not ToString since you want to make a call to the method:
reader["Vendor"].ToString()

A: The ToString part in your second code-snippet requires parentheses () because it is a method, not a member or property.

A: int productId;
if(int.TryParse(reader["ProductID"].ToString(), out productId))
   shopify.setVendor(productId, reader["Vendor"].ToString());

Would be a safe way to do it.


text:
Q: AWS Elasticache name resolution issue on high traffic guys
I'm facing a problem with an Elasticache Cluster with Redis when I have high traffic (1.6k requests/sec) on the web servers.
The problem is the clusters name (configuration endpoint), PHP start to fail with:
018-08-27 14:02:03 - 51.36.136.47 - Redis::connect(): php_network_getaddresses: getaddrinfo failed: Temporary failure in name resolution - https://myserver.com/re.php?id=qZ2pfKmeqqpofKg=&p1=M2018082712-dc6872150731b24433b8592f6455f50e&p2=83721 - SA - /home/ubuntu/myapp/system/api/LRedis.php - 25 - errno: 2

If I use a quarter of the total traffic works fine.
Actually, I'm using the private IP address from one node and works, but this is not a good practice.

A: I encountered the same problem just yesterday and did some workaround:

*

*change the redis instance type to allow higher network performance

*since I use Kubernetes environment, I increased kube-dns

And didn't see this issue coming up again, hope this helps.


text:
Q: Usar 2 tipos de navegação Drawer e BottomTab ao mesmo tempo Olá,
Estou meio confuso em relação as rotas do react-native, digo quando preciso usar 2 tipos de rotas na mesma tela. Aqui vai minha tentativa até agora:
export default (isSigned = false) =>
  createAppContainer(
    createSwitchNavigator(
      {
        Sign: createSwitchNavigator({
          SignIn,
          SignUp,
        }),
        App: createBottomTabNavigator({
          Dashboard,
          Profile,
          Settings,
        }),
      },
      {
        initialRouteName: isSigned ? 'App' : 'Sign',
      },
    ),
  );

Cheguei até aqui onde consigo usar o TabNavigator ou Drawer, não os 2 juntos.

A: Após alguns minutos de pesquisa resolvi da seguinte forma:
export default (isSigned = false) =>
  createAppContainer(
    createSwitchNavigator(
      {
        Sign: createSwitchNavigator({
          SignIn,
          SignUp,
        }),
        App: createBottomTabNavigator({
          Dashboard: {
            screen: createDrawerNavigator({
              Dashboard,
              Profile,
              Settings,
            }),
          },
          Profile: {
            screen: createDrawerNavigator({
              Dashboard,
              Profile,
              Settings,
            }),
          },
          Settings: {
            screen: createDrawerNavigator({
              Dashboard,
              Profile,
              Settings,
            }),
          },
        }),
      },
      {
        initialRouteName: isSigned ? 'App' : 'Sign',
      },
    ),
  );


text:
Q: How to prove the condition number $\kappa(P) = n$? I recently have been considering the Sylvester matrix equation given by $AX-XB = C$, where the rank of $C$ is lower than $X$, and
$A$ is a diagonal matrix, and $B$ is defined as follow
\begin{equation}
B=\begin{bmatrix}
& & & & -n \\
\frac{1}{2} & & & & \\
& \frac{2}{3} & & & \\
& & \ddots & & \\
& & & \frac{n-1}{n} &
\end{bmatrix}_{n \times n}.
\end{equation}
However, $B$ is not diagonal. I have obtained the eigendecomposition of $B$ as follow
\begin{equation}
BP = P\Lambda,
\end{equation}
where $P = [p_1\ p_2 \ \cdots \ p_n]$ is a square matrix whose columns are the $n$ linearly independent eigenvectors of $B$ and $\|p_i\| = 1$, and $\Lambda$ is a diagonal matrix where each diagonal element $\Lambda_{ii}$ is the eigenvalue associated with the $i$-th column of $P$, and $\Lambda_{ii}$ is the $n$ (shifted) roots of unity, i.e, $\Lambda_{ii}^n + 1 = 0$.
Then, it follows that
\begin{equation}
AXP - XBP = CP \Rightarrow A(XP) - (XP) \Lambda = CP.
\end{equation}
Thus, I want to estimate the condition number of $P$ to compare the singular value of $X$ and $XP$.
Through computer simulation, I have found that the condition number of $P$ is $n$, i.e.,
\begin{equation}
\kappa(P)=\left\|P^{-1}\right\|\|P\| = \frac{\sigma_{\max}(P)}{\sigma_{\min}(P)} = n.
\end{equation}
But I don't know how to prove $\kappa(P)=n$ yet.

A: Note that $B=wDCD^{-1}$ where $w=\exp(\frac{i\pi}{n}),\,D=\operatorname{diag}(1,\frac{w}{2},\ldots,\frac{w^{n-1}}{n})$ and
$$
C=\pmatrix{&&&&1\\ 1\\ &1\\ &&\ddots\\ &&&1}.
$$
It is well known that $C=UD^2U^\ast$ where $U$ is a unitary DFT matrix. (See Wikipedia for instance.) Therefore $B=P_0\Lambda P_0^{-1}$, where $P_0=DU$ and $\Lambda=wD^2$. Since $U$ is a DFT matrix, the moduli of all its elements are equal to $\frac{1}{\sqrt{n}}$. It follows that all columns of $P_0=DU$ have the same norm, namely, $r=\sqrt{\sum_{k=1}^n\frac{1}{nk^2}}$.
Now, since all eigenvalues of $\Lambda$ (or $B$) are distinct, its eigenspaces are one-dimensional. So, if $B$ has a diagonalisation $P\Lambda P^{-1}$ in which all columns of $P$ are unit vectors, we must have $P=\frac{1}{r}P_0S=\frac{1}{r}DUS$ for some unitary diagonal matrix $S$. It follows that the condition number of $P$ is identical to the condition number of $D$, which is $n$. (We actually know more: the singular values of $P$ are $\frac{1}{rk}$ for $k=1,2,\ldots,n$, but it suffices to conclude using the condition number of $D$.)


text:
Q: How to fix Error: spawn npm ENOENT in windows 10? I'm trying to create a CLI that automatically clones the vuex-store-starter template that I created. At the time of installation, it shows an error based on Error: spawn npm ENOENT
Any help will be more than welcome.
#! /usr/bin/env node

const {spawn} = require('child_process');

const name = process.argv[2];
if (!name || name.match(/[<>:"\/\\|?*\x00-\x1F]/)) {
  return console.log(`
  Invalid directory name.
  Usage: <vuex-store-starter-cli> <repo-name>
`);
}

const URL = 'https://github.com/ChrisMichaelPerezSantiago/vuex-store-starter.git';

f('git', ['clone', URL, name])
  .then(() => {
    return f('rm', ['-rf', `${name}/.git`]);
  }).then(() => {
    console.log('Installing dependencies...');
    return f('npm', ['install'], {
      cwd: process.cwd() + '/' + name
    });
  }).then(() => {
    console.log('Done! ');
    console.log('');
    console.log('cd', name);
    console.log('npm run start');
    console.log('For more information check the package.json')
  });

function f(command, args, options = undefined) {
  const spawned = spawn(command, args, options);
  return new Promise((resolve) => {
    spawned.stdout.on('data', (data) => {
      console.log(data.toString());
    });
    spawned.stderr.on('data', (data) => {
      console.error(data.toString());
    });
    spawned.on('close', () => {
      resolve();
    });
  });
}

The error output that I am having
Cloning into 'vuex-store-starter-cli'...

Installing dependencies...
events.js:174
      throw er; // Unhandled 'error' event
      ^

Error: spawn npm ENOENT
    at Process.ChildProcess._handle.onexit (internal/child_process.js:240:19)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)
Emitted 'error' event at:
    at Process.ChildProcess._handle.onexit (internal/child_process.js:246:12)
    at onErrorNT (internal/child_process.js:415:16)
    at process._tickCallback (internal/process/next_tick.js:63:19)

A: I corrected the problem by adding the following
const npm = which.sync('npm');

And changing the following
'npm', ['install'] by npm, ['install']


text:
Q: R package dependencies not installed from Additional_repositories (revisited) I am attempting to prepare a package for submission to the CRAN. In my DESCRIPTION file I include non-CRAN packages in the Depends and Suggests arguments. To tell R where to find the non-CRAN packages, I include the Additional_repositories argument; and I include an .onLoad function at the top of my program (i.e., in 'zzz.R'). I am able to build and check (--as-cran) in RStudio with zero warnings, notes or errors so long as all the Depends and Suggests packages are present. I then use devtools::build() to create a .tar.gz file locally.
To test for a successful local install, I remove the non-CRAN packages from my computer and attempt to install the .tar.gz file that I created. I then get the message:
ERROR: dependency 'smwrQW' is not available for package 'baytrends'

I've read through the

*

*R package dependencies not installed from Additional_repositories

*Include non-CRAN package in CRAN package

*http://thecoatlessprofessor.com/programming/r-data-packages-in-external-data-repositories-using-the-additional_repositories-field/

*How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?
Unfortunately, the above error continues. I'm confident of the url I'm using since the below install.package line works when run independently
install.packages('smwrQW',repos=c("http://owi.usgs.gov/R"),dependencies = TRUE)

The applicable bits of the DESCRIPTION and zzz.R file are below:
DESCRIPTION:
Date: 2017-03-15
Depends:
    R (>= 3.2.0),
    lubridate,
    mgcv,
    smwrQW
License: GPL-3
LazyData: TRUE
RoxygenNote: 6.0.1
Suggests:
    dataRetrieval,
    devtools,
    fitdistrplus,
    knitr,
    nlme,
    pander,
    plyr,
    rmarkdown,
    smwrBase,
    smwrGraphs,
    smwrStats,
    testthat
Additional_repositories: http://owi.usgs.gov/R
VignetteBuilder: knitr

zzz.R:
.onLoad <- function(libname = find.package("baytrends"), pkgname = "baytrends"){

  repos = getOption("repos")
  repos["USGS"] = "http://owi.usgs.gov/R"
  options(repos = repos)
  invisible(repos)

  # declaration of global variables (https://stackoverflow.com/questions/9439256)
  if(getRversion() >= "2.15.1")
    utils::globalVariables(c("begin", "methodsList"))
  invisible()

}

.onAttach <-  function(libname = find.package("baytrends"), pkgname = "baytrends"){
  packageStartupMessage("This software program is preliminary or provisional and is subject to revision. ")
}

A: You cannot have packages from non-standard repos in Depends: or Imports:.
You can have them in Suggests:
Several packages do this; one you could look at is hurricaneexposure which uses this to make a 'too-large-for-CRAN' data package hurricanexposuredata available from a repository created via drat.
So you must move the smwrQR package to Suggests: and then test for it.
Brooke and I have a draft paper (under review) on this which we could send you if you drop us line -- it details all this more than the short answer could.


text:
Q: Flex actionscript: how can I export my function to other SWF? I want to export some of my functions to external so that other people can embed my SWF into their's and invoke the function, how can I achieve that?

A: Check the LocalConnection class for that.
Here is an example: http://learn.adobe.com/wiki/display/Flex/Local+Connections


text:
Q: How to Display a String like Password ****** in jQuery Is there any way to output/display a user input like Password such as ** or small circles? let say a user inputs "Maraton" how can I represent it as * in the page not in the <input>? I am not talking about input type!

A: <input type="password" name="any" />

Update: Based on your comment
suppose your div where you want to show your password:

Next your javascript code
name = "maraton";
pass="";
for(i=0;i<name.length;i++)
{
    pass=pass+"*";
}

var element=document.getElementById("pass");
element.innerHTML=pass;


text:
Q: Data Model enquiry Folks,
I have a around 2 million assets that send 15 min interval data for a given day (i.e) total of 96 intervals for a given day. What is best database modeling approach. My target RDBMS is Oracle.
I'm partitioning by week and for each interval I need to store the interval type (INT_TYPE) (i.e) actual or estimated etc.,
Option--1 will be way too deep in terms of data.
Option--2 can minimize the volume, but how do i model the column interval-type in Option--2? such that we can capture the interval type??
--OPTION 1
CREATE TABLE TRANS.ASSET_DAILY_INT(
    INT_READ_DT                        DATE             NOT NULL,
     ASSET_ID                        VARCHAR2(30)      NOT NULL,
     MINUTES                         NUMBER (2,0)       NOT NULL,
    INT_VALUE                   FLOAT(126)              NOT NULL,
    **INT_TYPE                    VARCHAR2(30)          NOT NULL,**
   ASSET_TYPE                     NUMBER(38,0),
    INT_SUM_DAY_USG                  FLOAT(126),
    HIGHEST_INT_DAY_USG              FLOAT(126),
    CREATED_DT                       DATE,
    MODIFIED_DT                      DATE,
     )

TABLESPACE TRANS
PARALLEL(DEGREE 4 INSTANCES 1)
PARTITION BY RANGE(MDM_READ_DT)
INTERVAL (NUMTODSINTERVAL(7,'DAY'))
(PARTITION p_first VALUES LESS THAN ('01-JAN-2010'));

--OPTION 2 how do i model the column interval-type in Option--2? such that we can capture the interval type??
CREATE TABLE TRANS.ASSET_DAILY_INT(
    INT_READ_DT                        DATE             NOT NULL,
     ASSET_ID                        VARCHAR2(30)      NOT NULL,
    INT_VALUE_0000                   FLOAT(126),
    INT_VALUE_0015                   FLOAT(126),
    INT_VALUE_0030                   FLOAT(126),
    INT_VALUE_0045                   FLOAT(126),
    INT_VALUE_0100                   FLOAT(126),
    INT_VALUE_0115                   FLOAT(126),
    INT_VALUE_0130                   FLOAT(126),
    INT_VALUE_0145                   FLOAT(126),
    INT_VALUE_0200                   FLOAT(126),
    INT_VALUE_0215                   FLOAT(126),
    INT_VALUE_0230                   FLOAT(126),
    INT_VALUE_0245                   FLOAT(126),
    INT_VALUE_0300                   FLOAT(126),
    INT_VALUE_0315                   FLOAT(126),
    INT_VALUE_0330                   FLOAT(126),
    INT_VALUE_0345                   FLOAT(126),
    INT_VALUE_0400                   FLOAT(126),
    INT_VALUE_0415                   FLOAT(126),
    INT_VALUE_0430                   FLOAT(126),
    INT_VALUE_0445                   FLOAT(126),
    INT_VALUE_0500                   FLOAT(126),
    INT_VALUE_0515                   FLOAT(126),
    INT_VALUE_0530                   FLOAT(126),
    INT_VALUE_0545                   FLOAT(126),
    INT_VALUE_0600                   FLOAT(126),
    INT_VALUE_0615                   FLOAT(126),
    INT_VALUE_0630                   FLOAT(126),
    INT_VALUE_0645                   FLOAT(126),
    INT_VALUE_0700                   FLOAT(126),
    INT_VALUE_0715                   FLOAT(126),
    INT_VALUE_0730                   FLOAT(126),
    INT_VALUE_0745                   FLOAT(126),
    INT_VALUE_0800                   FLOAT(126),
    INT_VALUE_0815                   FLOAT(126),
    INT_VALUE_0830                   FLOAT(126),
    INT_VALUE_0845                   FLOAT(126),
    INT_VALUE_0900                   FLOAT(126),
    INT_VALUE_0915                   FLOAT(126),
    INT_VALUE_0930                   FLOAT(126),
    INT_VALUE_0945                   FLOAT(126),
    INT_VALUE_1000                   FLOAT(126),
    INT_VALUE_1015                   FLOAT(126),
    INT_VALUE_1030                   FLOAT(126),
    INT_VALUE_1045                   FLOAT(126),
    INT_VALUE_1100                   FLOAT(126),
    INT_VALUE_1115                   FLOAT(126),
    INT_VALUE_1130                   FLOAT(126),
    INT_VALUE_1145                   FLOAT(126),
    INT_VALUE_1200                   FLOAT(126),
    INT_VALUE_1215                   FLOAT(126),
    INT_VALUE_1230                   FLOAT(126),
    INT_VALUE_1245                   FLOAT(126),
    INT_VALUE_1300                   FLOAT(126),
    INT_VALUE_1315                   FLOAT(126),
    INT_VALUE_1330                   FLOAT(126),
    INT_VALUE_1345                   FLOAT(126),
    INT_VALUE_1400                   FLOAT(126),
    INT_VALUE_1415                   FLOAT(126),
    INT_VALUE_1430                   FLOAT(126),
    INT_VALUE_1445                   FLOAT(126),
    INT_VALUE_1500                   FLOAT(126),
    INT_VALUE_1515                   FLOAT(126),
    INT_VALUE_1530                   FLOAT(126),
    INT_VALUE_1545                   FLOAT(126),
    INT_VALUE_1600                   FLOAT(126),
    INT_VALUE_1615                   FLOAT(126),
    INT_VALUE_1630                   FLOAT(126),
    INT_VALUE_1645                   FLOAT(126),
    INT_VALUE_1700                   FLOAT(126),
    INT_VALUE_1715                   FLOAT(126),
    INT_VALUE_1730                   FLOAT(126),
    INT_VALUE_1745                   FLOAT(126),
    INT_VALUE_1800                   FLOAT(126),
    INT_VALUE_1815                   FLOAT(126),
    INT_VALUE_1830                   FLOAT(126),
    INT_VALUE_1845                   FLOAT(126),
    INT_VALUE_1900                   FLOAT(126),
    INT_VALUE_1915                   FLOAT(126),
    INT_VALUE_1930                   FLOAT(126),
    INT_VALUE_1945                   FLOAT(126),
    INT_VALUE_2000                   FLOAT(126),
    INT_VALUE_2015                   FLOAT(126),
    INT_VALUE_2030                   FLOAT(126),
    INT_VALUE_2045                   FLOAT(126),
    INT_VALUE_2100                   FLOAT(126),
    INT_VALUE_2115                   FLOAT(126),
    INT_VALUE_2130                   FLOAT(126),
    INT_VALUE_2145                   FLOAT(126),
    INT_VALUE_2200                   FLOAT(126),
    INT_VALUE_2215                   FLOAT(126),
    INT_VALUE_2230                   FLOAT(126),
    INT_VALUE_2245                   FLOAT(126),
    INT_VALUE_2300                   FLOAT(126),
    INT_VALUE_2315                   FLOAT(126),
    INT_VALUE_2330                   FLOAT(126),
    INT_VALUE_2345                   FLOAT(126),
    ASSET_TYPE                     NUMBER(38,0),
    INT_SUM_DAY_USG                  FLOAT(126),
    HIGHEST_INT_DAY_USG              FLOAT(126),
    CREATED_DT                       DATE,
    MODIFIED_DT                      DATE,
     )
TABLESPACE TRANS
PARALLEL(DEGREE 4 INSTANCES 1)
PARTITION BY RANGE(MDM_READ_DT)
INTERVAL (NUMTODSINTERVAL(7,'DAY'))
(PARTITION p_first VALUES LESS THAN ('01-JAN-2010'));


text:
Q: Triggers Creation on Insert on a View in SQL Server 2019 I have a table:
CREATE TABLE dbo.employee_assignment
(
    employee_id BIGINT,
    department_id BIGINT,
    job_title_id BIGINT,
    manager_id BIGINT,
    effective_start_date SMALLDATETIME,
    effective_end_date SMALLDATETIME,
    action_code VARCHAR(60)
);

I populated it with values:
INSERT INTO dbo.employee_assignment (employee_id, department_id, job_title_id, manager_id, effective_start_date, effective_end_date, action_code)
VALUES
     (1,2,8,3,'2018-06-08 00:00:00',NULL,'MANAGER_CHANGE'),
     (2,2,3,6,'2012-08-10 00:00:00','2013-08-10 00:00:00','MANAGER_CHANGE'),
     (3,5,6,3,'2014-07-29 00:00:00',NULL,'MANAGER_CHANGE'),
     (4,1,10,6,'2011-02-03 00:00:00','2015-06-04 00:00:00','HIRE'),
     (4,1,11,6,'2015-06-04 00:00:00',NULL,'GRADE_CHANGE'),
     (2,2,3,8,'2012-08-10 00:00:00','2013-08-10 00:00:00','GRADE_CHANGE'),
     (7,7,1,6,'2021-06-06 00:00:00',NULL,'MANAGER_CHANGE'),
     (1,2,8,8,'2016-06-07 00:00:00','2017-06-07 00:00:00','HIRE'),
     (8,5,7,12,'2018-04-18 00:00:00',NULL,'HIRE'),
     (3,5,6,12,'2013-10-25 22:12:01','2012-08-10 00:00:00','HIRE');

Then I created a view of it:
CREATE VIEW v_employee_assignment
AS
    SELECT
        employee_id, department_id, job_title_id, manager_id,
        effective_start_date, effective_end_date, action_code
    FROM
        employee_assignment

and two more tables with a copy of employee_assignment
SELECT *
INTO employee_assignment_history
FROM employee_assignment;

SELECT *
INTO employee_assignment_future
FROM employee_assignment;

I'm trying to create a trigger that each time a new record is inserted into employee_assignment view, check the following:

*

*If effective_start_date > current_date, then it should be inserted only into employee_assignment_future;

*If effective_start_date <= current_date, then it should insert it both into employee_assignment and employee_assignment_history
Code:
CREATE OR ALTER TRIGGER t_v_employee_assignment
ON v_employee_assignment
INSTEAD OF INSERT
AS
        DECLARE @employee_id BIGINT
        DECLARE @department_id BIGINT
        DECLARE @job_title_id BIGINT
        DECLARE @manager_id BIGINT
        DECLARE @effective_end_date SMALLDATETIME
        DECLARE @action_code VARCHAR(60)
        DECLARE @effective_start_date SMALLDATETIME
    BEGIN
            IF  @effective_start_date >  GETDATE()
            BEGIN
                INSERT INTO employee_assignment_future (employee_id,
                                                        department_id,
                                                        job_title_id,
                                                        manager_id,
                                                        effective_start_date,
                                                        effective_end_date ,
                                                        action_code)
                                                        VALUES (@employee_id,
                                                                @department_id,
                                                                @job_title_id,
                                                                @manager_id,
                                                                @effective_start_date,
                                                                @effective_end_date,
                                                                @action_code)

            END
            ELSE
            BEGIN
            INSERT INTO employee_assignment_history (employee_id,
                                                     department_id,
                                                     job_title_id,
                                                     manager_id,
                                                     effective_start_date,
                                                     effective_end_date ,
                                                     action_code)
                                                     VALUES (@employee_id,
                                                                @department_id,
                                                                @job_title_id,
                                                                @manager_id,
                                                                @effective_start_date,
                                                                @effective_end_date,
                                                                @action_code)

            INSERT INTO employee_assignment (employee_id,
                                                        department_id,
                                                        job_title_id,
                                                        manager_id,
                                                        effective_start_date,
                                                        effective_end_date ,
                                                        action_code)
                                                        VALUES (@employee_id,
                                                                @department_id,
                                                                @job_title_id,
                                                                @manager_id,
                                                                @effective_start_date,
                                                                @effective_end_date,
                                                                @action_code)
            END
    END;

However, I receive NULL row added into my tables, when I'm trying to insert a test row:
INSERT INTO dbo.v_employee_assignment2 (employee_id, department_id, job_title_id, manager_id, effective_start_date, effective_end_date, action_code)
VALUES
     (1, 2, 8, 3, '2023-06-08 00:00:00', NULL, 'MANAGER_CHANGE')

and it's supposed to be inserted into employee_assignment_future since the starting date is bigger than the current date, but it inserts in all the other tables but not into the employee_assignment_future.

A: Posting an answer, since I figured it out, maybe somebody will find it helpful.
So basically had to use inserted table, a special SQL table:
CREATE OR ALTER TRIGGER t_v_employee_assignment on v_employee_assignment2
INSTEAD OF INSERT
AS
    DECLARE @effective_start_date SMALLDATETIME = (SELECT effective_start_date from inserted)
BEGIN
SET ROWCOUNT 0;

        IF  @effective_start_date >  GETDATE()
        BEGIN
            INSERT INTO employee_assignment_future (employee_id,
                                                    department_id,
                                                    job_title_id,
                                                    manager_id,
                                                    effective_start_date,
                                                    effective_end_date ,
                                                    action_code)

                                                    SELECT
                                                    employee_id,
                                                    department_id,
                                                    job_title_id,
                                                    manager_id,
                                                    effective_start_date,
                                                    effective_end_date ,
                                                    action_code
                                                    from inserted i

        END
        ELSE
        BEGIN
        INSERT INTO employee_assignment_history (employee_id,
                                                 department_id,
                                                 job_title_id,
                                                 manager_id,
                                                 effective_start_date,
                                                 effective_end_date ,
                                                 action_code)
                                                 SELECT
                                                 employee_id,
                                                    department_id,
                                                    job_title_id,
                                                    manager_id,
                                                    effective_start_date,
                                                    effective_end_date ,
                                                    action_code
                                                    from inserted i

        INSERT INTO employee_assignment (employee_id,
                                                    department_id,
                                                    job_title_id,
                                                    manager_id,
                                                    effective_start_date,
                                                    effective_end_date ,
                                                    action_code)
                                                    SELECT
                                                 employee_id,
                                                    department_id,
                                                    job_title_id,
                                                    manager_id,
                                                    effective_start_date,
                                                    effective_end_date ,
                                                    action_code
                                                    from inserted i
        END
END;


text:
Q: On itemselectedListener not working with custom list adapter nothing happens when I click on item of list view here is code
@SuppressLint("ParserError")
public class DinerList extends Activity implements Comparator<CanteenTagEntry>,
        OnItemSelectedListener {
    List<CanteenTagEntry> dinerlist;
    int size;
    int[] arr;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.diner_list);
        ListView listView1 = (ListView) findViewById(R.id.list);
        Context con = getApplicationContext();
        DatabaseHelper dbHelper = new DatabaseHelper(con);
        ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();

        try {
            dinerlist = repository.total();
            Collections.sort(dinerlist, new DinerList());
            Collections.sort(dinerlist, new sortbyuser());
            Collections.sort(dinerlist, new sortbycompany());

            size = dinerlist.size();
            arr = new int[size];
            for (int i = 0; i < size; i++) {
                CanteenTagEntry tagentry = dinerlist.get(i);
                int b = tagentry.getId();
                System.out.print(b);
                arr[i] = tagentry.getId();
                System.out.print(arr[i]);
            }

        } catch (SQLException e) {
            Log.d("DinerList", "Unable to retrieve diner list", e);
        }
        CanteenAdapter adapter = new CanteenAdapter(this,
                R.layout.listview_item_row,
                (ArrayList<CanteenTagEntry>) dinerlist);
        listView1.setAdapter(adapter);
    }

    public class CanteenAdapter extends ArrayAdapter<CanteenTagEntry> {

        Context context;
        int layoutResourceId;
        ArrayList<CanteenTagEntry> data = (ArrayList<CanteenTagEntry>) dinerlist;

        public CanteenAdapter(Context context, int layoutResourceId,
                ArrayList<CanteenTagEntry> data) {
            super(context, layoutResourceId, dinerlist);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = (ArrayList<CanteenTagEntry>) dinerlist;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            RouteHolder holder = null;
            if (row == null) {
                LayoutInflater inflater = ((Activity) context)
                        .getLayoutInflater();
                row = inflater.inflate(layoutResourceId, parent, false);
                holder = new RouteHolder();
                holder.txtName1 = (TextView) row.findViewById(R.id.Title1);
                holder.txtName2 = (TextView) row.findViewById(R.id.Title2);
                holder.txtName3 = (TextView) row.findViewById(R.id.Title3);

                row.setTag(holder);
            } else {
                holder = (RouteHolder) row.getTag();
            }
            CanteenTagEntry tagentry = data.get(position);
            String idcolor = tagentry.getUser().getIdcolor().toString();

            try {
                holder.txtName1.setTextColor(Color.parseColor(idcolor));
                holder.txtName2.setTextColor(Color.parseColor(idcolor));
                holder.txtName3.setTextColor(Color.parseColor(idcolor));
            } catch (Exception e) {
                holder.txtName1.setTextColor(Color.GRAY);
                holder.txtName2.setTextColor(Color.GRAY);
                holder.txtName3.setTextColor(Color.GRAY);
            }

            holder.txtName1.setText(tagentry.getUser().getUserType().getName());
            holder.txtName2.setText(tagentry.getUser().getCompany().getName());
            holder.txtName3.setText(tagentry.getUser().getFirstName());

            return row;
        }

        class RouteHolder {
            TextView txtName1;
            TextView txtName2;
            TextView txtName3;
            TextView txtName4;

        }

    }

    @Override
    public int compare(CanteenTagEntry o1, CanteenTagEntry o2) {
        return o1.getUser().getFirstName()
                .compareTo(o2.getUser().getFirstName());

    }

    public class sortbyuser implements Comparator<CanteenTagEntry> {

        @Override
        public int compare(CanteenTagEntry lhs, CanteenTagEntry rhs) {
            return lhs.getUser().getUserType().getName()
                    .compareTo(rhs.getUser().getUserType().getName());

        }

    }

    public class sortbycompany implements Comparator<CanteenTagEntry> {

        @Override
        public int compare(CanteenTagEntry lhs, CanteenTagEntry rhs) {
            return lhs.getUser().getCompany().getName()
                    .compareTo(rhs.getUser().getCompany().getName());

        }

    }

    @Override
    public void onItemSelected(AdapterView<?> l, View v, int position,
            long ide) {
        super.onListItemClick(l, v, position, ide);
        CanteenTagEntry tagentry = null;
        int pos = position;
        int id = arr[pos];
        int userid = 0;
        Context con = getApplicationContext();
        DatabaseHelper dbHelper = new DatabaseHelper(con);
        ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();
        try {
            tagentry = repository.Retrieve(id);
            userid = tagentry.getUser().getId();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try {
            StartFood food = new StartFood(id, userid);

        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {
        // TODO Auto-generated method stub

    }

}

A: i thin you need to used
listview.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                long arg3) {
            // TODO Auto-generated method stub

               // do your work here

        }
    });

A: Try to set OnItemClickListener for your listView1 as per below and try to run.
listView1.setOnItemClickListener(new OnItemClickListener()
{
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id)
    {
        CanteenTagEntry tagentry = null;
        int pos = position;
        int id = arr[pos];
        int userid = 0;
        Context con = getApplicationContext();
        DatabaseHelper dbHelper = new DatabaseHelper(con);
        ICanteenLogRepository repository = dbHelper.getCanteenLogRepository();

        try
        {
            tagentry = repository.Retrieve(id);
            userid = tagentry.getUser().getId();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        try
        {
            StartFood food = new StartFood(id, userid);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

A: Before returning the row Set the listener to the row like this.
row.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                                      // your code
                }
            });


text:
Q: jQuery - adding class with color attribute to the link Here is my problem. I have a list of dynamically generated classes. Each class has a color. Here is example class:
.magenta {
    color: #7abbb8;
}

On the other side, I have some links in a footer. I want to use this class when <p> in footer is hovered:
(function($) {
    $('footer p').hover(function() {
        $(this).find('a').addClass('magenta');
    });
})(jQuery);

This code works perfect - I my a have class="magenta" after p is hovered. But... it doesn't have color: #7abbb8. It probably could be easly fixed with !important, but as I said, I have a lot of these classes, they are created dynamically, so I don't want to do that. How can I do that another way?
// edit
OK, the problem is somewhere else. I didn't changed classes css, I changed css of every element which had this class. So this color will not be added with class to new elements. Unfortunately there is no simple way to solve this with jQuery, but it seems there are some plugins adding CSS rules to the stylesheet.

A: Check your style sheet for a:visited style Or try to give this style in your css.

A: Try being more specific with your CSS:
footer p a.magenta {
    color: #7abbb8;
}

or you could always set the color directly :
(function($) {
    $('footer p').hover(function() {
        $(this).find('a').css('color', '#7abbb8');
    });
})(jQuery);

and make sure you target the right element, and that would be the element that actually contains the text you are trying to change.


text:
Q: File System Object late binding I have problem with File System Object late binding. This is my code:
Dim WordA As Object 'aplikacja programu Word
Dim PlikW As Object 'plik Worda
Dim Nazwa As Object 'obszar Worda ze zdefiniowaną nazwą
Dim Zakres As Range 'zakres danych używany do wiadomości
Dim NrRaportu As Integer 'Numer tworzonego raportu
Dim Katalog As String 'pełna nazwa katalogu, w którym zapisywane są wiadomości
Const Raport_szablon = "Raport_szablon.docx" 'zazwa pliku z szablonem
Dim fso As Object 'Objekt FileSystemObject

'1. Wczytanie danych
Set Zakres = Range("R2:Z" & Cells(Rows.Count, "R").End(xlUp).Row)
Katalog = ThisWorkbook.Path & "\Raporty"
Set fso = CreateObject("FileSystemObject")
If Not fso.FolderExists(Katalog) Then _
    fso.CreateFolder (Katalog)

and I get a message that

"ActiceX component can't create object"

.

A: You need also to use the reference manger and add the dll / ocx to the project. c:\windows\system32\wshom.ocx if i remember right


text:
Q: Change the MIME type in WordPress I am using JW Player plugin from wordpress. I try to upload mp4 file in the admin dashboard -> media
There is nothing problem in the uploading. but when i try to load the video in jw player of wordpress it loads only audio. When i try to upload the file it shows the mime type as
video/quicktime but i uploaded the mp4 file and mime type should be video/mp4 Not sure why this should happen.
Here is the screenshot that i uploaded from my side

How to change the mime type as video/mp4. Is that anything in wordpress or in convertor?
Any one give me a suggestion to overcome this problem
Reg,
vicky

A: To add additional MIME types, in function.php write the below code:
add_filter('upload_mimes', 'add_custom_mime_types');

function add_custom_mime_types($mimes) {
    return array_merge($mimes, array (
        'ac3' => 'audio/ac3',
        'mpa' => 'audio/MPA',
        'flv' => 'video/x-flv',
        'svg' => 'image/svg+xml'
    ));
}

To remove existing MIME types:
add_filter('upload_mimes', 'remove_mime_types');

function remove_mime_types($mimes) {
    unset($mimes['mp4']);
}

A: You can also add the video/mp4 mime type via .htaccess
Sample:
<IfModule mod_rewrite.c>
  AddType video/ogg .ogv
  AddType video/webm .webm
  AddType video/mp4 .mp4
</IfModule>


text:
Q: Improve file transfer speed between Windows PCs and servers I've setup a server which I've connected to multiple PCs in my workplace. Sadly, data transfer speeds are at max 3 MB/sec per connection which works out slow for file transfers, especially when transferring large files. I'm using Windows filesharing and the server is a Windows Server 2008 (2 Ghz CPU, 1 GB RAM) and the client PCs mostly running Windows 7. How can I detect bottlenecks in my network and improve file sharing speed within the network?

A: Hoping the Windows Server 2008 is "Server 2008 r2".  Can understand a limitation of moving to "r2" requires 64bit OS & CPU.  Immediately noticing server has 1GB RAM, which would be low for a server.  2GHz CPU is ambiguous, for instance a 2GHz P4 versus a 2GHz Xeon E5-2650  would be a 50 fold performance difference.  State of storage is not known, such as where the OS and fileshares reside physically and logically to the server.
From Microsoft:
http://technet.microsoft.com/en-us/windowsserver/bb414778.aspx
Hence, main concern would be the health and viability of the server before moving to physical and logical network components (switch, cables, VLANs, QoS, bandwidth, noise, etc).
Performance tuning instantiates with obtaining a local server baseline.  To get started, and better form a basis of the sever situation, do check these solid guides for Server 2008's own Performance Monitor.  It is a big topic, an overview:

*

*http://www.petri.co.il/performance-monitoring-easy-way-part-1.htm

*http://www.petri.co.il/performance-monitoring-easy-way-part-2.htm

*http://www.petri.co.il/performance-monitoring-easy-way-part-3.htm

*http://www.petri.co.il/performance-monitoring-easy-way-part-4.htm

A: By doing some basic analytics:

*

*consult the network map for slow devices (hubs)

*see if other devices are also on the network that are using bandwidth

*see if how much IO, cpu and memory is being used on the server while doing transfers

*see how much IO, cpu and memory is being used by the desktops

*see if there are any bandwidth shaping rules in place


text:
Q: How to know that the root view controller view hierarchy has finished loading Hi I have a UINavigationController I initialise it with a rootViewController I want to receive a call back after the rootViewController view hierarchy has completed loaded.
Currently, I am using protocol to achieve the same i.e.
I have a protocol named LoadedInitialViewController
Which defines a function as
func didFinishLoading()

When the root view controller has completed loading in viewWillAppear I call
self.delegate.didFinishLoading

The navigation controller receives this call and carrier out the operation I need. Although this works I was wondering if there are any navigation controller delegate provided methods that can help me achieve the same?

A: Give the UINavigationController a delegate, and in that delegate implement navigationController(_:didShow:animated:).


text:
Q: Reading File from directory I am doing some preprocessing, and after I am trying to open a file that has floats within the file name but I get a ValueError: invalid literal for int() with base 10: 'output_patch_fp' and I do not know why. Can anyone help? Code is below:
    out_blob = next(iter(net.outputs))
net.batch_size = len(args.input)

# Read and pre-process input images
n, c, h, w = net.inputs[input_blob].shape
images = np.ndarray(shape=(n, c, h, w))
for i in range(n):
    image = cv2.imread(args.input[i])
    if image.shape[:-1] != (h, w):
        log.warning("Image {} is resized from {} to {}".format(args.input[i], image.shape[:-1], (h, w)))
        image = cv2.resize(image, (w, h))
    # Swapping Red and Blue channels
    #image[:, :, [0, 2]] = image[:, :, [2, 0]]
    # Change data layout from HWC to CHW
    image = image.transpose((2, 0, 1))
    images[i] = image

    eoim = image
    eoim16 = eoim.astype(np.float16)

    # divide by 255 to get value in range 0->1 if necessary (depends on input pixel format)
    if(eoim16.max()>1.0):
        eoim16 = np.divide(eoim16,255)
        print(eoim16)

preprocessed_image_path = 'C:/Users/Owner/Desktop/Ubotica/IOD/cloud_detect/'
formated_image_file = "output_patch_fp"
f = open(preprocessed_image_path + "/" + formated_image_file + ".txt", 'r')
elem_counter = 0
for elem in eoim16:
    for elem1 in elem:
        for col in elem1:
            #f.read(int(float(formated_image_file)))
            f.read(float(f.readline())
f.close()

# calling the instance method using the object cloudDetector
res = cloudDetector.infer(eoim16)
res = res[out_blob]

labels_map = None
classid_str = "classid"
probability_str = "probability"
for i, probs in enumerate(res):
    probs = np.squeeze(probs)
    top_ind = np.argsort(probs)[-args.number_top:][::-1]
    print("Image {}\n".format(args.input[i]))
    print(classid_str, probability_str)
    print("{} {}".format('-' * len(classid_str), '-' * len(probability_str)))
    for id in top_ind:
        det_label = labels_map[id] if labels_map else "{}".format(id)
        label_length = len(det_label)
        space_num_before = (len(classid_str) - label_length) // 2
        space_num_after = len(classid_str) - (space_num_before + label_length) + 2
        space_num_before_prob = (len(probability_str) - len(str(probs[id]))) // 2
        print("{}{}{}{}{:.7f}".format(' ' * space_num_before, det_label,
                                      ' ' * space_num_after, ' ' * space_num_before_prob,
                                      probs[id]))
    print("\n")

The .txt file with the raw float data is followed below:
0.56494140625
0.521484375
0.56884765625
0.537109375
0.57666015625
0.64306640625
0.7841796875
0.7021484375
0.6982421875
0.6943359375
0.67431640625
0.7490234375
0.61181640625
0.65869140625

A: It's not necessary to call f.read(). f.readline() read the line from the file, and float() converts it to a float. The code should be something like this:
for elem in eoim16:
    for elem1 in elem:
        for col in elem1:
            val = float(f.readline())
            # now do something with val


text:
Q: How to get Retail (4-5-4) Calendar Week of Month from a date I need to get the 4-5-4 Calendar Week from a Date. Is there any utility like Georgian Calendar in Java for 4-5-4 Retail Calendar?
If not, how can I create one? What all logic is needed? What is 53rd Week in case of Leap Year?
For example, if I pass a date (DD-MM-YYY) 04-03-2018 as input I should get March Week 1 as output.
Or, if I give 01-04-2018 as input I should get March Week 5 as output.
Please help me by providing a way to build this utility.

A: The following class should do it:
public class NrfMonthWeek {

    public static NrfMonthWeek getWeek(LocalDate date) {
        // Determine NRF calendar year.
        // The year begins on the Sunday in the interval Jan 29 through Feb 4.
        LocalDate firstDayOfNrfYear = date.with(MonthDay.of(Month.JANUARY, 29))
                .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        if (date.isBefore(firstDayOfNrfYear)) { // previous NRF year
            firstDayOfNrfYear = date.minusYears(1)
                    .with(MonthDay.of(Month.JANUARY, 29))
                    .with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY));
        }
        // 1-based week of NRF year
        int weekOfNrfYear = (int) ChronoUnit.WEEKS.between(firstDayOfNrfYear, date) + 1;
        assert 1 <= weekOfNrfYear && weekOfNrfYear <= 53 : weekOfNrfYear;
        YearMonth firstMonthOfNrfYear = YearMonth.from(firstDayOfNrfYear)
                .with(Month.FEBRUARY);
        if (weekOfNrfYear == 53) {
            // Special case: the last week of a 53 weeks year belongs to
            // the last month, January; this makes it a 5 weeks month.
            return new NrfMonthWeek(firstMonthOfNrfYear.plusMonths(11), 5);
        } else {
            // 1-based month of NRF year (1 = February through 12 = January).
            // A little math trickery to make the 4-5-4 pattern real.
            int monthOfNrfYear = (weekOfNrfYear * 3 + 11) / 13;
            // Number of weeks before the NRF month: 0 for February, 4 for March, 9 for April, etc.
            int weeksBeforeMonth = (monthOfNrfYear * 13 - 12) / 3;
            int weekOfMonth = weekOfNrfYear - weeksBeforeMonth;
            return new NrfMonthWeek(
                    firstMonthOfNrfYear.plusMonths(monthOfNrfYear - 1), weekOfMonth);
        }
    }

    private YearMonth month;
    /** 1 through 5 */
    private int weekOfMonth;

    public NrfMonthWeek(YearMonth month, int weekOfMonth) {
        this.month = Objects.requireNonNull(month);
        if (weekOfMonth < 1 || weekOfMonth > 5) {
            throw new IllegalArgumentException("Incorrect week number " + weekOfMonth);
        }
        this.weekOfMonth = weekOfMonth;
    }

    @Override
    public String toString() {
        return month.getMonth().getDisplayName(TextStyle.FULL, Locale.US)
                + " Week " + weekOfMonth;
    }
}

Let's try it. Here I pass the two dates from your question to the getWeek method:
    System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.MARCH, 4)));
    System.out.println(NrfMonthWeek.getWeek(LocalDate.of(2018, Month.APRIL, 1)));

This prints the desired:
March Week 1
March Week 5

Though only month and week are printed, also the year is contained in the object returned from getWeek.
The formulas for calculating the month and week-of-month are cryptic. I have no really good argument why they work, though such an argument could probably be constructed. I have tested them with all relevant values, and you are free to do the same. Other than that, using java.time, the modern Java date and time API, it wasn't too bad.
If that were me, I would have finer validation in the NrfMonthWeek constructor, only allowing week 5 in the months that may have 5 weeks. I am leaving that to you. And I would have a pretty thorough unit test.
Please check whether my understanding agrees with yours: If I have understood correctly from the example calendars that Basil Bourque linked to in his answer, the NRF 4-5-4 year starts with February. Its weeks begin on Sunday, and the first week of the year is the first week that contains at least 4 days of February. In other words, the week that contains February 4. In yet other words, the week that begins on a Sunday in the interval January 29 through February 4. Months March, June, September and December always have 5 weeks. In case of a 53 weeks year also January has 5 weeks.

A: No support built-in
Neither the modern java.time classes nor the legacy date-time classes (Date/Calendar) directly support the National Retail Federation 4-5-4 Calendar.
Implement Chronology
I suspect the best way to solve this problem is to implement a Chronology for the java.time framework.
Java 8 and later bundle five implementations (HijrahChronology, IsoChronology, JapaneseChronology, MinguoChronology, ThaiBuddhistChronology). Their source is available in the OpenJDK project.
The ThreeTen-Extra project provides ten more chronologies (AccountingChronology, BritishCutoverChronology, CopticChronology, DiscordianChronology, EthiopicChronology, InternationalFixedChronology, JulianChronology, PaxChronology, Symmetry010Chronology, Symmetry454Chronology) whose source code might help.


text:
Q: The best paper from/at/of A When describing a person who is awarded the best paper, what preposition should be used? It would be great with the explanation why.

*

*"He is awarded the best paper from conference A?"

*"He is awarded the best paper at conference A?"

*"He is awarded the best paper of conference A?

A: At would probably be the most natural sounding. Of would work as well, but might be less common. From sounds odd, but would be understood.
Also, the present passive doesn't seem like it would be the right tense here. It would more likely be the past passive:

He was awarded the best paper at conference A

"awarded" is a completed action, but the present passive tends to indicate ongoing, repeated or habitual actions. For example,

He is awarded the best paper at this conference every year.


text:
Q: vscode debugger unexpected toke 'import' I am new to nodejs and vscode...... I have two files: entry.js and /utils/database.js.
When I run node entry.js I get the little logging that I expect(SSSS). I would like to run this in debug mode so that I can build on it but when I click on the "Run" in debug on the left side I get:

SyntaxError: Unexpected token import

*

*System: Ubuntu 18.04

*Editor: Visual Studio Code version 1.45.1

*node --version: v13.11.0

*npm --version: 6.13.7

package.json:
{
  "type": "module",
  "name": "node_load_test",
  "version": "1.0.0",
  "description": "",
  "main": "entry.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mysql": "^2.18.1"
  }
}

launch.json:
{
  // Use IntelliSense to learn about possible attributes.
  // Hover to view descriptions of existing attributes.
  // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
  "version": "0.2.0",
  "configurations": [
    {
      "type": "node",
      "request": "launch",
      "name": "Launch root Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/entry.js"
    },
    {
      "type": "node",
      "request": "launch",
      "name": "Launch 6 Program",
      "skipFiles": ["<node_internals>/**"],
      "program": "${workspaceFolder}/6/entry.js"
    }
  ]
}

utils/database.js:
import mysql from "mysql";

export const pool = mysql.createPool({
  connectionLimit: 100,
  host: "localhost",
  user: "root",
  password: "password",
  database: "no_replicate",
});

entry.js:
"use strict";

import { pool } from "./utils/database.js";

pool.end(function (err) {
  if (err) {
    return console.log("error:" + err.message);
  }
  console.log("Close the database connection.");
});

pool.getConnection(function (err, connection) {
  // execute query
  // ...
  console.log("SSSS");
});

Any help would make my day. Thanks

A: in utils/database.js:
const mysql = require("mysql");

const pool = mysql.createPool({
  connectionLimit: 100,
  host: "localhost",
  user: "root",
  password: "password",
  database: "no_replicate",
});
module.exports = pool

in entry.js
const pool = require('./utils/database.js');

pool.end(function (err) {
  if (err) {
    return console.log("error:" + err.message);
  }
  console.log("Close the database connection.");
});

pool.getConnection(function (err, connection) {
  // execute query
  // ...
  console.log("SSSS");
});

and in Nodejs we import like with require('package-name')


text:
Q: Dropdown menu is overlapping to other menu If I click on "Human Resource" link dropdown will appear, Client wants full width menu but dropdown is overlapping on 2nd row menus and I want if dropdown is open 2nd row will slide down.
HTML

Human Resource

 Human Resource

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

IT

 IT

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Finance

 Finance

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Freight

 Freight

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Administration

 Administration

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Design

 Design

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

CSS
.eservices-list-menu {
    position: relative;
}

.el-menu-holder {
    position: static;
}

.el-menu-holder .dropdown-menu {
    left: 12px;
    right: 12px;
    margin-top: -9px;
    padding: 0 0 10px;
}

.el-menu-holder .dropdown-menu:after {
    content: none;
}

.el-menu-holder .dropdown-menu .title {
    background-color: #936dab;
    font-size: 18px;
    color: #fff;
    display: block;
    padding: 5px 10px;
}

.el-menu-holder .dropdown-menu li {
    margin-top: 0;
    width: 25%;
    float: left;
}

.el-menu-holder .dropdown-menu li a {
    background-repeat: no-repeat;
    background-position: 95% center;
    background-color: #ebebeb;
    display: block;
    margin: 10px 11px 0;
    height: 50px;
    line-height: 51px;
    padding: 0 13px;
    color: #936dab;
    font-size: 15px;
    position: relative;
}

.el-menu-holder .dropdown-menu li a:hover {
    text-decoration: none;
    background-color: #d9d9d9;
}

.el-menu-holder .dropdown-menu li a:after {
    background-color: #936dab;
    height: 2px;
    position: absolute;
    width: 100%;
    bottom: -1px;
    left: 0;
    right: 0;
    content: "";
}

JQuery
$(".eservices-holder").click(function () {
        $(this).parent().children(".dropdown-menu").slideToggle(300);
        $(this).parent().siblings().children(".dropdown-menu").slideUp(300);
        $(this).parent().parent().siblings(".row").children().children(".dropdown-menu").slideUp(300);
    });

Here is Codepen LINK.
I'm sorry in advance if I'm not clear to you guys.
Thanks in advance.

A: Add style for ul, i.e from
.el-menu-holder .dropdown-menu {
left: 12px;
right: 12px;
margin-top: -9px;
padding: 0 0 10px;

}

to
.el-menu-holder .dropdown-menu {
left: 12px;
right: 12px;
margin-top: -9px;
padding: 0 0 10px;
position:relative;
}

A: Partial solution:
The Html changes are

Human Resource

 Human Resource

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

IT

 IT

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Finance

 Finance

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Freight

 Freight

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Administration

 Administration

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Design

 Design

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Title Goes here

Css changes are
        .eservices-list-menu {
        position: relative;
    }

    .el-menu-holder {
        position: static;
    }

    .el-menu-holder .dropdown-menu {
        left: 12px;
        right: 12px;
        margin-top: -9px;
        padding: 0 0 10px;
      position:relative;
      min-width:100vw;
    }

    .el-menu-holder .dropdown-menu:after {
        content: none;
    }

    .el-menu-holder .dropdown-menu .title {
        background-color: #936dab;
        font-size: 18px;
        color: #fff;
        display: block;
        padding: 5px 10px;
    }

    .el-menu-holder .dropdown-menu li {
        margin-top: 0;
        width: 25%;
        float: left;
    }

    .el-menu-holder .dropdown-menu li a {
        background-repeat: no-repeat;
        background-position: 95% center;
        background-color: #ebebeb;
        display: block;
        margin: 10px 11px 0;
        height: 50px;
        line-height: 51px;
        padding: 0 13px;
        color: #936dab;
        font-size: 15px;
        position: relative;
    }

    .el-menu-holder .dropdown-menu li a:hover {
        text-decoration: none;
        background-color: #d9d9d9;
    }

    .el-menu-holder .dropdown-menu li a:after {
        background-color: #936dab;
        height: 2px;
        position: absolute;
        width: 100%;
        bottom: -1px;
        left: 0;
        right: 0;
        content: "";
    }

The javascript changes are
    $(".eservices-holder").click(function () {
        var content = $(this).parent().children(".dropdown-menu");
         $(this).parent().parent().find(".content").html(content.html());
        $(this).parent().siblings().children(".dropdown-menu").slideUp(300);
        $(this).parent().parent().siblings(".row").children().children(".dropdown-menu").slideUp(300);
    });