text:
Q: Time series fitting: use of 'trend' in VAR models via statsmodels.tsa.vector_ar.var_model.VAR I'm using the statsmodels.tsa.vector_ar.var_model.VAR package to fit some bivariate time series. That is, time series of vectors with 2 components: (x1, y1)T, ..., (xN, yN)T.
However, I do not understand how to use the parameter trend in the VAR.fit() function. There are 4 possible values for that parameter ({"c", "ct", "ctt", "n"}) and the explanation given in the doc is: "c" - add constant "ct" - constant and trend "ctt" - constant, linear and quadratic trend "n" - co constant, no trend Note that these are prepended to the columns of the dataset.
What I understand is that the trend parameter allows to perform some pre-processing steps on the time series, before fitting the VAR model. In particular, I expect that, when trend is:

*

*n: the VAR model yt = A1 yt-1 + ... + Ap yt-p is fitted on the series as it is;

*c: the mean of the series is removed before the fit. So, defining mu_x =  np.mean(x) and mu_y = np.mean(y) the mean values of the univariate series, the VAR model is fitted on the new series: (xi - mu_x, yi - mu_y)i=1,...,N;

*ct: the VAR model is fitted on the series where the linear trend has been removed: (xi - a - b * i, yi - c - d * i)i=1,...,N;

*ctt: the VAR model is fitted on the series where the quadratic trend has been removed: (xi - m - n * i - p* i2, yi - q - r * i - s* i2)i=1,...,N.

However, this is not what results from some attempts. Here after my code with a few examples.
1) I define a bivariate time series ts0 and, from that, 2 other transformed time series:

*

*ts1: computed from ts0 by subtracting the mean;

*ts2: compuetd from ts1 by removing the linear trend.

### original bivariate time series
ts0 = np.array([[-2.27390781,  4.89021106],
               [ 0.56894665,  1.57356924],
               [-1.54000883, -1.97090661],
               [ 0.60917182,  0.3684891 ],
               [-2.518067  ,  0.42002855],
               [-0.4788302 , -0.63284219],
               [ 1.8208968 ,  2.27831329],
               [-1.65226058, -2.6647208 ],
               [ 0.72437619,  1.09676352],
               [-3.190304  , -0.48445386],
               [ 0.41290842,  1.01441648]])
N = np.shape(ts0)[0]                                           # number of time steps

### pre-processing of the time series by hand:
#   remove the mean values
ts1 = ts0 - np.mean(ts0,axis=0)                                # translated time series
#   remove the linear trend
time = np.arange(N)
b,d = (np.cov(time,ts1[:,0],ddof=1)[0,1]/np.var(time,ddof=1),
       np.cov(time,ts1[:,1],ddof=1)[0,1]/np.var(time,ddof=1))  # ang. coef
a,c = (np.mean(ts1[:,0]) - b*np.mean(time),
       np.mean(ts1[:,1]) - d*np.mean(time))                    # intercept
x_lin,y_lin = ([a+b*i for i in time], [c+d*i for i in time])   # linear predictions
ts2 = ts1 - np.transpose([x_lin, y_lin])                       # translated and rotated time series

In the following, I'll forecast the vector N+1 for the three time series, by setting different values for the parameter trend.
2) I expect the forecast for ts2 to return the same result regardeless of trend = n, c, or ct. This is not true:
### fit the series ts2
lag = 1
var_2 = VAR(pd.DataFrame(data=ts2))
var_2n = var_2.fit(lag, trend='n')                       # 3 fits
var_2c = var_2.fit(lag, trend='c')
var_2ct = var_2.fit(lag, trend='ct')
pred_2n = var_2n.forecast(y=ts2[-lag:,:], steps=1)[0]    # 3 predictions
pred_2c = var_2c.forecast(y=ts2[-lag:,:], steps=1)[0]
pred_2ct = var_2ct.forecast(y=ts2[-lag:,:], steps=1)[0]

### plot
fig, axs = plt.subplots(1,2,figsize=(12,3))

# coord x
ax = axs[0]
ax.plot(time, ts2[:,0])
ax.hlines(xmin=time[0], xmax=time[-1], y=np.mean(ts2[:,0]), color='g', label='linear fit')
ax.scatter(N, pred_2n[0], marker='x', c='salmon', label='VAR(ts2, trend=n)')
ax.scatter(N, pred_2c[0], marker='D', c='orange', label='VAR(ts2, trend=c)', alpha=0.5)
ax.scatter(N, pred_2ct[0], marker='.', c='k', label='VAR(ts2, trend=ct)', alpha=0.5)
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('ts2: coord x')
ax.legend(loc='lower left')

# coord y
ax = axs[1]
ax.plot(time, ts2[:,1])
ax.hlines(xmin=time[0], xmax=time[-1], y=np.mean(ts2[:,1]), color='g', label='linear fit')
ax.scatter(N, pred_2n[1], marker='x', c='salmon')
ax.scatter(N, pred_2c[1], marker='D', c='orange')
ax.scatter(N, pred_2ct[1], marker='.', c='k')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('ts2: coord y')

fig.tight_layout()

enter image description here
3) I expect to get the same prediction when:

*

*I fit the ts2 series with trend=n and I transform back the points on the ts1 series;

*I fit the ts1 series with trend=c.

This is not true:
### compute predictions
pred_2n_backto_1 = np.array([a,c]) + np.array([b,d])*N + pred_2n   # prediction VAR(ts2, trend=n) back to ts1
var_1 = VAR(pd.DataFrame(data=ts1))                                # prediction VAR(ts1, trend=c)
var_1c = var_1.fit(lag, trend='c')
pred_1c = var_1c.forecast(y=ts1[-lag:,:], steps=1)[0]

### plot
fig, axs = plt.subplots(1,2,figsize=(12,3))

# coord x
ax = axs[0]
ax.plot(time, ts1[:,0])
ax.plot(time, x_lin, c='g', label='linear fit')
ax.scatter(N, pred_2n_backto_1[0], marker='x', c='salmon', label='VAR(ts2, trend=n) back to ts1')
ax.scatter(N, pred_1c[0], marker='o', c='b', alpha=0.5, label='VAR(ts1, trend=c)')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('ts1: coord x')
ax.legend(loc='lower left')

# coord y
ax = axs[1]
ax.plot(time, ts1[:,1])
ax.plot(time, y_lin, c='g', label='linear fit')
ax.scatter(N, pred_2n_backto_1[1], marker='x', c='salmon', label='VAR(ts2, trend=n) back to ts1')
ax.scatter(N, pred_1c[1], marker='o', c='b', alpha=0.5, label='VAR(ts1, trend=c)')
ax.grid(True)
ax.set_xlabel('time')
ax.set_ylabel('ts1: coord y')

fig.tight_layout()

enter image description here
4) More general investigation:

*

*I compute predictions for the 3 series (ts0, ts1, ts2), with trend={n, c, ct};

*I transform back those values through the pre-processing steps, in order to have all the predictions on the ts0 series;

*I compare the 9 predictions.

I find that only some predictions are equals, but I don't understand the logic behind. In particular:

*

*VAR(ts2, trend='ct'), VAR(ts1, trend='ct') and VAR(ts0, trend='ct') return the same predictions;

*VAR(ts1, trend='c') and VAR(ts0, trend='c') also return the same predictions.

# pre-processing parameters
intercepts = np.array([a,c])
ang_coefs = np.array([b,d])
mean_ts0 = np.mean(ts0, axis=0)

# predictions for ts2 back to ts0
pred_2n_backto_0 = (intercepts + ang_coefs*N + pred_2n) + mean_ts0
pred_2c_backto_0 = (intercepts + ang_coefs*N + pred_2c) + mean_ts0
pred_2ct_backto_0 = (intercepts + ang_coefs*N + pred_2ct) + mean_ts0

# predictions for ts1 back to ts0
var_1 = VAR(pd.DataFrame(data=ts1))
var_1n = var_1.fit(lag, trend='n')
var_1c = var_1.fit(lag, trend='c')
var_1ct = var_1.fit(lag, trend='ct')
pred_1n = var_1n.forecast(y=ts1[-lag:,:], steps=1)[0]
pred_1c = var_1c.forecast(y=ts1[-lag:,:], steps=1)[0]
pred_1ct = var_1ct.forecast(y=ts1[-lag:,:], steps=1)[0]
pred_1n_backto_0 = pred_1n + mean_ts0
pred_1c_backto_0 = pred_1c + mean_ts0
pred_1ct_backto_0 = pred_1ct + mean_ts0

# predictions for ts0
var_0 = VAR(pd.DataFrame(data=ts0))
var_0n = var_0.fit(lag, trend='n')
var_0c = var_0.fit(lag, trend='c')
var_0ct = var_0.fit(lag, trend='ct')
pred_0n = var_0n.forecast(y=ts0[-lag:,:], steps=1)[0]
pred_0c = var_0c.forecast(y=ts0[-lag:,:], steps=1)[0]
pred_0ct = var_0ct.forecast(y=ts0[-lag:,:], steps=1)[0]

# compare predictions
list_pred_x = [pred_2n_backto_0[0], pred_2c_backto_0[0], pred_2ct_backto_0[0],
              pred_1n_backto_0[0], pred_1c_backto_0[0], pred_1ct_backto_0[0],
              pred_0n[0], pred_0c[0], pred_0ct[0]]
list_pred_y = [pred_2n_backto_0[1], pred_2c_backto_0[1], pred_2ct_backto_0[1],
              pred_1n_backto_0[1], pred_1c_backto_0[1], pred_1ct_backto_0[1],
              pred_0n[1], pred_0c[1], pred_0ct[1]]
list_labels = ['pred_2n_backto_0', 'pred_2c_backto_0', 'pred_2ct_backto_0',
              'pred_1n_backto_0', 'pred_1c_backto_0', 'pred_1ct_backto_0',
              'pred_0n', 'pred_0c', 'pred_0ct']

mat_x = mat_y = np.zeros((9,9))
for i in range(9):
    x_i = list_pred_x[i]
    y_i = list_pred_y[i]
    for j in range(9):
        x_j = list_pred_x[j]
        y_j = list_pred_y[j]
        mat_x[i,j] = np.log(np.fabs(x_i - x_j))
        mat_y[i,j] = np.log(np.fabs(y_i - y_j))

fig = plt.figure(figsize=(16,5))
plt.subplot(1,2,1)
plt.imshow(mat_x, cmap='plasma')
plt.colorbar()
plt.title('predictions for coord x:' + '\n' + r'$val_{ij} = log(|pred_i - pred_j|)$')
plt.xticks(np.arange(9), list_labels, rotation=90)
plt.yticks(np.arange(9), list_labels)

plt.subplot(1,2,2)
plt.imshow(mat_y, cmap='plasma')
plt.colorbar()
plt.title('predictions for coord y:' + '\n' + r'$val_{ij} = log(|pred_i - pred_j|)$')
plt.xticks(np.arange(9), list_labels, rotation=90)
plt.yticks(np.arange(9), list_labels)

plt.show()

enter image description here
Could someone explain to me the logic of the trend parameter in the statsmodels.tsa.vector_ar.var_model.VAR package ?
Thank you in advance :)


text:
Q: How can get string which seprated by delimeted symbol ( | ) in text file using java? I having test file in my java project directory which having below content:
HEADER|INPUT|2017|test|1
|Id|Name|
From where I want to update " Id " value from another string "xyz"
"ID" is not static everytime this value gets changed
How can I get particular string using java?

A: You can use the split function. This will return your string split into the parts, seperated by |.
var result = "HEADER|INPUT|2017|test|1 |Id|Name|".split("\\|");
// Access an array
// result[0] will be 'Header'

Source

A: You can use String.split() function:
String string = "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] parts = string.split("\\|");
String part1 = parts[0]; // HEADER
String part2 = parts[1]; // INPUT
String part3=parts[2]; //2017

and so on.

A: You can make use of split() method here to divide your string as per your requirement.
String input= "HEADER|INPUT|2017|test|1 |Id|Name|";
String[] contents = input.split("\\|");
String name = input[6];
String id = input[5];
String number = input[4];
String test = input[3];
String year = input[2];
String input = input[1];
String header = input[0];

For more on String.split()

redpajama_set_name: RedPajamaStackExchange


text:
Q: Less expensive way of converting a double[] to an immutable list I want to convert an array double[] to an immutable collection for use in a value object. However, I am dealing with a very large array and I keep getting the error java.lang.OutOfMemoryError: Java heap space.
I am currently using
Collections.unmodifiableList(DoubleStream.of(myArray).boxed().collect(Collectors.toList()));

I think it is because of this my program is running out of memory. Is there a cheaper way to convert double[] to an immutable list?

A: How about creating your own List<Double>? If you implement AbstractList<Double>, you'd only need to implement two methods for an unmodifiable list:
class MyDoubleList extends AbstractList<Double> implements RandomAccess {

    private double[] backingArray;

    public MyDoubleList(double[] backingArray) {
        this.backingArray = backingArray;
    }

    @Override
    public Double get(int index) {
        return backingArray[index];
    }

    @Override
    public int size() {
        return backingArray.length;
    }

    // adding other list methods should be trivial...
}

Usage:
List<Double> list = new MyDoubleList(myBigDoubleArray);

Note that if you change the backing array, the list contents will change as well. To prevent this, you'd usually copy the array passed in, but since copying the array will probably cause an out of memory exception, I didn't do it.

Or if you use Guava, use Doubles.asList(myBigDoubleArray), which does essentially the same thing. Thanks to Joe for the suggestion!

A: Streams are great for functional programming, and readability but should be avoided when performance is the main concern. They create unnecessary extra objects.
Also surprisingly, arrays of the double primitive types consume more memory than their wrapper class Double arrays (ref: https://www.baeldung.com/java-primitives-vs-objects)
Use a Double object array instead of a double primitive, and then run:
Collection<Double> l = Collections.unmodifiableCollection(Arrays.asList(myArray));

I compared the 2 approaches like this
    public static void main(String[] args) {
        int len = 1000000;
        Double[] myArray = new Double[len];
        for (int i = 0; i < len; i++) {
            myArray[i] = Math.random();
        }
        Collection<Double> l = Collections.unmodifiableCollection(Arrays.asList(myArray));
        long totalMem = Runtime.getRuntime().totalMemory();
        long usedMem =  totalMem - Runtime.getRuntime().freeMemory();
        System.out.println("totalMem="+humanReadableByteCountBin(totalMem));
        System.out.println("usedMem=" + humanReadableByteCountBin(usedMem));
        System.out.println("l has " + l.size() + " items ");
    }

The stream approach used 48Mb, whereas Arrays.asList with Double uses 28Mb.


text:
Q: What is the best way to drop a table & remove a model in Rails 3? I have a model & a table which I no longer need in my App, I could leave them there but I would like to remove them to keep things tidy.
I'm trying to figure out the best way to remove them with out messing around with my migrations & db/schema.rb files & any side effect it could have on my production environment, my app is on Heroku.  I'm using PostgreSQL on both my local machine & heroku.
So far I've found two ways to do this but am not sure which is the best method/ rails way?
Method 1
I thought about just going in to my database & dropping the table & then destroying the model.
rails db
DROP TABLE table_name
\q
rails destroy model model_name

If I do this what will happen to the migrations I have for this model/table?  I have two migrations for this model, a timestamp_create_modelname & a add_attribute_to_table name.
Also will this method update the db/schema.rb file?
When I push the App to Heroku I suspect the Model will be removed but the table will remain in place, is there a heroku command to drop a table.
Method Two
Another way I read about was to generate a new migration to drop the table & then destroy the model.
rails generate migration drop_tablename

& then update the below file:
db/migrate/timestamp_drop_tablename (updated in response to Dan Wich's answer below)
class DropTablename < ActiveRecord::Migration
  def up
    drop_table :tablename
  end

  def down
    create_table :tablename do |t|
      t.string :table_column
      t.references :anothertable

      t.timestamps
    end
    add_index :tablenames, :anothertable_id
  end
end

& then in the terminal:
rake db:migrate
rails destroy model model_name
rake db:migrate
git add .
git commit -m "removed table/model_name"
git push heroku master
heroku run rake db:migrate
heroku restart

This seems to be the best method but what happens to the older migration files?  Will they remain & update db/schema every time I run rake db:migrate only to be overridden by db/migrate/timestamp_drop_tablename?
I'm happy to experiment with the second method but would like someone with someone with experience to weigh in & tell me the rails ways for doing this.

A: The second method is the ideal way to handle this: your migration files are meant to represent how your database has changed over time. The older migration files will remain in your project (in case, hypothetically, you wanted to roll back to an older version), but Rails will not run them when you rake db:migrate because it knows they've already been run (based on data in the database's schema_migrations table).
Your schema.rb will just be updated once to reflect that your database no longer contains that table.
One minor tweak to your code: your migration file should drop the table in the up method, and ideally recreate it in the down method. The "up" signifies that your migration drops the table to move forward in time, and if the migration is rolled back, the down method will be run.

A: I know this is an old thread. More often than not, you want to remove not only the model, but routes, controller and views associated with that model as well. To do that, run these
rails g migration DropYourModel
rails destroy scaffold YourModelName

Edit your migration file to drop_table and then run
rake db:migrate

If the model happens to be defined in a namespace, e.g., admins, replace the first command with
rails destroy scaffold admins/YourModelName


text:
Q: Cannot accsess array of objects inside same class? Ive got this kinda stupid exam question in which I'm told to make an array of objects IN MAIN method.
I defined the class Account with two variables - String owner and double amount.
Then I'm told to make the Account class handle change of values sum of all amounts. etc.
But I cant figure out what I'm doing wrong - I cannot get access to the array from getAmount().
public static void main(String[] args)
{
    Account[] account = new Account[10];
    for ( int i=0; i<account.length; i++)
    {
    account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0)); //<- dont work,  but works with account[0].amount
}

public static double getAmount(int x)
{
    double s = account[x].amount;   //<<------- CANNOT FIND SYMBOL
    return s;
}

A: account is local to the main method, so it can't be accessed from other methods unless passed to them as a parameter.
An alternative is to declare it as a static member:
static Account[] account = new Account[10];

public static void main(String[] args)
{
    for ( int i=0; i<account.length; i++)
    {
        account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0));
}

A: In this case account is a local variable for main, if you want to use the method getAmount you have two options:
-Declare the array as static and put it out of the main method (the array would be a global variable)
-Pass the array as a parameter in getAmount.
public static void main(String[] args)
{
    Account[] account = new Account[10];
    for ( int i=0; i<account.length; i++)
    {
    account[i]=new Account();
    }
    account[0].owner = "Thomas";
    account[0].amount = 24325;
    System.out.println(getAmount(0), account); //<- dont work,  but works with account[0].amount
}
public static double getAmount(int x, Account[] account)
{
    double s = account[x].amount;   //<<------- CANNOT FIND SYMBOL
    return s;
}


text:
Q: excel number format - varying decimal digits I'm trying to set a special cell number format with theses rules:

*

*display percentage

*display at max 3 digits (decimal + integer part)

So I can display 100% or 99.3% or 1.27%
but not 100.9% or 100.27% or 99.27%.
Of course, I can have negative number (-27.3%) and it does not affect my rules.
I've try with the cell formating option without success:
[<1]0.00%;[<10]0.0%;0%

Because it seemed that excel (2010) does not support more than 2 conditions in cell formating (and so I can't expand it to manage negative number...)
It there anyway to do what I want?
Thanks

A: I have a rather primitive solution by implementing a function in VBA:
Function formatStr(myVal As Double) As String
' the smaller the number, the more digits are to be shown
Dim retStr      As String
Dim absVal      As Double

    absVal = Abs(myVal)

    If absVal >= 100 Then
        retStr = "0"
    ElseIf absVal >= 10 Then retStr = "0.0"
    ElseIf absVal >= 1 Then retStr = "0.00"
    Else ' number is between -1 and 1
        retStr = ".000"
    End If

    formatStr = retStr
End Function

...which can be used then in a VBA statement like this :
   myVal = 0.5555: ActiveSheet.Cells(27, 4).Value = Format(myVal, formatStr(myVal))

if you want to use that in a sheets cell you need another little function
  Function FormatAlignDigits(myVal As Double) As Double
     FormatAlignDigits = Format(myVal, formatStr(myVal))
  End Function

=> you may enter =FormatAlignDigits(B27) in the cell where you want the result. B27 is the cell with the source data in this example.
My test results:
100.3   =>  100
100.5   =>  101
10.53   =>  10.5
10.55   =>  10.6
1.553   =>  1.55
1.555   =>  1.56
0.5553  =>  0.555
0.5555  =>  0.556
-0.5555 =>  -0.556
-0.5553 =>  -0.555
-1.555  =>  -1.56
-1.553  =>  -1.55
-10.55  =>  -10.6
-10.53  =>  -10.5
-100.5  =>  -101
-100.3  =>  -100
I'm sure there can be a more fancy solution, e.g. with a parameter for function 'formatStr' that tells at which power the number of digits is down to 0 (here: power = 2; meaning if the value is >= 100).
For me this primitive thing works just fine.

A: Under the Home tab in the Ribbon select Conditional Formatting:

and then select either New Rule or Manage Rules (with the latter you can then select New Rule, but also have an overview of all current rules)
Then select Use a formula to determine which cells to format and enter the formula with reference to the cell itself (in my case cell A1 was selected, take the $ signs out to allow it to be applied to other cells themselves as well!):

Now Click Format... and select the required Number format as percentage with the number of decimal places as you want it.
Repeat this for all the cases you want to distinguish.
As values can be negative I use ABS() to always test for the rule on the absolute value of the cell.
Note you can either make all rules apply for a 2 side limited value range (in my example I have the minimum of 0.1 and the maximum of 1 (10% and 100% respectively). Alternatively you can only determine the minimum OR maximum and tick the box for Stof If True at the right end for all your rules involved.

A: I've recently solved this issue but configuring up to 6 decimals. The request is as follows:

We want to display a number same way as entered by the user but
  allowing no more than 6 decimals:

*

*1 -> 1

*1,1 -> 1,1

*1,12 -> 1,12

*...

*1,123456 -> 1,123456

*1,1234567 -> 1,123457 (Round from this point)
This can be solved using conditional formatting and one rule per decimal starting from integers. An integer is a number without decimals, so X MOD 1 = 0. We can apply this logic multiplying the number by 10^N being N the number of decimals we want. Besides, we want to stop applying rules when we have detected the number of decimals in the cell value, so be sure you mark "Stop if True" flag and that the order of the rules is from the most restrictive one (the integer) to the less restrictive (the one that stands for the maximum number of decimals allowed).
Summarizing, you have to configure the following way (in the sample I'm doing for B column):

*

*INTEGER: =MOD(B2;1)=0

*ONE DECIMAL: =MOD(B2*10;1)=0

*TWO DECIMALS: =MOD(B2*100;1)=0

*...

*SIX DECIMALS: =MOD(B2*1000000;1)=0

Also set the default format of the cell to be a number with the maximum number of supported decimals:

And finally the working results on Excel:


text:
Q: Mac OSX 10.6 leaves open files on Windows Server We've got several Mac OS X 10.6 clients who connect to our Windows 2000 & 2003 File Servers - No Active Dir, just file shares.
I'm finding that the Mac clients keep lots of connections open on our server, even when they have no files open.  My tests show that just browsing the folders using Finder keeps all of the folders open.  Windows "Computer Management" shows these sessions with 15-20 open files, and these are causing us to reach our connection limit and locking down the server.
I've disabled the creation of DS_Store, thinking that was the problem, but it was not.
Also, tried disabling named streams - no luck.
I ran a test -
A Mac client browsed to a folder called "AFolder" with one file called "Program.doc", then navigated to another folder, and recorded the activity with ProcMon on the server (W2K):
http://www.thelifechurch.com/pete/10.6.jpg
From computer manager, you can see that the folder "D:\Shared\AFolder" is still open, and thus dozens of folders stay open when they browse around (even after closing finder):
http://www.thelifechurch.com/pete/cm.jpg
I tested the same thing with Mac OS X 10.5.7 and it did not have that problem. Here is the ProcMon results:
http://www.thelifechurch.com/pete/10.5.jpg
I'm not too familiar with these file operations, can anyone tell whats causing this?
The best I can tell by comparing the 10.5 and 10.6 logs, is that 10.6 does a
CreateFile D:\Shared\AFolder,
and then never closes it, even after I navigate out to a different folder.  Whereas, 10.5 does close the folder.

A: It could be as simple as Spotlight (the MacOS Search mechanism) is indexing those files once the shares are mounted.  I believe that there is a preference to turn off the indexing of network shares.
I don't have facilities to test right now, but you could try:

*

*Try running mdutil -i off
/path/to/volume to turn off indexing
for the relevant volume.  If that
works you could set it up as a script
to run at startup or login.

*You could also try creating an empty
file called ".metadata_never_index"
and placing that at the root of the
network mount point.  It should
prevent spotlight from indexing the
folder and subfolders (at least under
that mountpoint.)

A: Had similar problem. Lots of opened files o windows server.
The problem was - AVAST antivirus on MacOS. Uninstalling it fixed the problem.


text:
Q: Indexing Julia's DataArrays with included NA values I am wondering why indexing Julia's DataArrays with NA values is not possible.
Excuting the snipped below results in an error(NAException("cannot index an array with a DataArray containing NA values")):
dm = data([1 4 7; 2 5 8; 3 1 9])
dm[dm .== 5] = NA

dm[dm .< 3] = 1  #Error
dm[(!isna(dm)) & (dm .< 3)] = 1  #Working

There is a solutions to ignore NA's in a DataFrame with isna(), like answered here. At a first glance it works like it should and ignoring NA's in DataFrames is the same approach like for the DataArrays, because each column of a DataFrame is a DataArray, stated here. But in my opinion ignoring missing values with !isna() on each condition is not the best solution.
For me it's not clear why the DataFrame Module throws an error if NA's are included. If the boolean Array needed for indexing, has NA's values, this values should convert to false like MATLAB® or Pythons Pandas does. In the DataArray modules sourcecode(shown below) in indexing.jl, there is an explicit function to throw the NAException:
# Indexing with NA throws an error
function Base.to_index(A::DataArray)
    any(A.na) && throw(NAException("cannot index an array with a DataArray containing NA values"))
    Base.to_index(A.data)
end

If you change the snippet by setting the NA's to false ...
# Indexing with NA throws an error
function Base.to_index(A::DataArray)
    A[A.na] = false
    any(A.na) && throw(NAException("cannot index an array with a DataArray containing NA values"))
    Base.to_index(A.data)
end

... dm[dm .< 3] = 1 works like it should(like in MATLAB® or Pandas).
For me it make no sense to automatically throw error if NA's are included on indexing. There should leastwise be a parameter creating the DataArray to let the user choose if NA's are ignored. There are two siginificant reasons: On the one hand it's not very pleasent for writing and reading code, when you have formulas with a lot of indexing and NA values (e.g calculating meteorological grid models) and on the other hand there is a noticeable loss of performance, which this timetest is showing:
@timeit dm[(!isna(dm)) & (dm .< 3)] = 1  #14.55 µs per loop
@timeit dm[dm .< 3] = 1  #754.79 ns per loop

What is the reason that the developers make use of this exception and is there another simpler approach as the !isna() for ignoring NA's in DataArrays?

A: Suppose you have three rabbits. You want to put the female rabbit(s) in a separate cage from the males. You look at the first rabbit, and it looks like a male, so you leave it where it is. You look at the second rabbit, and it looks like a female, so you move it to the separate cage. You can't really get a good look at the third rabbit. What should you do?
It depends. Maybe you're fine with leaving the rabbit of unknown sex behind. But if you're separating out the rabbits because you don't want them to make baby rabbits, then you might want your analysis software to tell you that it doesn't know the sex of the third rabbit.
Situations like this arise often when analyzing data. In the most pathological cases, data is missing systematically rather than at random. If you were to survey a bunch of people about how fluffy rabbits are and whether they should be eaten more, you could compare mean(fluffiness[should_be_eaten_more]) and mean(fluffiness[!should_be_eaten_more]). But, if people who really like rabbits are incensed that you're talking about eating them at all, they might leave that second question blank. If you ignore that, you will underestimate the mean fluffiness rating among people who don't think rabbits should be eaten more, which would be a grave mistake. This is why fluffiness[!should_be_eaten_more] will throw an error if there are missing values: It is a sign that whatever you are trying to do with your data may not give the right results. This situation is bad enough that people write entire papers about it, e.g. this one.
Enough about rabbits. It is possible that there should be (and may someday be) a more concise way to drop/keep all missing values when indexing, but it will always be explicit rather than implicit for the reason described above. As far as performance goes, while there is a slowdown for isna(x) & (x < 3) vs x < 3, the overhead of repeatedly indexing into an array is also high, and DataArrays adds additional overhead on top of that. The relative overhead decreases as the array gets larger. If this is a bottleneck in your code, your best bet is to write it differently.


text:
Q: How can I get this external drive to work on this machine?
*

*The device is an HGST Touro S (HTOSPA10001BHB)

*The machine is a (new) Asus T100 Chi running Win10 Home x64

*The error I get is a notification that says "USB device not recognized / The last USB device you connected to this computer malfunctioned, and Windows does not recognize it.", and inside Device Manager is "Device Descriptor Request Failed"

The device is connected to the machine via OTG multi-cable.  The drive spins up and the light comes on as though nothing were wrong.  Other devices work fine through this same setup, and the device works fine on other machines.
Things I have tried, with no change in system behavior:

*

*Connect charger to the cable for extra power

*Update drivers

*(Re)Install Intel chipset driver package from ASUS support site

*Delete all USB devices in Device Manager (including hidden ones) and reboot so they reinstall

*Run the windows troubleshooter (which says it made some changes and prompts me to reboot)

Connecting through the other USB port (which is a USB 3 micro-B port, connected to a powered hub, connected to the device; I don't have a cable to go direct USB 3 micro-B to USB 3 micro-B) gives a different Device Manager error ("Port Reset Failed"), but still no dice.
Running MS's USB Troubleshooter tells me that "The USB Controller is in a failed state or is not currently installed.  The USB Controller must be installed or in a working state for this troubleshooter to run".  Interestingly, this does not change even if all the USB devices are freshly removed and auto-reinstalled with absolutely no USB devices connected.
What am I missing here?  How can I get this to work properly?
EDIT:  also tried booting from a live-linux Ubuntu medium.  Drive was also not recognized there, so seems like a hardware/firmware issue?


text:
Q: Not null if other entry is not null I am writing a table and I need A to not be null if B is not null (see below). I am trying to write a CHECK however I am not sure how to write it. Any advise is much appreciated.
CREATE TABLE `Test`
`A` varchar(4) CHECK(?),
`B` varchar(4)
);

A: Don't bother with a CHECK constraint. According to the manual:

The CHECK clause is parsed but ignored by all storage engines.

You can instead use a trigger, as suggested in this thread. The test itself would be
(B is null) or (A is not null)

EDIT: Assuming you are using MySQL version 5.5 or later, here's how you can trigger an error signal when the condition is violated:
mysql> DELIMITER //
mysql> DROP TRIGGER IF EXISTS before_insert_trigger//
mysql> CREATE TRIGGER before_insert_trigger
    ->   BEFORE INSERT ON Customer FOR EACH ROW
    ->   BEGIN
    ->   DECLARE msg VARCHAR(255);
    ->       IF (NEW.B is not null) and (NEW.A is null) THEN
    ->           SET msg = concat('Error: Trying to insert a NULL A when B is not null: ',
    ->                            cast(NEW.B as char));
    ->           SIGNAL sqlstate '45000' SET message_text = msg;
    ->       END IF;
    ->   END//
mysql> delimiter ;

(Note that I inverted the test because I want to test when it is violated, not when it is satisfied.) If you are using an earlier version of MySQL, you can use the suggestion provided in this answer or here.

A: MySQL does not enforce check constraints.  So, the only way you can do this in MySQL (using one table) is to use triggers.
I think the check constraint syntax you want is:
check ((a is null and b is null) or (a is not null and b is not null))

although it might be:
check ((b is null) or (a is not null))

depending on whether you really mean "if" or "if and only if".


text:
Q: A JMS XA connection factory injected using spring jee-jndi lookup behaves differently than @Resource injection on Weblogic 12c I have an MDB application recently ported to Weblogic 12c. I use spring 3.1 to inject datasource and jms resources however have found that delivery of message queues does not succeed (without error), appearing to not participate in the XA transaction although no rollback is evident.
I have since created a test app to isolate the issue. This test app contains:

*

*session timer bean putting message on testQueue1

*MDB1 updating the datasource and moving message from testQueue1 to testQueue2.

My spring configuration:
<jee:jndi-lookup id="jdbcDS" expected-type="javax.sql.DataSource" jndi-name="jdbc/test_OraclePool" />
<jee:jndi-lookup id="jmsCF" jndi-name="jms/test_ConnectionFactory" />
<jee:jndi-lookup id="jmsTestQueue1" jndi-name="jms/testQueue1"/>
<jee:jndi-lookup id="jmsTestQueue2" jndi-name="jms/testQueue2"/>
<bean id="transactionManager" class="org.springframework.transaction.jta.WebLogicJtaTransactionManager">
        <property name="transactionManagerName" value="javax.transaction.TransactionManager"/>
</bean>

The connection factory and queues reside in the same sub deployment and target the same JMS server on Weblogic 12c.
So I have found if I inject the connection factory through ejb @Resource injection everything works fine however for reasons outside of my control, changing our application to inject the connection factory is not an option. The other interesting difference is the concrete factory class returned by the container in each case varies:
@Resource returns - weblogic.deployment.jms.PooledConnectionFactory
Spring jndi injection - weblogic.jms.client.JMSXAConnectionFactory.
Does anyone have any idea what, if anything, I am missing?

A: In the instance of Spring configuration you are doing straight JNDI lookup of JMS connection factory. When using @Resource WebLogic injects JMS wrapper around the same factory. Among other things that wrapper takes care of automatic transaction enlistment(foreign JMS providers do not get enlisted automatically otherwise).  For more details look here: http://docs.oracle.com/cd/E24329_01/web.1211/e24387/j2ee.htm#JMSPG366 and here https://docs.oracle.com/cd/E24329_01/web.1211/e24387/interop.htm#JMSPG555
Although WebLogic has had support for JMS Wrappers since at least version 8.1  there is no public API(last I checked anyways) to use those wrappers in Java, thus making it difficult to piggyback on them for libraries like Spring. There is an enhancement request for this created a few years back(bug 20062862), but you would need to ask Oracle where they are with it.
If not using wrappers for foreign JMS providers you need to deal with enlistment yourself, which is unfortunate.


text:
Q: Errors in installing MariaDB in WSL2 I am trying to install MariaDB in WSL2, but it's showing me the following errors -
sachinpandeyatd@DESKTOP-Q3O2EQE:/mnt/c/Users/Hp/documents/server$ sudo apt-get install mariadb-server
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 mariadb-server : Depends: mariadb-server-10.3 (>= 1:10.3.29-0ubuntu0.20.04.1) but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

I'd be very grateful if anyone can resolve my error!!


text:
Q: Multiple String Manipulation using js I have a text area that I will paste some data in for example like so
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019

And when I click submit all the text inside the text box to give an output below something like this
06/01/2019 <!-- dd/mm/yyyy -->
07/01/2019
08/01/2019
08/01/2019
10/01/2019

I have managed to this on python  using this code
filepath = ('date.txt')
f = open("newdate.txt", "w+")
new = []
with open(filepath) as fp:
    for line in fp:
        line = line.strip('\n')
        new = line.split("-")
        f.write(new[1] + "/" + new[2] + "/" + new[0] + "\n")
        print(new[1] + "/" + new[2] + "/" + new[0] + "\n")
f.close()

I am new to JavaScript and jQuery so wondering how can i achieve that in jQuery

A: You can register an onsubmit listener on your form and then in the handler, perform your logic of parsing the text area's value.
The following snippet is an example of how to do that:

// Register 'submit' event listener
document.querySelector('#form')
  .addEventListener('submit', e => {
    // Prevent default action so that page doesn't refresh
    e.preventDefault();

    // Get the text from the textarea
    let text = document.querySelector('#text').value;

    // Split the lines
    let converted = text.split('\n')
      // Convert each line
      .map(str => {
        // Extract the date parts
        let [mm, dd, yyyy] = str.split('-');

        // Return the desired format by joining the date parts with /
        return [dd, mm, yyyy].join('/');
      });

    // Print result to console
    console.log(converted);
  });
<form id="form">
  <textarea id="text"></textarea>
  <button type="submit">submit</button>
</form>

A: use following regexp-replace for textarea value
value.replace(/(-)(?=\d)/g,'/')

The (-)(?=\d) will find all dashes '-' preceding the number

function submit() {
  let r=data.value.replace(/(-)(?=\d)/g,'/');
  console.log(r);
}
textarea { width: 200px; height: 100px; }
button { display: block }
<textarea id="data">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>

<button onclick=submit()>Submit</button>

A: You don't really need any jQuery for this just a little regex should work.

const datesArr = [
  '01-06-2019',
  '01-07-2019',
  '01-08-2019',
  '01-09-2019',
  '01-10-2019',
]
const newDates = []
const regex = /(\d\d)-(\d\d)-(\d{4})/

for (let date of datesArr) {
    newDates.push(date.replace(regex, '$2/$1/$3'))
}

console.log(newDates)

A: function convertToFormat(data) {
    var _dataSplit = data.split('\r\n');
    var _length = _dataSplit.length;

    var _finalData = '';

    for (var i=0;i<_length;i++) {
        var _dataDSplit = _dataSplit[i].split('-');
        _finalData += _dataDSplit[1]+'/'+_dataDSplit[0]+'/'+_dataDSplit[2]+'\r\n';
    }

    return _finalData;
}

A: You can get the text area value on clicking submit like the below snippet. You can do your date manipulation (Learn some string manipulation to do the formatting. Refer - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String)

function formatText() {
  var textAreaValue = $('#my-text').val();
  // Do the necessary formatting here
  var formattedText = 'test';
  $('#my-text').val(formattedText);
}
.btn {
  display: block;
  width: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <textarea id="my-text"></textarea>
  <button class="btn" onClick="formatText()">Submit</button>
</div>

A: Try using regex replace.
Regex demo here

let dates = document.getElementById('dates');

console.log(dates.value.replace(/(\d{2})-(\d{2})-(\d{4})/g, '$2/$1/$3'))
<textarea id="dates" rows="6" cols="30">
01-06-2019 <!-- mm-dd-yyyy -->
01-07-2019
01-08-2019
01-09-2019
01-10-2019
</textarea>


text:
Q: Tkinter - Return only occurs after the 2nd execution I have a very simple app in Tkinkter. I am running it in Ipython Notebook.
The issue is whenever i run the app and press the button 'Get' once, nothing is returned. I press the button again and two values are returned. I press button 3 or more times and 1 value is returned per time I press the button as expected. The issue is around the first press of the button. Is there something going on I do not understand.
from tkinter import *
from tkinter import ttk, Tk

class SampleApp(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.entry = tk.Entry(self)
        self.button = tk.Button(self, text="Get", command=self.on_button)
        self.button.pack()
        self.entry.pack()

    def on_button(self):
        value = float(self.entry.get())
        print (value*2)

app = SampleApp()
app.mainloop()

input = 5
output i get after 1 button press (not expected)
nothing
after 2 button presses (whilst i would expect 2 values at this stage, i do not expect 2 values to appear at the same time)
10
10
after 3 button presses (expected)
10
10
10
after 4 button presses (expected)
10
10
10
10

A: Having searched for an answer for a while, annoyingly the answer reveals itself just after i post. Found the answer here. Whilst I am not sure i understand, the first print doesn't trigger a flush of stdout. A manual workaround is in the link or below
import sys

def on_button(self):
    value = float(self.entry.get())
    print (value*2)
    sys.stdout.flush() #place this after the print statement


text:
Q: How to get data from Call without a callback - Retrofit - Kotlin - Jetpack Compose i have a method calling an API. :
interface ILoginService {
    //make login
    suspend fun login(payload: String): Call<Session>?

    //creates payload for request body
    fun createLoginPayload(login: LoginModel): String
}

override suspend  fun login(payload:String):Call<Session>?{
         val instance=retrofitService.getInstance()
         val requestBody = payload.toRequestBody("application/json".toMediaTypeOrNull())
         return instance?.requestToken(requestBody) ?: return null
     }

I am returning Call to viewmodel. How i can extract data from that Call without a callback (response.enqueue() ... )???? This is the method in viewmodel:
fun loginPass() {
        var result: Call<Session>?
        try {
            viewModelScope.launch {
                result = _loginService.login(_loginService.createLoginPayload(_login))!!
                val test=result
                Log.d("resultado",result.toString())
            }
        }catch (err:Throwable){
            Log.d("ERROR",err.message.toString())
        }
    }


text:
Q: YOLO Training error with shape for my own dataset, Can someone help to understand this and help to solve the issue ValueError: could not broadcast input array from shape (1,5) into shape (1,8)

A: Basically, this error is occurring due to incompatibility between the shapes while broadcasting. There are some broadcasting rules that are followed when performing certain operations on NumPy arrays. You can read more about these rules here.


text:
Q: ElasticSearch: Sorted index vs inverted index I wanna know whats the difference between the sorted vs inverted index in an elastic search (lucene).
From an ElasticSearch talk I read that the inverted index is kinda like a sorted dictionary: https://youtube.com/clip/UgkxYaESyHcsWyCkPKp7kac5BT4tFy99WTip
Doesn't that make the whole sorted index concept unneccessary?


text:
Q: What does Max connections in my SQL exactly means? We are  building a POS app which is cloud based
We decided to 4GB VPS for MySQL
And 2GB VPS for nodejs
Our client count will be atleast 5000 and atleast 1500 users will update the tables at same time
I checked how much memory does MySQL takes for 1500 concurrent connections
Now my doubt is , even 1500 connections at a time require more than 4GB RAM .
But I have seen lot and lot of DB servers serving lot of request just 4 GB RAM
Please explain me whether max user connections mean number of end users at front end OR something else?
(Not a duplicate question. I searched many Stack overflow questions but still confusing)

A: As MySQL documentation on max_connections setting says:

The maximum permitted number of simultaneous client connections.

So, this is the maximum number of concurrent mysql connections that you can have. Nothing to do with the number of front end users, this is purely a mysql level configuration.

A:
atleast 1500 users will update the tables at same time

No, they won't. Depending on how badly your application is designed, you may have 5000 concurrent connections - updates will not all happen at the same time.

We decided to 4GB VPS

How did you decide?
Even if you were ask the question properly, it is not something which can be sensibly answered here.
Currently you are not in any position to evaluate any answers you get here - you don't understand the application you are writing nor capacity planning. Your question will be downvoted and closed. Read the linked discussion then go do some modelling and testing. Then go read up on MySQL tuning.

A: Small sample

*

*Python app needs from 1 to 8MB (stack_size) for one thread
(if will be more connection server throw error stackoverflow (memory error))

*1500 x 8MB => 12 GB for python app

*Mysql need 1.5 GB per 500 conn +-

*1500 conn => 4.5GB (mysql)

Read:
https://www.percona.com/blog/2019/02/25/mysql-challenge-100k-connections/
https://www.percona.com/blog/2014/02/04/16000-active-connections-percona-server-continues-work-others-die/


text:
Q: navigation bar contents lose all styling after translation I have ran into a problem, I have managed to translate nav bar. Right now, I have managed to translate all the content of the page but I have a problem which I cannot figure out myself. The problem: When I switch the language of the page from "English" to "Latvian" all  leading to other pages and css styling disappears. After the translation the latvian version becomes a plain text in the navbar, but it stays the same in heading and paragraph. Can anyone help me solve the problem?

        const langEl = document.querySelector('.langWrap');
        const link = document.querySelectorAll('a');
        const titleEl = document.querySelector('.headings');
        const descrEl = document.querySelector('.description');
        const aboutUsEl = document.querySelector('.aboutus');
        const newsEl = document.querySelector('.news');
        const resultsEl = document.querySelector('.results');
        const leaguesEl = document.querySelector('.leagues');
        const loginEl = document.querySelector('.login');

        link.forEach(el => {
            el.addEventListener('click', () => {
                langEl.querySelector('.active').classList.remove('active');
                el.classList.add('active');

                const attr = el.getAttribute('language');

                titleEl.textContent = data[attr].headings;
                descrEl.textContent = data[attr].description;
                aboutUsEl.textContent = data[attr].aboutus;
                newsEl.textContent = data[attr].news;
                resultsEl.textContent = data[attr].results;
                leaguesEl.textContent = data[attr].leagues;
                loginEl.textContent = data[attr].login;
            });
        });
var data = {
    "english":
    {
    "aboutus":"About Us",
    "news":"News",
    "results":"Results",
    "leagues":"Leagues",
     "login":"Profile",
      "headings": "News",
      "description":
          "Last weekend there were a lot of great games."
    },
    "latvian":
    {
        "Aboutus":"Par mums",
         "news":"Jaunumi",
        "results":"Rezultāti",
        "leagues":"līgas",
        "login":"profils",
        "headings": "Jaunumi",
         "description":
            "Pagājušajā nedēļā bija ļoti daudz labu spēļu"
    }
  }

            EN
            LV

About Us

News

Results

Leagues

Profile

 News

Last weekend there were a lot of great games.

A: here's just change selector to a tag

const langEl = document.querySelector('.langWrap');
        const link = document.querySelectorAll('a');
        const titleEl = document.querySelector('.headings');
        const descrEl = document.querySelector('.description');
        const aboutUsEl = document.querySelector('.aboutus a');
        const newsEl = document.querySelector('.news a');
        const resultsEl = document.querySelector('.results a');
        const leaguesEl = document.querySelector('.leagues a');
        const loginEl = document.querySelector('.login a');

        link.forEach(el => {
            el.addEventListener('click', () => {
                langEl.querySelector('.active').classList.remove('active');
                el.classList.add('active');

                const attr = el.getAttribute('language');

                titleEl.textContent = data[attr].headings;
                descrEl.textContent = data[attr].description;
                aboutUsEl.textContent = data[attr].aboutus;
                newsEl.textContent = data[attr].news;
                resultsEl.textContent = data[attr].results;
                leaguesEl.textContent = data[attr].leagues;
                loginEl.textContent = data[attr].login;
            });
        });
var data = {
    "english":
    {
    "aboutus":"About Us",
    "news":"News",
    "results":"Results",
    "leagues":"Leagues",
     "login":"Profile",
      "headings": "News",
      "description":
          "Last weekend there were a lot of great games."
    },
    "latvian":
    {
        "aboutus":"Par mums",
         "news":"Jaunumi",
        "results":"Rezultāti",
        "leagues":"līgas",
        "login":"profils",
        "headings": "Jaunumi",
         "description":
            "Pagājušajā nedēļā bija ļoti daudz labu spēļu"
    }
  }

            EN
            LV

About Us

News

Results

Leagues

Profile

 News

Last weekend there were a lot of great games.


text:
Q: How to ignore warning unrelated to package name in Proguard file? I am working with Android Studio 3.0 and experience warnings after gradle build:

AGPBI: {"kind":"warning","text":"Transform
  \u0027RealmTransformer\u0027 uses scope PROJECT_LOCAL_DEPS which is
  deprecated and replaced with EXTERNAL_LIBRARIES","sources":[{},{}]}

I heard about the issue https://github.com/realm/realm-java/issues/4659 which explains the bug, but my question is unrelated. I am actually curious, if it's possible to ignore in build with Proguard shrinking warnings unrelated to any package name or class.
proguard-rules.pro with
-dontwarn **
-ignorewarnings
-dontwarn io.realm.**

simply doesn't work and I can't build the project with Proguard activated.


text:
Q: Template Compiler Error (TemplateCompiler) in ember-paper/templates/components/paper-dialog.hbs My ember application started showing below error while building the app (Initially it was working and without any code change, build started failing):
*Template Compiler Error (TemplateCompiler) in ember-paper/templates/components/paper-dialog.hbs
Assertion Failed: The {{in-element}} helper cannot be used. ('ember-paper/templates/components/paper-dialog.hbs' @ L1:C0)*
I am using "ember-cli": "^3.28.3" and "ember-paper": "^1.0.0-beta.30"
Ember latest 4.0 release showing renderTemplate is removed in favor of {{in-element}} or other rendering target. Is this API removal is the culprit?
Any clue or suggestion will help. Thanks a lot in advance!


text:
Q: Update Reports to filter with an Oracle function in Crystal Reports 2008 I have several reports, and on each one of them i have a few tables included.
Lets say 3 tables, tableA, tableB and tableC.
I want to use the following Oracle Function to filter the result set passing also a report parameter:
AND function(tableB.field1, tableB.field2, tableB.field3, {?report_parameter}) = 'S'

Facts to be aware of:

*

*Oracle Functions can only be used on SQL Expressions and/or SQL Commands in Crystal Reports.

*SQL Expressions cannot contain report parameters (so, not an option).

*Crystal Reports lets you replace a report table with a SQL Command, but does not let you replace several tables to a single SQL Command.

*We do not want to re-build all the reports all over again.

*We do not want to replace a single table to a SQL Command because it affects performance in a high level since Crystal does not transform the tables and the SQL Command on a single query when executing the report.

*This Oracle Function selects data from other tables and therefore can not be rewritten on a Report Custom Function.

*The {?report_parameter} is an information that only the application knows. It is filled by the application before exporting the report to the user.

What could I do to work around this?

A: No knowing exactly why your function requires tables and parameter, I can only give you vague, untested options.  None of the options are ideal:

*

*rewrite your Oracle function as 'Custom Function' (CF); reference CF in record-selection formula; filter will be applied WhileReadingRecords (i.e. the function will not be sent to the database)

*rewrite your function as a stored procedure that accepts one parameter, but returns a record set (the parameter will be recognized by Crystal Reports); join the other tables to the stored procedure.  The stored procedure will need to be written in a manner that will support Crystal Reports' data needs (using result from a stored procedure with parameters as value for gauge chart - crystal reports in asp.net application)


text:
Q: Save to ArrayList within method - unexpected results I am trying to save a list of permutations to use later in my program. However, when I try to append the permutation results to full_list, the original list gets saved to the list over and over. BUT the results printed from System.out.println(arr); are exactly what I want.
import java.util.*;

public class mytest {

    public static void main(String[] args){
        ArrayList<Integer> inlist = new ArrayList<Integer>();
        inlist.add(1);
        inlist.add(2);
        inlist.add(3);
        permute(inlist, 0);
        System.out.println(full_list);
    }

    public static HashSet<ArrayList<Integer>> full_list = new HashSet<ArrayList<Integer>>();

    public static void permute(ArrayList<Integer> arr, int k){

        for(int i = k; i < arr.size(); i++){
            java.util.Collections.swap(arr, i, k);
            permute(arr, k+1);
            java.util.Collections.swap(arr, k, i);
        }
        if (k == arr.size() -1){
            System.out.println(arr);
            full_list.add(arr);
        }
    }
}

results from System.out.println(arr);
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[2, 3, 1]
[3, 2, 1]
[3, 1, 2]

results from printing full_list in the main method:
[[1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3], [1, 2, 3]]

What can I do to fix this so the printed results are saved in the full_list?

A: You are changing values of arr that are adding to full_list. To prevent this you should add new clone of arr to full_list:
full_list.add(new ArrayList<>(arr));

A: Just do: full_list.add(new ArrayList<Integer>(arr));
The error in your code is that you are adding the same ArrayList every time, but you have to create a copy of it. This code is creating a copy new ArrayList<Integer>(arr)


text:
Q: Terminology - matrix whose elements are the magnitudes of the elements of a complex matrix Given a complex matrix A, we calculate B whose elements $B_{ij} = |A_{ij}|$. What is B called in terms of A (is there a special name?) and what notation do we use?
Using B = |A| would be problematic since this is the determinant sign.


text:
Q: Data type change in Metabase I am trying to change the data type of a column i created with SQL in Metabase.
i used this code to split the json column
select *,
       substring(key from '_([^_]+)$') as Volume,
       substring(outgoing::varchar from ':"([a-z]*)' ) as Status
from table
cross join lateral json_object_keys(outgoing) as j(key);

upon splitting, i realized that the volume field has the type text.
I am trying to change this to integer.


text:
Q: Skip field validation when creating a record using Dynamics 365 web api I am integrating Dynamics 365 with our product, and I am running into an issue when creating fields on dynamics 365 using web api.
I am creating a contact or lead using a set of fields such as email, name etc. Some fields seem to have validation, such as number only field, or picklist. In these cases I am getting an error with 400 status and the record is not created. Is there a way to just create the record using the valid fields and just skip updating the fields that failed validation.
This is the end point I am using for creating a contact:
/api/data/v9.1/contacts

Headers used:
Prefer:return=representation
Content-Type:application/json
OData-MaxVersion:4.0
OData-Version:4.0
If-None-Match:null

A: You have two options:

*

*Either do the proper validation when user entering values for those fields from outside Dynamics.

*Or create custom fields in Dynamics contact entity to store the string type values
Web api payload has to be whole and cannot be truncated/set for adhoc scenarios like skip failing datatypes (your requirement).

A: Hope this helps. No matter what software or environment you are integrating with, it is important to know your data structure including data types, data validations (including required yes/no) and data constraints (length, decimal places, etc.).
There are three ways you can integrate with Dynamics 365 factoring in the above.
1. Static code based on the Dynamics 365 configuration
If you can login to Dynamics 365, you can view the environment definition by going to Settings > Customizations > Customize the System.

From here you can view all Entity and Attribute definitions and and write your code accordingly. You can also "require" installation of your own solution with Entities and Attributes, giving you control over what your integrating with.

2. Creating Early-Bound classes
You can generate Early Bound classes with the Entity and Attribute definition from Dynamics 365 with the CrmSvcUtil tool. For more information.
For more information:
https://learn.microsoft.com/en-us/dynamics365/customer-engagement/developer/org-service/create-early-bound-entity-classes-code-generation-tool
3. Dynamics 365 Metadata service
Dynamics 365 provides a Metadata service, enabling you to retrieve the exact definition of alle Entities and Attributes directly from the given Dynamics 365 environment. As such you can retrieve the definition prior to integrating.
I think considering the performance, this is definitly not something you would like to do every single message. To resolve this you could retrieve the definition on request (manual trigger) or daily.
For more information: https://learn.microsoft.com/en-us/dynamics365/customer-engagement/customize/create-edit-metadata
When working with Dynamics 365, the XRMToolBox is a must have tool for any developer or consultant. With the tools Metadata Browser plugin you can view the data that you can retrieve by the Metadata service.


text:
Q: bounds on $\frac{(\operatorname{Tr} H C)^2}{\operatorname{Tr} H^2 C}$ Suppose $H,C$ are positive semi-definite matrices, and $C$ has unit trace. $H$ is given and fixed while $C$ is allowed to vary. How do I bound the following quantity?
$$R=\frac{(\operatorname{Tr} H C)^2}{\operatorname{Tr} H^2 C}$$
For instance suppose
$$H=\left(
\begin{array}{cccc}
 4 & 0 & 0 & 0 \\
 0 & 3 & 0 & 0 \\
 0 & 0 & 2 & 0 \\
 0 & 0 & 0 & 1 \\
\end{array}
\right)$$
Simulation suggests the following:
$$\frac{16}{25}\le R\le 1$$
Is there a general formula in terms of $H$ eigenvalues?

A: The ratio $R$ is not always defined as the denominator may be zero. You may modify your question by asking what are the largest possible $k\ge0$ and the least possible $K\ge0$ such that
$$
k\operatorname{tr}(H^2C)\le\left(\operatorname{tr}(HC)\right)^2\le K\operatorname{tr}(H^2C)
$$
for all $C,H\ge0$ with $\operatorname{tr}(C)=1$.
In this case, the answer is $k=0$ (unless the matrices are $1\times1$, in which case $k=1$) and $K=1$. That $K=1$ is an easy consequence of Cauchy-Schwarz inequality
$$
\left(\operatorname{tr}(HC)\right)^2
=\langle H\sqrt{C},\sqrt{C}\rangle_F^2
\le\|H\sqrt{C}\|_F^2\|\sqrt{C}\|_F^2
=\operatorname{tr}(H^2C)
$$
and the fact that equality holds when $C=H=\operatorname{diag}(1,0,\ldots,0)$. For the largest possible value of $k$, consider $C=\operatorname{diag}(t,1-t,0,\ldots,0)$ and $H=\operatorname{diag}(1,0,0,\ldots,0)$ with $t>0$. Then $\dfrac{\left(\operatorname{tr}(HC)\right)^2}{\operatorname{tr}(H^2C)}=t$. Since this ratio approaches zero as $t\to0$, we must have $k=0$.
Edit. If you want a lower bound that depends on $H$, an obvious one is
$$
\lambda_\min(H)^2\operatorname{tr}(H^2C)\le\lambda_\max(H)^2\left(\operatorname{tr}(HC)\right)^2.
$$
To prove it, assume that $H$ is a diagonal matrix. Let $h_\min,h_\max$ and $h_i$ be respectively the minimum, the maximum and the $i$-th diagonal element of $H$. Then
$$
h_\min^2\sum_ih_i^2c_{ii}
\le h_\min^2h_\max^2\sum_ic_{ii}
=h_\max^2\left(\sum_ih_\min c_{ii}\right)^2
\le h_\max^2\left(\sum_ih_ic_{ii}\right)^2.
$$


text:
Q: Azure DevOps pipeline variables in .nuspec files Is it possible to use Azure DevOps pipeline variables in .nuspec files, which are used for packages creation?
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2012/06/nuspec.xsd">
  <metadata>
    <id>MyTemplate</id>
    <version>$(var1).$(var2).$(var3)</version>
    <description>
      Some template
    </description>
    <authors>Test Test</authors>
    <packageTypes>
      <packageType name="Template" />
    </packageTypes>
  </metadata>
</package>

Or is it a way to ovveride version specified in .nuspec file(it is required element) by those one in .yaml task?
task: NuGetCommand@2
  displayName: Pack template
  inputs:
    command: pack
    packagesToPack: '**/Template/*.nuspec'
    packDestination: $(Build.ArtifactStagingDirectory)
    versioningScheme: byPrereleaseNumber
    majorVersion: '$(var1)'
    minorVersion: '$(var2)'
    patchVersion: '$(var3)'

But with versioningScheme: byPrereleaseNumber we will get timestamp added to our numbers.

A: Pop-up ToolTip for Build Properties:

Specifies a list of token=value pairs, separated by semicolons, where each occurrence of $token$ in the .nuspec file will be replaced with the given value. Values can be strings in quotation marks.

I figured out the following YAML by going into the UI builder for editing the pipeline visually, there's an "Advanced" pane inside the NuGet > Pack task. It allows you to specify additional token replacement values under "build properties" (buildProperties)
I have a feeling it's one of those things where you have to transform one type of token into another.. see the buildProperties on the last line:
variables:
  Parameters.requestedMajorVersion: '1'
  Parameters.requestedMinorVersion: '0'
  Parameters.requestedPatchVersion: '6'

steps:
- task: NuGetCommand@2
  displayName: 'NuGet pack'
  inputs:
    command: pack
    packagesToPack: '**/*.nuspec'
    versioningScheme: byPrereleaseNumber
    majorVersion: '$(Parameters.requestedMajorVersion)'
    minorVersion: '$(Parameters.requestedMinorVersion)'
    patchVersion: '$(Parameters.requestedPatchVersion)'
    includeSymbols: true
    buildProperties: 'id=$(Build.Variable)'

Example .nuspec
<?xml version="1.0" encoding="utf-8"?>
<package xmlns="http://schemas.microsoft.com/packaging/2013/05/nuspec.xsd">
  <metadata minClientVersion="2.5">
    <id>$id$</id>


text:
Q: Stem list Tor circuit generated in file I am attempting to start a Tor connection using Stem and then list the nodes that are selected.
Using other questions and the FAQ on their website I can do one or other, but not both.
For example, I can start a Tor circuit with
  tor_process = stem.process.launch_tor_with_config(
    config = {
      'ControlPort': '2778',
      'Log': [
        'NOTICE stdout',
        'ERR file /tmp/tor_error_log',
      ],
    "MaxCircuitDirtiness" : str(60*60*24*30),
    "NewCircuitPeriod" : str(60*60*24*30),
    },
  )

And separately I can look at the circuit nodes if I start Tor separately using code from here.
But if I try to do both, such as:
from stem import CircStatus
from stem.control import Controller
import stem
import stem.connection
import stem.process

from stem.control import Controller

if __name__ == '__main__':
  tor_process = stem.process.launch_tor_with_config(
    config = {
      'ControlPort': '2778',
      'Log': [
        'NOTICE stdout',
        'ERR file /tmp/tor_error_log',
      ],
    "MaxCircuitDirtiness" : str(60*60*24*30),
    "NewCircuitPeriod" : str(60*60*24*30),
    },
  )

  with Controller.from_port() as controller:
    controller.authenticate()

    for circ in controller.get_circuits():
      if circ.status != CircStatus.BUILT:
        continue  # skip circuits that aren't yet usable

      entry_fingerprint = circ.path[0][0]
      entry_descriptor = controller.get_network_status(entry_fingerprint, None)

      if entry_descriptor:
        print "Circuit %s starts with %s" % (circ.id, entry_descriptor.address)
      else:
        print "Unable to determine the address belonging to circuit %s" % circ.id
  tor_process.kill()

I get an error:
Traceback (most recent call last):
  File "circuit.py", line 22, in <module>
    with Controller.from_port() as controller:
  File "/usr/local/lib/python2.7/dist-packages/stem/control.py", line 1024, in from_port
    control_port = stem.connection._connection_for_default_port(address)
  File "/usr/local/lib/python2.7/dist-packages/stem/connection.py", line 1058, in _connection_for_default_port
    raise exc
stem.SocketError: [Errno 111] Connection refused

Which is normally the error I get when I try to do things without having separately started tor.
Is there a way to combine these two operations?
EDIT: There is, I forgot I set the ControlPort answered my question below.

A: The answer was simple, I forgot I set the port in config, I set ControlPort : 2778, but opened Contoller.from_port() which uses the default port of 9051.
Using Controller.from_port(port = 2778) fixed the problem.


text:
Q: Где найти хорошую статью о различиях движков в mysql Не могу найти нигде , кроме как на doc.mysql. Может кто-то встречался с данной проблемой?

A: Замечательная статья здесь сравнение , описание и т.д.
или тут на крайняк


text:
Q: Update user meta after one hour With the standard wordpress function I am trying to update user meta data, but after one hour, not directly. I am doing something wrong but I can't really put my finger on it. Time is set to 30 secs for testing purposes btw.
 $afteranhour = update_user_meta( $user_id, 'money', $oldmoney-$totalprice);

 function do_this_in_an_hour($afteranhour) {

 // do something
 }
 add_action( 'my_new_event','do_this_in_an_hour' );

 // put this line inside a function,
 // presumably in response to something the user does
 // otherwise it will schedule a new event on every page visit

wp_schedule_single_event( time() + 30, 'my_new_event' );

// time() + 3600 = one hour from now.

A: Please read carefully about wp_schedule_single_event in Codex. As you can see, there is a third argument $args.
You can schedule a singule WP_Cron event by modifying the function you use above and passing arguments as third parameter:
<?php
// Your basic hook schelduling...
wp_schedule_single_event( time() + 30, 'user_cron_event',
    array(
        'user_id' => $user_id,
        'oldmoney' => $oldmoney,
        'totalprice' => $totalprice
    )
);

and your base action in this case...
add_action('user_cron_event', 'user_cron_event_callback');
function user_cron_event_callback($args){
    update_user_meta( $args['user_id'], 'money', $args['oldmoney']-$args['totalprice']);
}


text:
Q: Why do I have accept error when using Boost library saying "I'm missing websocket handshake connection field is missing the upgrade token" I'm a newbie in using Boost library.
I'm currently trying to connect websocket to a webpage hosting locally but having the error.
It keeps complaining that the websocket connection field is missing the upgrade token, and I don't have a clue what this is about.
The following is the code related to creating and interfacing with a websocket.
void
fail(beast::error_code ec, char const* what)
{
    std::cerr << what << ": " << ec.message() << endl;
    throw std::runtime_error("fail");
}

// Echoes back all received WebSocket messages

    session::session(tcp::socket&& socket, queue<PQN_DATA_PACKET *> *pQ)
        : ws_(std::move(socket))
    {
        cycle_cnt = 0;
        phase_cnt = 0;
        pconnectionQ = pQ;
        m_portion = 0;
    }

    // Get on the correct executor
    void session::run()
    {
       cout << "TODO session for " << endl;
        // We need to be executing within a strand to perform async operations
        // on the I/O objects in this session. Although not strictly necessary
        // for single-threaded contexts, this example code is written to be
        // thread-safe by default.
        net::dispatch(ws_.get_executor(),
            beast::bind_front_handler(
                &session::on_run,
                shared_from_this()));
    }

    // Start the asynchronous operation
    void session::on_run()
    {
        cout << "ON_RUN_SESSION" << endl;
        // Set suggested timeout settings for the websocket
        ws_.set_option(
            websocket::stream_base::timeout::suggested(
                beast::role_type::server));

        // Set a decorator to change the Server of the handshake
        ws_.set_option(websocket::stream_base::decorator(
            [](websocket::response_type& res)
            {
                res.set(http::field::server,
                    std::string(BOOST_BEAST_VERSION_STRING) +
                    " websocket-server-async");
            }));
        // Accept the websocket handshake
        ws_.async_accept(
            beast::bind_front_handler(
                &session::on_accept,
                shared_from_this()));
    }

    void session::on_accept(beast::error_code ec)
    {
        cout << "ON_ACCEPT SESSION" << endl;
        if (ec)
            return fail(ec, "accept");

        // Read a message
        // do_read();
        // boost::this_thread::sleep_for(boost::chrono::milliseconds(1000));

        // const int size = 256;
        // unsigned char pu8rawbuf[size];

        // for (int i = 0; i < size; i++) {
        //     pu8rawbuf[i] = rand() % 256;;
        // }

        cout << "accept connection" << endl;
        //m_portion = 0;
        //m_count_objects = 0;
        //m_itr_doc = jsonDocumentData.MemberBegin();
        //m_itr_arr = m_itr_doc->value.Begin();
        //m_is_end_file = false;

        do_write();
    }

    void session::do_read()
    {
        // Read a message into our buffer
        ws_.async_read(
            buffer_,
            beast::bind_front_handler(
                &session::on_read,
                shared_from_this()));
    }

    void session::on_read(
            beast::error_code ec,
            std::size_t bytes_transferred)
    {
        boost::ignore_unused(bytes_transferred);

        // This indicates that the session was closed
        if (ec == websocket::error::closed)
            return;

        if (ec)
            fail(ec, "read");

        // Echo the message
        ws_.text(ws_.got_text());

        // auto jv = parse_file("./input2.json");
        // pretty_print(std::cout, jv);
        std::string stringForSending = std::string("TEST");
                std::cout << "SENDED\n";
        ws_.async_write(
            net::buffer(stringForSending),
            beast::bind_front_handler(
                &session::on_write,
                shared_from_this()));
    }

The error is occurring at session::on_accept() function. And the error message is as the below:
TODO session for
ON_RUN_SESSION
DO_ACCEPT LISTENER
DO_ACCEPT LISTENER END
ON_ACCEPT SESSION
accept: The WebSocket handshake Connection field is missing the upgrade token
terminate called after throwing an instance of 'std::runtime_error'
  what():  fail

I'm connecting the websocket to node.js server hosted locally, and the port number matches of course.
The following code snippet is from the websocket client side.
const connectToWebSocketServer = () => {
  const socket = new WebSocket(WEB_SOCKET_URL)

  socket.onopen = (event) => {
    console.warn('websocket connection established', event)
    if (WEBSOCKET_CONNECTION_DURATION) {
      setTimeout(() => {
        socket.close()
        console.warn('websocket connection closed')
      }, WEBSOCKET_CONNECTION_DURATION)
    }
  }

Can anyone figure out what my problem is and how I can fix this?
Thank you in advance!

A: I once again completed your example - this time as
On Coliru
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <iostream>
#include <memory>
#include <queue>

namespace net   = boost::asio;
namespace beast = boost::beast;
using net::ip::tcp;
using beast::error_code;

static void fail(error_code ec, std::string_view msg) {
    std::cerr << msg << ": " << ec.message() << std::endl;
    throw std::runtime_error("fail");
}

struct PQN_DATA_PACKET {
};

struct session : std::enable_shared_from_this<session> {
    session(tcp::socket&& socket) : _socket(std::move(socket)) {}

    void run()
    {
        std::cout << "TODO session for " << _socket.remote_endpoint()
                  << std::endl;
    }

  private:
    tcp::socket _socket;
};

using Queue = std::queue<PQN_DATA_PACKET*>;

struct listener : std::enable_shared_from_this<listener> {
    net::io_context& _ioc;
    tcp::acceptor    _acceptor{_ioc};
    Queue&           _connectionQ;

    listener(net::io_context& ioc, tcp::endpoint ep, Queue& connectionQ)
        : _ioc(ioc)
        , _acceptor(ioc, ep)
        , _connectionQ(connectionQ)
    {
    }

    // Start accepting incoming connections
    void run() { do_accept(); }

    void do_accept()
    {
        std::cout << "DO_ACCEPT LISTENER" << std::endl;
        // The new connection gets its own strand
        _acceptor.async_accept( //
            net::make_strand(_ioc),
            beast::bind_front_handler(&listener::on_accept,
                                      shared_from_this()));

        std::cout << "DO_ACCEPT LISTENER END" << std::endl;
    }

    void on_accept(beast::error_code ec, tcp::socket socket)
    {
        std::cout << "ON_ACCEPT LISTENER" << std::endl;
        if (ec) {
            fail(ec, "accept");
        } else {
            // Create the session and run it
            std::make_shared<session>(std::move(socket) /*, _connectionQ*/)
                ->run();
        }

        // Accept another connection
        do_accept();
    }
};

struct server {
    net::io_context           _ioc;
    Queue                     _connectionQ;

    void run(tcp::endpoint ep, unsigned nthreads = 1) {
        std::make_shared<listener>(_ioc, ep, _connectionQ) //
            ->run();

        // Run the I/O service on the requested number of threads
        std::vector<std::thread> v(nthreads);

        for (auto& th : v)
            th = std::thread([this] { _ioc.run(); });

        for (auto& th : v)
            if (th.joinable())
                th.join();
    }
};

int main() {
    static uint16_t constexpr SERVER_PORT_NUMBER = 9797;

    server srv;
    srv.run({{}, SERVER_PORT_NUMBER}, 1);
}

Then I made a sample client in node:
#!/usr/bin/env node
var WebSocketClient = require('websocket').client;

var client = new WebSocketClient();

client.on('connectFailed', function(error) {
    console.log('Connect Error: ' + error.toString());
});

client.on('connect', function(connection) {
    console.log('WebSocket Client Connected');
    connection.on('error', function(error) {
        console.log("Connection Error: " + error.toString());
    });
    connection.on('close', function() {
        console.log('echo-protocol Connection Closed');
    });
    connection.on('message', function(message) {
        if (message.type === 'utf8') {
            console.log("Received: '" + message.utf8Data + "'");
        }
    });

    function sendNumber() {
        if (connection.connected) {
            var number = Math.round(Math.random() * 0xFFFFFF);
            connection.sendUTF(number.toString());
            console.log("Sending: '" + number.toString() + "'");
            setTimeout(sendNumber, 1000);
        }
    }
    sendNumber();
});

client.connect('ws://localhost:9797/', '');

I can run them fine:
./sotest & npm install websocket && nodejs ./test.js

Prints
[1] 14461
DO_ACCEPT LISTENER
DO_ACCEPT LISTENER END

added 18 packages, and audited 19 packages in 699ms

found 0 vulnerabilities
ON_ACCEPT LISTENER
TODO session for
DO_ACCEPT LISTENER
DO_ACCEPT LISTENER END
accept connection
WebSocket Client Connected
Sending: '7599795'
Received: '7599795'
Sending: '3553782'
Received: '3553782'
Sending: '13810406'
Received: '13810406'
Sending: '12580747'
Received: '12580747'
Sending: '3757113'
Received: '3757113'

etc.


text:
Q: Create radial network diagram with non-hierarchical data in D3.js I am trying to create a diagram similar to this one in D3.js:
http://mbostock.github.io/d3/talk/20111116/bundle.html
This example uses hierarchical edge bundling. However, my data is not hierarchical in nature and I want to represent a relatively simple network structure. I have a bunch of nodes divided into groups, and connected through a simple connectivity matrix. I am able to generate a force-directed network diagram in D3.js similar to this:
http://bl.ocks.org/mbostock/4062045

var width = 500,
    height = 500;

var color = d3.scale.category20();

var force = d3.layout.force()
    .charge(-120)
    .linkDistance(30)
    .size([width, height]);

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height);

var graph = getData();

force
    .nodes(graph.nodes)
    .links(graph.links)
    .start();

var link = svg.selectAll(".link")
    .data(graph.links)
   .enter()
    .append("line")
    .attr("class", "link")
    .style("stroke-width", function(d) { return Math.sqrt(d.value); });

var node = svg.selectAll(".node")
    .data(graph.nodes)
   .enter()
    .append("circle")
    .attr("class", "node")
    .attr("r", 5)
    .style("fill", function(d) { return color(d.group); })
    .call(force.drag);

node.append("title")
    .text(function(d) { return d.name; });

force.on("tick", function() {
    link.attr("x1", function(d) { return d.source.x; })
        .attr("y1", function(d) { return d.source.y; })
        .attr("x2", function(d) { return d.target.x; })
        .attr("y2", function(d) { return d.target.y; });

    node.attr("cx", function(d) { return d.x; })
        .attr("cy", function(d) { return d.y; });
});

function getData() {

return {
  "nodes":[
    {"name":"Myriel","group":1},
    {"name":"Napoleon","group":1},
    {"name":"Mlle.Baptistine","group":1},
    {"name":"Mme.Magloire","group":1},
    {"name":"CountessdeLo","group":1},
    {"name":"Geborand","group":1},
    {"name":"Champtercier","group":1},
    {"name":"Cravatte","group":1},
    {"name":"Count","group":1},
    {"name":"OldMan","group":1},
    {"name":"Labarre","group":2},
    {"name":"Valjean","group":2},
    {"name":"Marguerite","group":3},
    {"name":"Mme.deR","group":2},
    {"name":"Isabeau","group":2},
    {"name":"Gervais","group":2},
    {"name":"Tholomyes","group":3},
    {"name":"Listolier","group":3},
    {"name":"Fameuil","group":3},
    {"name":"Blacheville","group":3},
    {"name":"Favourite","group":3},
    {"name":"Dahlia","group":3},
    {"name":"Zephine","group":3},
    {"name":"Fantine","group":3},
    {"name":"Mme.Thenardier","group":4},
    {"name":"Thenardier","group":4},
    {"name":"Cosette","group":5},
    {"name":"Javert","group":4},
    {"name":"Fauchelevent","group":0},
    {"name":"Bamatabois","group":2},
    {"name":"Perpetue","group":3},
    {"name":"Simplice","group":2},
    {"name":"Scaufflaire","group":2},
    {"name":"Woman1","group":2},
    {"name":"Judge","group":2},
    {"name":"Champmathieu","group":2},
    {"name":"Brevet","group":2},
    {"name":"Chenildieu","group":2},
    {"name":"Cochepaille","group":2},
    {"name":"Pontmercy","group":4},
    {"name":"Boulatruelle","group":6},
    {"name":"Eponine","group":4},
    {"name":"Anzelma","group":4},
    {"name":"Woman2","group":5},
    {"name":"MotherInnocent","group":0},
    {"name":"Gribier","group":0},
    {"name":"Jondrette","group":7},
    {"name":"Mme.Burgon","group":7},
    {"name":"Gavroche","group":8},
    {"name":"Gillenormand","group":5},
    {"name":"Magnon","group":5},
    {"name":"Mlle.Gillenormand","group":5},
    {"name":"Mme.Pontmercy","group":5},
    {"name":"Mlle.Vaubois","group":5},
    {"name":"Lt.Gillenormand","group":5},
    {"name":"Marius","group":8},
    {"name":"BaronessT","group":5},
    {"name":"Mabeuf","group":8},
    {"name":"Enjolras","group":8},
    {"name":"Combeferre","group":8},
    {"name":"Prouvaire","group":8},
    {"name":"Feuilly","group":8},
    {"name":"Courfeyrac","group":8},
    {"name":"Bahorel","group":8},
    {"name":"Bossuet","group":8},
    {"name":"Joly","group":8},
    {"name":"Grantaire","group":8},
    {"name":"MotherPlutarch","group":9},
    {"name":"Gueulemer","group":4},
    {"name":"Babet","group":4},
    {"name":"Claquesous","group":4},
    {"name":"Montparnasse","group":4},
    {"name":"Toussaint","group":5},
    {"name":"Child1","group":10},
    {"name":"Child2","group":10},
    {"name":"Brujon","group":4},
    {"name":"Mme.Hucheloup","group":8}
  ],
  "links":[
    {"source":1,"target":0,"value":1},
    {"source":2,"target":0,"value":8},
    {"source":3,"target":0,"value":10},
    {"source":3,"target":2,"value":6},
    {"source":4,"target":0,"value":1},
    {"source":5,"target":0,"value":1},
    {"source":6,"target":0,"value":1},
    {"source":7,"target":0,"value":1},
    {"source":8,"target":0,"value":2},
    {"source":9,"target":0,"value":1},
    {"source":11,"target":10,"value":1},
    {"source":11,"target":3,"value":3},
    {"source":11,"target":2,"value":3},
    {"source":11,"target":0,"value":5},
    {"source":12,"target":11,"value":1},
    {"source":13,"target":11,"value":1},
    {"source":14,"target":11,"value":1},
    {"source":15,"target":11,"value":1},
    {"source":17,"target":16,"value":4},
    {"source":18,"target":16,"value":4},
    {"source":18,"target":17,"value":4},
    {"source":19,"target":16,"value":4},
    {"source":19,"target":17,"value":4},
    {"source":19,"target":18,"value":4},
    {"source":20,"target":16,"value":3},
    {"source":20,"target":17,"value":3},
    {"source":20,"target":18,"value":3},
    {"source":20,"target":19,"value":4},
    {"source":21,"target":16,"value":3},
    {"source":21,"target":17,"value":3},
    {"source":21,"target":18,"value":3},
    {"source":21,"target":19,"value":3},
    {"source":21,"target":20,"value":5},
    {"source":22,"target":16,"value":3},
    {"source":22,"target":17,"value":3},
    {"source":22,"target":18,"value":3},
    {"source":22,"target":19,"value":3},
    {"source":22,"target":20,"value":4},
    {"source":22,"target":21,"value":4},
    {"source":23,"target":16,"value":3},
    {"source":23,"target":17,"value":3},
    {"source":23,"target":18,"value":3},
    {"source":23,"target":19,"value":3},
    {"source":23,"target":20,"value":4},
    {"source":23,"target":21,"value":4},
    {"source":23,"target":22,"value":4},
    {"source":23,"target":12,"value":2},
    {"source":23,"target":11,"value":9},
    {"source":24,"target":23,"value":2},
    {"source":24,"target":11,"value":7},
    {"source":25,"target":24,"value":13},
    {"source":25,"target":23,"value":1},
    {"source":25,"target":11,"value":12},
    {"source":26,"target":24,"value":4},
    {"source":26,"target":11,"value":31},
    {"source":26,"target":16,"value":1},
    {"source":26,"target":25,"value":1},
    {"source":27,"target":11,"value":17},
    {"source":27,"target":23,"value":5},
    {"source":27,"target":25,"value":5},
    {"source":27,"target":24,"value":1},
    {"source":27,"target":26,"value":1},
    {"source":28,"target":11,"value":8},
    {"source":28,"target":27,"value":1},
    {"source":29,"target":23,"value":1},
    {"source":29,"target":27,"value":1},
    {"source":29,"target":11,"value":2},
    {"source":30,"target":23,"value":1},
    {"source":31,"target":30,"value":2},
    {"source":31,"target":11,"value":3},
    {"source":31,"target":23,"value":2},
    {"source":31,"target":27,"value":1},
    {"source":32,"target":11,"value":1},
    {"source":33,"target":11,"value":2},
    {"source":33,"target":27,"value":1},
    {"source":34,"target":11,"value":3},
    {"source":34,"target":29,"value":2},
    {"source":35,"target":11,"value":3},
    {"source":35,"target":34,"value":3},
    {"source":35,"target":29,"value":2},
    {"source":36,"target":34,"value":2},
    {"source":36,"target":35,"value":2},
    {"source":36,"target":11,"value":2},
    {"source":36,"target":29,"value":1},
    {"source":37,"target":34,"value":2},
    {"source":37,"target":35,"value":2},
    {"source":37,"target":36,"value":2},
    {"source":37,"target":11,"value":2},
    {"source":37,"target":29,"value":1},
    {"source":38,"target":34,"value":2},
    {"source":38,"target":35,"value":2},
    {"source":38,"target":36,"value":2},
    {"source":38,"target":37,"value":2},
    {"source":38,"target":11,"value":2},
    {"source":38,"target":29,"value":1},
    {"source":39,"target":25,"value":1},
    {"source":40,"target":25,"value":1},
    {"source":41,"target":24,"value":2},
    {"source":41,"target":25,"value":3},
    {"source":42,"target":41,"value":2},
    {"source":42,"target":25,"value":2},
    {"source":42,"target":24,"value":1},
    {"source":43,"target":11,"value":3},
    {"source":43,"target":26,"value":1},
    {"source":43,"target":27,"value":1},
    {"source":44,"target":28,"value":3},
    {"source":44,"target":11,"value":1},
    {"source":45,"target":28,"value":2},
    {"source":47,"target":46,"value":1},
    {"source":48,"target":47,"value":2},
    {"source":48,"target":25,"value":1},
    {"source":48,"target":27,"value":1},
    {"source":48,"target":11,"value":1},
    {"source":49,"target":26,"value":3},
    {"source":49,"target":11,"value":2},
    {"source":50,"target":49,"value":1},
    {"source":50,"target":24,"value":1},
    {"source":51,"target":49,"value":9},
    {"source":51,"target":26,"value":2},
    {"source":51,"target":11,"value":2},
    {"source":52,"target":51,"value":1},
    {"source":52,"target":39,"value":1},
    {"source":53,"target":51,"value":1},
    {"source":54,"target":51,"value":2},
    {"source":54,"target":49,"value":1},
    {"source":54,"target":26,"value":1},
    {"source":55,"target":51,"value":6},
    {"source":55,"target":49,"value":12},
    {"source":55,"target":39,"value":1},
    {"source":55,"target":54,"value":1},
    {"source":55,"target":26,"value":21},
    {"source":55,"target":11,"value":19},
    {"source":55,"target":16,"value":1},
    {"source":55,"target":25,"value":2},
    {"source":55,"target":41,"value":5},
    {"source":55,"target":48,"value":4},
    {"source":56,"target":49,"value":1},
    {"source":56,"target":55,"value":1},
    {"source":57,"target":55,"value":1},
    {"source":57,"target":41,"value":1},
    {"source":57,"target":48,"value":1},
    {"source":58,"target":55,"value":7},
    {"source":58,"target":48,"value":7},
    {"source":58,"target":27,"value":6},
    {"source":58,"target":57,"value":1},
    {"source":58,"target":11,"value":4},
    {"source":59,"target":58,"value":15},
    {"source":59,"target":55,"value":5},
    {"source":59,"target":48,"value":6},
    {"source":59,"target":57,"value":2},
    {"source":60,"target":48,"value":1},
    {"source":60,"target":58,"value":4},
    {"source":60,"target":59,"value":2},
    {"source":61,"target":48,"value":2},
    {"source":61,"target":58,"value":6},
    {"source":61,"target":60,"value":2},
    {"source":61,"target":59,"value":5},
    {"source":61,"target":57,"value":1},
    {"source":61,"target":55,"value":1},
    {"source":62,"target":55,"value":9},
    {"source":62,"target":58,"value":17},
    {"source":62,"target":59,"value":13},
    {"source":62,"target":48,"value":7},
    {"source":62,"target":57,"value":2},
    {"source":62,"target":41,"value":1},
    {"source":62,"target":61,"value":6},
    {"source":62,"target":60,"value":3},
    {"source":63,"target":59,"value":5},
    {"source":63,"target":48,"value":5},
    {"source":63,"target":62,"value":6},
    {"source":63,"target":57,"value":2},
    {"source":63,"target":58,"value":4},
    {"source":63,"target":61,"value":3},
    {"source":63,"target":60,"value":2},
    {"source":63,"target":55,"value":1},
    {"source":64,"target":55,"value":5},
    {"source":64,"target":62,"value":12},
    {"source":64,"target":48,"value":5},
    {"source":64,"target":63,"value":4},
    {"source":64,"target":58,"value":10},
    {"source":64,"target":61,"value":6},
    {"source":64,"target":60,"value":2},
    {"source":64,"target":59,"value":9},
    {"source":64,"target":57,"value":1},
    {"source":64,"target":11,"value":1},
    {"source":65,"target":63,"value":5},
    {"source":65,"target":64,"value":7},
    {"source":65,"target":48,"value":3},
    {"source":65,"target":62,"value":5},
    {"source":65,"target":58,"value":5},
    {"source":65,"target":61,"value":5},
    {"source":65,"target":60,"value":2},
    {"source":65,"target":59,"value":5},
    {"source":65,"target":57,"value":1},
    {"source":65,"target":55,"value":2},
    {"source":66,"target":64,"value":3},
    {"source":66,"target":58,"value":3},
    {"source":66,"target":59,"value":1},
    {"source":66,"target":62,"value":2},
    {"source":66,"target":65,"value":2},
    {"source":66,"target":48,"value":1},
    {"source":66,"target":63,"value":1},
    {"source":66,"target":61,"value":1},
    {"source":66,"target":60,"value":1},
    {"source":67,"target":57,"value":3},
    {"source":68,"target":25,"value":5},
    {"source":68,"target":11,"value":1},
    {"source":68,"target":24,"value":1},
    {"source":68,"target":27,"value":1},
    {"source":68,"target":48,"value":1},
    {"source":68,"target":41,"value":1},
    {"source":69,"target":25,"value":6},
    {"source":69,"target":68,"value":6},
    {"source":69,"target":11,"value":1},
    {"source":69,"target":24,"value":1},
    {"source":69,"target":27,"value":2},
    {"source":69,"target":48,"value":1},
    {"source":69,"target":41,"value":1},
    {"source":70,"target":25,"value":4},
    {"source":70,"target":69,"value":4},
    {"source":70,"target":68,"value":4},
    {"source":70,"target":11,"value":1},
    {"source":70,"target":24,"value":1},
    {"source":70,"target":27,"value":1},
    {"source":70,"target":41,"value":1},
    {"source":70,"target":58,"value":1},
    {"source":71,"target":27,"value":1},
    {"source":71,"target":69,"value":2},
    {"source":71,"target":68,"value":2},
    {"source":71,"target":70,"value":2},
    {"source":71,"target":11,"value":1},
    {"source":71,"target":48,"value":1},
    {"source":71,"target":41,"value":1},
    {"source":71,"target":25,"value":1},
    {"source":72,"target":26,"value":2},
    {"source":72,"target":27,"value":1},
    {"source":72,"target":11,"value":1},
    {"source":73,"target":48,"value":2},
    {"source":74,"target":48,"value":2},
    {"source":74,"target":73,"value":3},
    {"source":75,"target":69,"value":3},
    {"source":75,"target":68,"value":3},
    {"source":75,"target":25,"value":3},
    {"source":75,"target":48,"value":1},
    {"source":75,"target":41,"value":1},
    {"source":75,"target":70,"value":1},
    {"source":75,"target":71,"value":1},
    {"source":76,"target":64,"value":1},
    {"source":76,"target":65,"value":1},
    {"source":76,"target":66,"value":1},
    {"source":76,"target":63,"value":1},
    {"source":76,"target":62,"value":1},
    {"source":76,"target":48,"value":1},
    {"source":76,"target":58,"value":1}
  ]
}

}
.node {
  stroke: #fff;
  stroke-width: 1.5px;
}

.link {
  stroke: #999;
  stroke-opacity: .6;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

However, I can't figure out how to generate the radial graph above when the structure is not hierarchical. In the example given here
https://gist.github.com/mbostock/7607999

they use the bundle() and cluster.nodes() functions which require a hierarchical data structure. Can I use the same json data structure that I use for the force-directed graph for this type of radial graph? If yes, how?
EDIT: Here is a (non-working) JSFiddle http://jsfiddle.net/12sb8jxg/
I added
nested = d3.nest()
.key(function (d) {
return d.group;
})
.entries(graph.nodes);

but
cluster.nodes(nested)

still doesn't append the .x, .y, .parent etc. necessary for the bundle function to work.


text:
Q: apply encoding algorithm from original and encoded string onto new string I have an ecoded string and the original string.
Is it possible to apply the used algorithm without knowing it onto another string?
Those are the strings:
num1 = "1193"
encoded1 =  "7ecb452bee6a1b227bc3"

num2 = "1259"
encoded2 = "7ecfb3daff5acd1b7ab2"

If you know how these strings were encrypted that would also make it easier :D


text:
Q: How do I get the current time in a different time zone without setting TZ variable How do I get the current time in a different time zone without setting tz variable (because I don't want to change my local time zone (IST)).
For example: I need different timezone time like (PST, EST,....).

A: Can you not use something like linux's time.h and then do post processing for your different time zones?
void linux_time_get
(
    os_time_t* p_time_seconds,
    os_time_us_t* p_time_microseconds
)
{
    struct timeval tv;
    gettimeofday(&tv, NULL); /* Second arg is timezone */
    if (p_time_seconds)
    {
        *p_time_seconds = tv.tv_sec;
    }
    if (p_time_microseconds)
    {
        *p_time_microseconds = tv.tv_usec;
    }
}

And then the caller of this function modifies 'p_time_seconds' and 'p_time_microseconds' according to which timezone you want to use?
Alternatively you could make a local variable for 'tz', to be parsed in as the second arg to the 'gettimeofday()' function.


text:
Q: How can I launch a Virtualbox VM from the Dock? How can I put my VirtualBox on my Dock in Mac OS X Lion.  I want to have it on my dock so I can click on it to launch it.

A: Right click VM in Manager, create desktop icon.  Select the desktop icon and press Control+Shift+Command+T
That's it done

A: I don't use Virtualbox, but based on a couple resources, it looks like you can launch a specific VM from the command line, which means we can create a basic Automator application to serve as a launcher, which you can then put in the Dock.
In Automator, create a new workflow. Add a Run Shell Script action, and enter /abolute/path/to/vboxmanage startvm "vmname" in the text box. Replace vmname with the name of your VM as it appears in the Virtualbox GUI (make sure to keep the quotes though). Save the workflow, setting the File Format to Application. Then drag the resulting app onto your Dock.


text:
Q: Snowflake - Dense_rank starting at 2 rather than 1 I'm using the following statement in a query:
 CASE WHEN apercent IS NULL THEN NULL ELSE dense_rank() over (partition by adate order by apercent desc) END as arank

For some reason the ranked results are starting at 2 rather than 1. There are no tied values, but there are some NULL values. I'm assuming it's because of the NULLs. Any way to update this to force the rank to begin at 1?
Current Results:

arank
apercent

2
23.57

3
13.61

4
10.67

5
6.14

6
6.00

7
5.79

8
5.57

9
5.27

10
4.80

NULL
NULL

Desired Result:

arank
apercent

1
23.57

2
13.61

3
10.67

4
6.14

5
6.00

6
5.79

7
5.57

8
5.27

9
4.80

NULL
NULL

A: A simple solution is to use NULLS LAST:
(CASE WHEN apercent IS NOT NULL
      THEN dense_rank() over (partition by adate order by apercent desc nulls last)
 END) as arank

Alternatively, you could partition by NULL values so they are not included in the counting for non-NULL values:
(CASE WHEN apercent IS NOT NULL
      THEN dense_rank() over (partition by adate, apercent is null order by apercent desc)
 END) as arank

A: If your percentages can't be negative, you could mimic nulls last by using coalesce
case when apercent is null then null
     else dense_rank() over (partition by adate order by coalesce(apercent,0.00) desc)
end as arank


text:
Q: Search bing maps with latitude and longitude - c# I currently have the following method being called whenever a location is selected.
Instead of passing the city name as the parameter to search by, I would like to search locations by using latitudes and longitudes.
I will be retrieving the latitude and longitude of the selected city.
How would I need to modify this code in order to obtain this?
Thank you
private void xgrdLocation_SelectedItemChanged(object sender, SelectedItemChangedEventArgs e)
        {
            this.Cursor = Cursors.AppStarting;
            lblFooter.Content = "Searching ...";
            pushpin = new MapPushpin();
            if (xgrdLocation.SelectedItem != null)
            {
                City selectedCity = xgrdLocation.SelectedItem as City;
                //GeocodeService.Location point = new GeocodeService.Location();
                pushpin.Text = selectedCity.CityName;
                searchDataProvider.Search(pushpin.Text);
                //lblSelectedCity.Content = selectedCity.CityName;
            }
        }

A: If you want to get the city that a latitude/longitude value is in, you can use the Reverse Geocoding. The Bing Maps REST Location API has such a feature. https://msdn.microsoft.com/en-us/library/ff701710.aspx
You can also find documentation on how to use the REST services in .NET here: https://msdn.microsoft.com/en-us/library/jj819168.aspx
Not sure, but it looks like you might be using the old legacy SOAP services in your application to do the geocoding currently. Avoid the SOAP services, they are old, slow and nearing end of life.