text:
Q: git push origin master error: The following untracked working tree files would be overwritten by merge: .DS_Store It's been a while that I am facing the following problem. What's the fix to it? I am just a newbie in git so please be instructive. I have already tried to follow the commands shown in the error but wasn't successful.
Monas-MacBook-Pro:demo mona$ git branch
* master
Monas-MacBook-Pro:demo mona$ git add .
Monas-MacBook-Pro:demo mona$ git commit -m "logo fixed"
[master 62bedf3] logo fixed
 1 file changed, 8 insertions(+), 7 deletions(-)
Monas-MacBook-Pro:demo mona$ ls
1a
Monas-MacBook-Pro:demo mona$ git push
fatal: The current branch master has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin master

Monas-MacBook-Pro:demo mona$ git push origin master
To https://lamiastella@bitbucket.org/lamiastella/vldb-demo.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'https://lamiastella@bitbucket.org/lamiastella/vldb-demo.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Integrate the remote changes (e.g.
hint: 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
Monas-MacBook-Pro:demo mona$ git pull origin master
From https://bitbucket.org/lamiastella/vldb-demo
 * branch            master     -> FETCH_HEAD
error: The following untracked working tree files would be overwritten by merge:
    .DS_Store
Please move or remove them before you can merge.
Aborting
Monas-MacBook-Pro:demo mona$ git pull
There is no tracking information for the current branch.
Please specify which branch you want to merge with.
See git-pull(1) for details

    git pull <remote> <branch>

If you wish to set tracking information for this branch you can do so with:

    git branch --set-upstream-to=origin/<branch> master

Monas-MacBook-Pro:demo mona$

A: Those are OS X internal files. Somebody must have checked them in by mistake. Just move them to a different folder, do the merge, move back and add the .DS_Store folder to .gitignore and you should be fine.


text:
Q: upload application to azure batch job failed while uploading from azure portal I am trying to upload an application to newly created azure batch account from the portal I followed below steps-
1) Created a azure batch account.
2) Create .zip of the application exe in local desktop
3) Go to the application options
4) Click on add applications
5) Give applicationid, version and application package path by selecting the .zip from local machine.
6) Click on submit

Got different Errors-

*

*ajaxExtended call failed

*Upload Error for ffmpeg.zip

*Upload block blob to blob store failed. Details: StatusCode = 201, StatusText = Created.

A: This happened to me as well, and like Phil G, I noticed that a message was showing up in F12 developer tools that 'the auto storage account keys are invalid.'.  However, they were valid.
The problem was that I had turned off 'allow access from all networks' under firewalls and network configuration.   Changing this back to 'allow access from all networks' worked, at the tradeoff of security.
If relevant, I'm using a cluster with public access disabled, and user subscription pool allocation mode.

A: Actually when we upload a .zip file in this case it's failing, its better to use Azure Batch Explorer, its a desktop application.
https://azure.github.io/BatchExplorer/
Than you can easily add a package/ application to your batch account.
Also I was getting the same error when uploading a file to blob container from azure portal, so I used Microsoft Azure Explorer to upload and download the files.

A: I had a slightly different error and the message was very vague:
Upload Error for ffmpeg-3.4-win64-static.zip
File Upload encountered an unexpected error during upload.

Batch Explorer also failed to upload the file.
By looking at the network traffic in my browser I saw the POST request recieved a success 200 code, but looking inside the response JSON I saw the detailed error:
HHTP Status 409 - The auto storage account keys are invalid, please
sync auto storage keys.

I'd changed them a day ago, and had successfully used the new ones in a batch app, but in order for the batch account to automatically upload the application to the storage account they keys needed to be synchronized.
Quick fix was to sync the keys and all was good.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Polar sets and weak star topology I have to prove the following:
Let X a real normed space, and I a non-empty index set. Let $ \{ x_{i}, i \in I \}$ $\subset$ X ,   $\{  \alpha_{i},\ i \in I \}$ a set of positive real numbers.
Define $ S:= \{x^{*} \in X^{*}, ||{x^{*}}|| \leq R \ and \ |x^{*}(x_{i})| \leq \alpha_{i}, \forall i \in I \} $. Show that $\forall \  x_{0} \in X$, the set $ \{x^{*}(x_{0}), \ x^{*} \in S \} $ is a bounded closed interval in the real line.
My claim was the following:
$ \forall i \in I $, let $ x_{i}^{\circ} = \{x^{*} \in X^{*}, \ such \ that \ |x^{*}(x_{i})| \leq 1 \}$ the polar of $x_{i}$. Then we know that $\alpha_{i} x_{i}^{\circ} = (x_{i}/\alpha_{i})^{\circ}$.
Now we can characterize $S= B_{R}^{\star} \  \cap \ \cap_{i \in I} (x_{i}/\alpha_{i})^{\circ}$. Thus S is $wk^{\star}$compact because $B_{R}^{\star}$ is $wk^{\star}$compact  (Banach-Alaoglu Theorem) and $\cap_{i \in I} (x_{i}/\alpha_{i})^{\circ} = (\cup_{i \in I} (x_{i}/\alpha_{i}))^{\circ}$ which is $wk^{\star}$ closed because polars are.
Thus if we take the evaluation map $\phi_{x_{0}}:S \to \mathbb{R}$ such that $\phi_{x_{0}}(x^{*})=x^{*}(x_{0})$, this is a continuous map from a compact set so its image must be compact, therefore it is bounded and closed.
Am I missing something or it sounds good?
Thanks in advance for any help! :)

A: First observe that $S$ is closed. It follows from the fact that if $x^*_n\in S$ and $x^*_n\to y^*$ in the weak* topology then $||y^* ||\leq R$ and $|y^* (x_i ) |\leq \alpha_i $ for all $i\in I.$ So $S$ is closed in weak* topology in $X^*.$
Moreover $S$ is convex this follows from the fact that the sets $$H^{x_i}_{\alpha_i } =\{ x^* \in X^* : |x^* (x_i )|\leq \alpha_i \}$$ are convex and $$S=\{x^*\in X:||x^* ||\leq R\}\cap\bigcap_{i\in I} H^{x_i}_{\alpha_i }$$
Moreover from the above follows that the set $S$ is also bounded.
Now observe that $$\{x^* (x_0 ): x\in S \} = k_{x_0} (S)$$ where $k_{x_0 }: X^{*} \to\mathbb{R} $ is defined by $$k_{x_0 } (x^* ) =x^* (x_0 ).$$
Moreover $k_{x_0} $ is continous when $X^*$ is equiped with  weak* topology this follows from fact topology $$k_{x_0 } (\{x\in X^* : |x^* (x_0 )|<\varepsilon \} ) \subset (-\varepsilon , \varepsilon ).$$
So we prove that $S$ is closed bounded and convex set in weak* topology and hence by Banach - Alaoglu theorem it is compact in weak* topology.
The set $\{x^* (x_0 ): x\in S \} = k_{x_0} (S)$ is a image of compact convex set by a continous linear functional and hence it is compact convex subset of real line thus it is a closed interval.


text:
Q: Using StealJS to load Bower components lacking a bower.json file I am using the StealJS + Bower integration in my application, but a couple of my Bower components (including es6-collections) do not contain a bower.json file. Because es6-collections is one of the dependencies in my project's bower.json file, StealJS tries to load the es6-collections component's bower.json file, cannot find it because it does not exist, and complains: Unable to load the bower.json for es6-collections. I tried using System.config({ path: { 'es6-collections': '...' } }) to notify StealJS of the path to the script to use when loading es6-collections, but that does not help. What can I do to get StealJS to load this component?

A: Assumptions
So I am going to make a few assumptions:

*

*you are using steal from bower

*you are "bower install"'ing es6-collections from github directly

*you are implicitly using the system-bower plugin by using the HTML <script src="bower_components/steal/steal.js" main="main"></script> to load your "main" file

If these things seem mostly true-ish then you may just have to add some configuration in your bower.json file to silence the error/warning and have everything work as expected.
Explanation:
So because the system-bower plugin (which you are using implicitly because steal detects it is being loaded from a bower_components directory) uses the components bower.json files to determine entry points, so in this case the error/warning comes from not being able to find es6-collections bower.json file.
Solution:
So we just need to tell System (used by steal) where to find that module and that it can stop looking for it's bower.json file.
We can do that by adding a "system" property to the bower.json and adding some configuration data like this...
"system": {
  "paths": {
    "es6-collections": "bower_components/es6-collections/index.js"
  },
  "bowerIgnore": ["es6-collections"],
  "meta": {
    "es6-collections": {
      "format": "global"
    }
  }
}

*

*The paths configuration there, tells System where to find the module

*The bowerIgnore array tells system-bower to not look for the bower.json for that module

*and the meta config is there to tell System to treat this module like it's a script that is going to add to the global object (window in the browser), which you should probably do for this particular module because of the way es6-collections was written: it exports an empty object if it has nothing to pollyfill so you can't use the exported object, best to just use it as if it was a global module.

For more information on all these things...
http://stealjs.com/docs/bower.html
https://github.com/systemjs/systemjs/wiki/Meta-Configuration
http://stealjs.com/docs/steal.html
Just to have a working example here https://gist.github.com/BigAB/c108bb0860c9cfee3d6a are three files you can copy-paste/clone and then do a bower install and see it working.


text: Q: Is there an equivalent of C's #define in JavaScript? Title says it all. I'm sure there's already answers on the internet, but due to Google's limitations in searching for non alphanumeric characters, I'm only getting results about TypeScript define keyword.


text:
Q: Не работает код biopython Пытаюсь освоить biopython, всё установил, нашёл учебник.
Там просят запустить этот код:
from Bio.SeqIO import parse
from Bio.SeqRecord import SeqRecord
from Bio.Seq import Seq

file = open("example.fasta")

records = parse(file, "fasta") for record in records:
   print("Id: %s" % record.id)
   print("Name: %s" % record.name)
   print("Description: %s" % record.description)
   print("Annotations: %s" % record.annotations)
   print("Sequence Data: %s" % record.seq)
   print("Sequence Alphabet: %s" % record.seq.alphabet)

example.fasta выглядит так:
>sp|P25730|FMS1_ECOLI CS1 fimbrial subunit A precursor (CS1 pilin)
MKLKKTIGAMALATLFATMGASAVEKTISVTASVDPTVDLLQSDGSALPNSVALTYSPAV
NNFEAHTINTVVHTNDSDKGVVVKLSADPVLSNVLNPTLQIPVSVNFAGKPLSTTGITID
SNDLNFASSGVNKVSSTQKLSIHADATRVTGGALTAGQYQGLVSIILTKSTTTTTTTKGT

>sp|P15488|FMS3_ECOLI CS3 fimbrial subunit A precursor (CS3 pilin)
MLKIKYLLIGLSLSAMSSYSLAAAGPTLTKELALNVLSPAALDATWAPQDNLTLSNTGVS
NTLVGVLTLSNTSIDTVSIASTNVSDTSKNGTVTFAHETNNSASFATTISTDNANITLDK
NAGNTIVKTTNGSQLPTNLPLKFITTEGNEHLVSGNYRANITITSTIKGGGTKKGTTDKK

Консоль выдает ошибку:
records = parse(file, "fasta") for record in records:
                                     ^
SyntaxError: invalid syntax

Помогите, пожалуйста, разобраться! :(

A: Возможно Вам стоит перенести цикл for record in records: на новую строку?))
Должно быть так:
records = parse(file, "fasta")
for record in records:
   print("Id: %s" % record.id)
   print("Name: %s" % record.name)
   print("Description: %s" % record.description)
   print("Annotations: %s" % record.annotations)
   print("Sequence Data: %s" % record.seq)
   print("Sequence Alphabet: %s" % record.seq.alphabet)


text:
Q: ActiveRecord Claims No Adaptor Specified When I try to run the following, I get an error back from ActiveRecord stating that the connector hasn't been found.
require 'activerecord'
ActiveRecord::Base.establish_connection(
    :adaptor => "sqlite3",
    :database => "db.sqlite3"
)

Error Message:
>> ActiveRecord::Base.establish_connection("adaptor" => "sqlite3-ruby")
ActiveRecord::AdapterNotSpecified: database configuration does not specify
    adapter from
/System/Library/Frameworks/Ruby.framework/Versions/1.8/usr/lib/ruby/gems/1.8/
gems/activerecord/2.2.2/lib/active_record/connection_adapters/abstract/
connection_specification.rb:64:in `establish_connection'

Is the ActiveRecord gem broken, or is the initial code incorrect?

A: Looks like you misspelled "adapter" in your arguments. -er and -or are both proper in English, but does AR expect a specific one? Judging by the error message, they want -er.


text:
Q: Array Index out of bound 2D array I have a 2D array where no. of rows is 1 and no. of columns is > 1.
double[][] T = new double[1][24];
System.out.println(T[1].length);

But when i print the length of the columns, its says the index is out of bounds.
but when i print the following,
System.out.println(T[0].length);

I get the result as 24. But shouldn't T[0] should be equal to 1 and T[1] be equal to 24?
Why am I getting this error?
I suppose, java considers the above array as 1D array since it has only one row. but I need it to be a 2D array for further processes. Could anyone please help?

A: Array indices are 0-based.
If your array length is 1 (for the 1st dimension here), then you can only reference element 0.
In other words:

*

*The declaration states the desired size (1 here)

*The element reference states the desired 0-based index (0 here)

A: Array indices start from 0.
Your array length is 1, so T[0] is a valid index but T[1] is not.

A: System.out.println(T[0].length);

is correct. Because Array index starts from 0

A: Array is zero based so when double[][] T = new double[1][24];
you created a 2d array first dimension is 1 and the second is 24 so that's 1*24 Array
So System.out.println(T[1].length); gave you java.lang.arrayindexoutofboundsexception As arrays are zero based
if you wrote this double[][] T = new double[3][24];  you got 3*24 Array :-
System.out.println(T[0].length);//24
System.out.println(T[1].length);//24
System.out.println(T[2].length);//24
System.out.println(T[3].length);//java.lang.arrayindexoutofboundsexception

A: Array index starts from 0.
double[][] T = new double[1][24];

which can be also declared as follows:
double[][] T = new double[1][];
T[0] = new double[24];

A: imagine matrix of 1X24. you don't have 2nd column so obvious it will through nullpointerException.

A: In Java/Android and many other languages this is how is declared
matrix[numRows][numColumns]

And since Array indices start from 0 you need to be carefull to be sure that you are accessing a single value
x = matrix[0][1]

Or if you are accesing the first row (as a single dimension array)
x = matrix[0]

A: Array index start with 0 not 1.
If your array length is 1  then you can start from 0.
so T[0] is a valid index but T[1] is not


text:
Q: Using ExceptionReceived in OnMessageOptions I'm trying to use the method QueueClient.OnMessage(Action<BrokeredMessage>, OnMessageOptions). In the OnMessageOptions I coded this simple ExceptionReceived event:
void LogErrors(object sender, ExceptionReceivedEventArgs e)
{
  if (e.Exception != null)
  {
    Trace.TraceError("Exception captured: " + e.Exception.Message);
  }
}

My doubt is how to get the "LogErrors" the BrokeredMessage that is being processend in the callback in order to save a log with errors when BrokeredMessages are occured.

A: I tried to see how to get the message from/within the ExceptionReceived callback but the information is not present in the arguments. Here is my sample code:
var connectionString = "my-connection-string";
var queueName = "my-queue-name";
var client = QueueClient.CreateFromConnectionString(connectionString, queueName);

var options = new OnMessageOptions();
options.ExceptionReceived += (sender, args) =>
{
    // Neither sender or args contains information about the message being processed
};

client.OnMessage(brokeredMessage =>
{
    throw new Exception();
}, options);

Depending on your need, the simple solution is to wrap your callback inside a try/catch:
client.OnMessage(brokeredMessage =>
{
    try
    {
        // Process the message
        ...

       // Complete the message (depends on the )
       brokeredMessage.Complete();
    }
    catch (Exception ex)
    {

        Trace.TraceError("Exception captured: " + ex.Message);

        // Here you have access to the brokeredMessage so you can log what you want.
        ...
        //Abandon the message so that it could be re-process ??
        brokeredMessage.Abandon();
    }

}, options);

After you can put this wrapper in a function or create an extension method for QueueClient :
public static class QueueClientExtensions
{
    public static void OnCustomMessage(this QueueClient queueClient, Action<BrokeredMessage> callback,
        OnMessageOptions onMessageOptions)
    {
        queueClient.OnMessage(message =>
        {
            try
            {
                // process the message
                callback(message);

                //complete if success
                message.Complete();
            }
            catch (Exception ex)
            {
                // Here you have access to the brokeredMessage so you can log what you want.
                // message.GetBody<string>()
                Trace.TraceError("Exception captured: " + ex.Message);

                //Abandon the message so that it could be re-process
                message.Abandon();
            }

        }, onMessageOptions);
    }
}

And call this method in the same way:
var queueClient = QueueClient.CreateFromConnectionString(connectionString, queueName);
queueClient.OnCustomMessage(brokeredMessage =>
{
    // Process the message
    ...
}, new OnMessageOptions());


text:
Q: How could you retrieve a range of user highlighted cells in Google Sheets using Google Apps Script? At the moment this is the function I'm using but I have no way of testing if it will work in the spreadsheet until I publish the application.
function readSelection() {
  //The commented lines aren't needed if the sheet is open already
  //var sheetid = "sheet id here";
  //var spreadsheet = SpreadsheetApp.openById(sheetid);
  //SpreadsheetApp.setActiveSpreadsheet(spreadsheet);

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();
  //sheet.setActiveSelection("B2:B22");
  var activerange = sheet.getActiveRange();
  var activecells = activerange.getValues();

  return activecells;
 };

A: I assume you mean highlighted == selected
The result depends on whether the cells are contiguous or not (non contiguous cell selection is available in the new spreadsheets features http://googleblog.blogspot.co.nz/2013/12/new-google-sheets-faster-more-powerful.html
For contiguous cells selected your code returns the values of the selection as an array, for non-contiguous cells your code will return the an array with the single value of the LAST selected item.
I suggest that this is a bug in the implementation of the new spreadsheet. If it is important to you, I suggest you raise an issue. For the old spreadsheets, you can only select contiguous cells (eg B2:B22) so it will work as you expect.
The easiest way to answer this Q is to run the code you have written! You don't have to publish anything just run the code in the script editor of the spreadsheet you are examining
and look at the log.
 function readSelection() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();

  var activerange = sheet.getActiveRange();

  var activecells = activerange.getValues();
Logger.log(activecells)
  return
 };

A: There is no way to do this at the moment or to obtain the selected ranges from a script.
A request is pending and you can support it here : https://code.google.com/p/google-apps-script-issues/issues/detail?id=4056
by adding a star to the request.
If/when this function is implemented your code would look as follows:
 function readSelection() {

  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = SpreadsheetApp.getActiveSheet();

  var activeranges = sheet.getSelectedRanges();
  var activecells = [] ;'

  for (var ar in activeranges)
     activecells = activecells.concat(activeranges[ar].getValues()) ;

  Logger.log(activecells)
  return ;
  }

note that selected ranges may overlap, so some cell contents could be added twice.


text:
Q: операции с double результат расчетов print.Price — всегда целое число.

Первый случай:
s[1] "0,008459" string
instrument.PriceStep 5E-07 double
print.Price 16918 int

Второй случай:
s[1] "0,0084585" string
instrument.PriceStep 5E-07 double
print.Price 16918 int

print.Price = (int)Math.Ceiling((double.Parse(s[1]) / instrument.PriceStep));

В обоих случаях результат — одно и тоже число. А должно быть разное.
Знаю, что это связано с ограничением размера double и периодическими дробями.
Как правильно выполнить такую операцию?

A: Для денежных значений надо использовать DECIMAL:
https://msdn.microsoft.com/ru-ru/library/364x0z75.aspx

Ключевое слово decimal обозначает 128-битный тип данных. По сравнению
  с типами данных с плавающей запятой, диапазон значений типа decimal
  меньше, а точность выше, благодаря чему этот тип подходит для
  финансовых расчетов.

A: Ваша проблема в том, что вычисления с типом double точны только если вы остаётесь в рамках двоичных дробей, а с типом decimal — десятичных.
Сравните:
var double1 = 0.008459 / 5e-7;       // 16918.0
var double2 = 0.0084585 / 5e-7;      // 16917.000000000004

var decimal1 = 0.008459m / 5e-7m;    // 16918
var decimal2 = 0.0084585m / 5e-7m;   // 16917

Почему вычисления с double неточны? Потому что double записывает значения в двоичной системе. Но ни число 0.008459, ни дробь 1 / 5e-7 не могут быть точно представленными в двоичной системе. Поэтому результат будет приблизительно равен ожидаемому вами числу.
Чтобы в этом убедиться, имеет смысл воспользоваться точным строковым представлением двоичного числа (например, вот этим):
DoubleConverter.ToExactString(0.008459);
    // выдаёт "0.00845899999999999950561768713441779254935681819915771484375"
DoubleConverter.ToExactString(5e-7);
    // выдаёт "0.0000004999999999999999773740559129431293428069693618454039096832275390625"
DoubleConverter.ToExactString(0.008459 / 5e-7);
    // выдаёт "16918"

DoubleConverter.ToExactString(0.0084585);
    // выдаёт "0.008458500000000000740296712820054381154477596282958984375"
DoubleConverter.ToExactString(0.0084585 / 5e-7);
    // выдаёт "16917.00000000000363797880709171295166015625"

(Всегда полезно знать, что же под капотом на самом деле.)
А вот для decimal значения внутри в точности соответствуют тем десятичным дробям, которые вы вводите.


text:
Q: QODBC (Quickbooks), ODBC Mathematica connection string I am trying to connect to QuickBooks using QODBC driver. I am able to successfully connect when I use RazorSQL but can not figure out the correct statements in Mathematica (11.2) nor can Icconnect with Database Explorer.
I can successfully connect from  RazorSQL successfully in which they use the following:
Driver Class: sun.jdbc.odbc.JdbcOdbcDriver
JDBC URL: jdbc:odbc:QuickBooks Data 64-Bit QRemote
In their driver they have two other boxes:
Login:  "login name"
Password:  "password"
I don't understand how you pass this in Mathematica.  I have looked at documentation but can't seem to duplicate something that works.
I have tried:
    Needs["DatabaseLink`"]
OpenSQLConnection[

JDBC["sun.jdbc.odbc.JdbcOdbcDriver",
  "jdbc:odbc:QuickBooks Data 64-Bit"]]
Error given ----JDBC::classnotfound: sun.jdbc.odbc.JdbcOdbcDriver
and tried this
    Needs["DatabaseLink`"]
conn = OpenSQLConnection[JDBC["odbc", "QuickBooks Data 64-Bit QRemote"]]

During evaluation of In[5]:= JDBC::classnotfound: odbc
Out[6]= $Failed

I have this but not sure how I got that set up:
JDBCDriver["Version" -> 3.1,
 "Location" ->
 "C:\\ProgramData\\Mathematica\\DatabaseResources\\Quickbooks \
 Connector.m", "Description" -> Null,
"Driver" -> "sun.jdbc.odbc.JdbcOdbcDriver",
"Name" -> "Quickbooks Connector",
"Protocol" -> "jdbc:odbc:QuickBooks Data 64-Bit QRemote",
"Location" ->
"C:\\ProgramData\\Mathematica\\DatabaseResources\\Quickbooks \
Connector.m"]}

Would someone be able provide the correct Mathematica statements? Thanks David

A: There is no authentication required by QODBC. You can skip Login & Password & try to connect to QuickBooks using QODBC DSN "QuickBooks Data 64-Bit QRemote". You just need to keep QuickBooks running login to company file as an Admin & try to connect.
Please refer below mentioned article for Connecting QODBC Driver to QuickBooks for the First Time (Video):
http://support.flexquarters.com/esupport/index.php?/Default/Knowledgebase/Article/View/2512
If you are still the facing issue, Please raise a support ticket to the QODBC Technical Support department from below mentioned link & provide requested information:
http://support.flexquarters.com/esupport/index.php?/Tickets/Submit
We may need the following information, Please attach below listed files when replying to the ticket.
1) Screenshot of QODBC Setup Screen -- > About
2) Screenshot of the issue you're facing.
Share Entire Log Files as an attachment in text format from
3) QODBC Setup Screen -- > Messages -- > Review QODBC Messages
4) QODBC Setup Screen -- > Messages -- > Review SDK Messages
Refer: How to take screenshot: www.qodbc.com/links/screenshot.htm


text:
Q: Google App Engine Python Authenticated Endpoints and Android I'm not able to find a small example (or tutorial) of Android App (possibly with Android Studio) that use Authenticated Endpoints realized with GAE (possibly Python).
Google examples (Greetings and Tic Tac Toe) seems have some problem in my environment (token error, 404 not found, .....).
Can anyone help me? I'm going crazy...
Thank you in advance.

A: Are you able to access your Endpoint from api Explorer on localhost(http://localhost:8080/_ah/api/explorer ) you can even simulate authentication there.
if API explorer is working then you need to check how you define SCOPE when getting credentials.
In my experience I had problems in following areas:
1. Generating Client IDs
2. define scoping in Endpoint API
3. Specifying correct scope in android App (server:client_id:123456789-abcdefghsadffwe.apps.googleusercontent.com";

A: I'm finally able to do it.
I used this 2 google examples:
On the server side:
https://github.com/GoogleCloudPlatform/appengine-endpoints-helloendpoints-python
On the client side:
https://github.com/GoogleCloudPlatform/appengine-endpoints-helloendpoints-android
The instructions inside this pages are, in my opinion, better than the official google documentation.


text:
Q: Nested Lists and List Comprehensions I am fairly new to Python and I'm having trouble figuring out how to apply a list comprehension to part of a nested list (specifically at the index level).
For instance, if I have the following:
my_list = [[1,2], [3,7], [6,9], [4,3]]

new_list = [[i*2 for i in sublist] for sublist in my_list]

How would I alter my list comprehension to only apply the operation to index 1 of each sublist? I have experimented quite a bit with no success.

A: A more general version of mac's:
>>> my_list = [[1,2], [3,7], [6,9], [4,3]]
>>> new_list = [[v*2 if i==0 else v for i,v in enumerate(sublist)] for sublist in my_list]
>>> new_list
[[2, 2], [6, 7], [12, 9], [8, 3]]

A: Are you looking for this?
>>> my_list = [[1,2], [3,7], [6,9], [4,3]]
>>> [[sublist[0] * 2, sublist[1]] for sublist in my_list]
[[2, 2], [6, 7], [12, 9], [8, 3]]

EDIT: The above solution wouldn't scale well if you had sublists of many elements. If this is the case for you, an alternative could be use mapping:
>>> my_list = [[1,2], [3,7], [6,9], [4,3]]
>>> def double_first(list_):
...     list_[0] *= 2
...     return list_
...
>>> map(double_first, my_list)
[[2, 2], [6, 7], [12, 9], [8, 3]]

EDIT2: The solution in my first edit allows to implement any type of manipulation on the sublists, but if the operation is basic and only dependent from the index of the sublist, Dan's solution will perform faster.
HTH!

A: you mean something like this:
my_list = [[1,2], [3,7], [6,9], [4,3]]

new_list = [sublist[0]*2 for sublist in my_list]

Output:
    new_list == [2, 6, 12, 8]

also, you forgot to put commas between your sublists (Fixed in my answer)
I am assuming that by 'index 1' you mean the first element.
If you actually mean the second item (which is index 1) you will use sublist[1] instead of sublist[0].


text:
Q: Passing array[index] to function function setclass(element, classname) {
    console.log("event");
    console.log(element);
    element.classList.add(classname);
    console.log(element.outerHTML);
}

var tpa = document.querySelectorAll("#topnav a");

for(var i=0; i<tpa.length; i++) {
    tpa[i].onclick = () => setclass(tpa[i], "current");
}

I don't understand why the element ins't passed to setclass via setclass(tpa[i],...). console.log(element) logs "undefined" and everything that follows fails because element is undefined.
On the other hand, this works as expected:
var tpa = document.querySelectorAll("#topnav a");
tpa[0].onclick= () => setclass(tpa[0], "current");

A: for(var i=0; i<tpa.length; i++) {
  (i=> tpa[i].onclick = () => setclass(tpa[i], "current"))(i);
}

The onclick will happen after your loop has iterated.Therefore tpa[i] will point to the last element. You might bind i trough an IIFE like in the code above, or you use the context:
for(var i=0; i<tpa.length; i++) {
tpa[i].onclick = function(){ setclass(this, "current")};
}

A: Bind creates a new function that will have this set to the first parameter passed to bind().

function setclass(element, classname, event) {
    console.log(event);
    console.log(element);
    element.classList.add(classname);
    console.log(element.outerHTML);
}
var tpa = document.querySelectorAll("#topnav a");
var i,
    len = tpa.length;
for(i=0; i<len; i+=1) {
  tpa[i].onclick = setclass.bind(this, tpa[i], "current");
}

  sfdg
  sfdg
  sfdg
  sfdg
  sfdg
  sfdg


text:
Q: Java singleton VO class implementing serializable, having default values using getter methods I have a J2SE application having user threads running in a separate JVM outside JBOSS server.
During startup, J2SE invokes a EJB inside jboss, by passing a new object(singleton) of simple JAVA VO class having getter/setter methods. {The VO class is a singleton and implements serialiable(as mandated by EJB)}.
EJB receives the object, reads all db configuration and uses the setter methods of new object to set all the values. It then returns back this updated object back to J2SE in the same remote call.
After J2SE receives the object(singleton/serializable), if i invoke getter methods, I could see only default values set during object creation before EJB call, and not the values set by the EJB.
Kindly throw some light on, why the received object from EJB does not see any updated values and how to rectify this.
I believe it got to do with object initialization during deserialization. And i tried overriding readResolve() in the VO class, but of no help.
With Regards,
Krishna

A: Below are some of the code snippets:

*

*Singleton VO class

public class TekelecConfigurationInfo implements Serializable{
    /**
     *
     */
    private static final long serialVersionUID = -7518766779917305604L;
/**
 *
 */

private static TekelecConfigurationInfo mObjectReference = null;

String mActiveStandby;
String mActiveIPAddress;
String mStandByIPAddress;
int mActiveLNPDBPort;
int mStandByLNPDBPort;
int mDBPort;
int mActiveSocketTimeOut;
int mStandBySocketTimeOut;
int mThreadCount;
int mRetryCount;
int mRetryInterval;

int mPublisher_Daemon_interval;
int mProvisioning_Daemon_interval;
String mCountryCode;

String serverType;

String DataPerTxn;
int maxRetryCount;
String commandMode;
String dataDir;
String fileName;

String errorCodes;

int tekelecCmdTimeOutVal;

public int getTekelecCmdTimeOutVal() {
    return tekelecCmdTimeOutVal;
}

public void setTekelecCmdTimeOutVal(int tekelecCmdTimeOutVal) {
    this.tekelecCmdTimeOutVal = tekelecCmdTimeOutVal;
}

public String getErrorCodes() {
    return errorCodes;
}

public void setErrorCodes(String errorCodes) {
    this.errorCodes = errorCodes;
}

public String getDataDir() {
    return dataDir;
}

public void setDataDir(String dataDir) {
    this.dataDir = dataDir;
}

private TekelecConfigurationInfo()
{

}

public static TekelecConfigurationInfo getObjectReference()
{
    if(mObjectReference == null)
    {
        mObjectReference = new TekelecConfigurationInfo();
    }
    return mObjectReference;
}

/**
 * @return Returns the mActiveStandby.
 */
public String getActiveStandby() {
    return mActiveStandby;
}
/**
 * @param activeStandby The mActiveStandby to set.
 */
public void setActiveStandby(String activeStandby) {
    mActiveStandby = activeStandby;
}

//and so on...
.....
..

*Singleton initialized during J2SE startup:

mConfigurationInfo = TekelecConfigurationInfo.getObjectReference();

//Call to EJB from J2SE:
public TekelecConfigurationInfo getNPConfigurationDetails( long sigConfigId,long tekelecConfigId, TekelecConfigurationInfo mConfigurationInfo )throws TekelecException
    {
        Context ic;
        try {
            ic = getInitialContext();
            Object obj = ic.lookup(JNDI_NAME);
            ReadNPConfigurationTableEJBRemote ds = (ReadNPConfigurationTableEJBRemote) obj;
            mConfigurationInfo = ds.getNPConfigurationDetails(sigConfigId, tekelecConfigId, mConfigurationInfo);

*When doing mConfigurationInfo.getter (methods) on the received obj from server, it does not show the values set by EJB, but shows the default value set during object creation.


text:
Q: Redux returns undefined I'm currently doing a MERN App, it's like a TODO list, but quite big
The thing is that I'm using redux thunk, with my actions, I'm sending data to the DB, and the DB returns me data and I save it in my redux, the problem is that, when I ask for the data that is saved in the reducer, it returns me an undefined, if I ask for the state, it returns me an object with the data, but if I asked for the state.all ( that is the array with my data ) it returns me undefined.
Where I create my store
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";

import { Provider } from "react-redux";
import { createStore, compose, applyMiddleware } from "redux";
import thunk from "redux-thunk";

import { reducers } from "./reducers/index";

const store = createStore(reducers, compose(applyMiddleware(thunk)));

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById("root")
);

The actions
import * as api from "../api/rooms";

export const gettingRooms = () => async dispatch => {
  try {
    const { data } = await api.getAllRooms();
console.log(data)
    dispatch({ type: "ROOMS", payload: data });
  } catch (error) {
    console.log(error);
  }
};

export const creatingAll = room => async dispatch => {
  try {
    const { data } = await api.creatingRooms(room);

    dispatch({ type: "CREATING", payload: data });
  } catch (error) {
    console.log(error);
  }
};

My reducer
const rooms = (all = [], action) => {
  switch (action.type) {
    case "ROOMS":
      return action.payload;

    case "CREATING":
      return [...all, action.payload];

    case "DELETE":
      return all.filter(room => action.payload._id !== room._id);

    default:
      return all;
  }
};

export default rooms;

Where i combine my reducers
import { combineReducers } from "redux";

import Rooms from "./rooms";

export const reducers = combineReducers({ Rooms });

Where I ask the DB for the information to save
import React, { useEffect } from "react";
import Navbar from "./components/navbar/Navbar";
import "./App.css";
import Room from "./components/rooms/Room";

// Calling Actions

import { useDispatch } from "react-redux";
import { gettingRooms } from "./actions/rooms";

const Home = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(gettingRooms());
  }, [dispatch]);

  return (
    <>
      <Navbar />
      <Room />
    </>
  );
};

export default Home;

Where it returns me undefined ( the useSelector thing )
import React, { useState } from "react";

import {
  MainBackground,
  Container,
  ShowForm,
  CreateRoom,
  Start,
  Cancel,
  Rooms,
  RoomsButtons,
  RoomsButtonEdit,
  RoomsButtonDelete
} from "./RoomStyled";

import { useDispatch, useSelector } from "react-redux";

import { creatingAll } from "../../actions/rooms";

const Room = () => {
  const [showForm, setShowForm] = useState(false);
  const [showRooms, setShowRooms] = useState(false);
  const [roomData, setRoomData] = useState({ room: "" });

  const dispatch = useDispatch();

  // Asking For The Data

  const fuck = useSelector(state => state.all);

  console.log(fuck);

  // Sending The Data

  const handleSubmit = async e => {
    e.preventDefault();

    dispatch(creatingAll(roomData));

    // Showing The Room And Hiding The Form
    setShowRooms(true);
    setShowForm(false);
  };

  return (
    <MainBackground>
      <Container>
        {/* Showing The Rooms */}
        {showRooms && (
          <>
            {fuck &&
              fuck.map(room => {
                return (
                  <Rooms key={room._id}>

{room.room}

                      <RoomsButtons>

                          {" "}
                          <RoomsButtonEdit />{" "}

                          {" "}
                          <RoomsButtonDelete />

                      </RoomsButtons>

                  </Rooms>
                );
              })}
          </>
        )}
        {/* Creating Rooms */}
        {!showForm ? (
          <ShowForm onClick={() => setShowForm(true)}>Create</ShowForm>
        ) : (
          <CreateRoom onSubmit={handleSubmit}>

Create Your Room

              <input
                name="room"
                required
                type="text"
                value={roomData.room}
                onChange={e =>
                  setRoomData({ ...roomData, room: e.target.value })
                }
                placeholder="Example : What i will do every single day in february"
                maxLength="85"
              />

                <Start type="submit">Start</Start>
                <Cancel onClick={() => setShowForm(false)}>Cancel</Cancel>

          </CreateRoom>
        )}
      </Container>
    </MainBackground>
  );
};

export default Room;

If you notice a way to get me the array instead of the undefined, i will love you :/


text:
Q: For studying languages / to study languages Don't know which sentence to use, to study a language from someone.

*

*I want to find someone for studying languages.

*I want to find someone to study languages.

*I want to find someone to learn languages/for learning languages.

A: These are correct sentences, but they each have different meanings. If you're the one learning the language, then you would say:

I want to find someone for studying languages.

While if you are looking for someone else to study languages (i.e. you're going to make them study languages) you'd say:

I want to find someone to study languages.

You can, for the most part, use "learn" and "study" interchangeably here.
Even though your sentences aren't wrong, it would be better to say:

I want to find someone to help me study languages.

A: All of these are somewhat ambiguous or awkward.  A better phrasing would be:

I want to find someone to teach me languages.

This indicates clearly that the speaker is the one who desires to learn languages.


text:
Q: Probability of meeting your friend on a tournament. There are $2^n$ players in a knock-out chess tournament. They all have identical skill. This means for any two pairings the probability of either winning is $\frac{1}{2}$.
The table is assigned uniformly randomly. You and your friend are both competing. What is the probability you guys meet?
Method one
Draw out a knock-out table in a rooted binary tree sense. Without loss of generality put yourself at the bottom left leaf. We can condition the probability you and your friend meet on the friends initial location.
Notice we have $2^n-1 $ positions they could be in. One of the positions is adjacent to you in which case the probability you meet is $1$. Two of these positions are only one game away from in which case you must both win your games to meet, with probability $\frac{1}{4}$. Four of these positions are two games away from you in which case you meet if you both win two games. $\frac{1}{2^4}$. And so on.
Formally: Probability of meeting = $\sum\limits_{i = 0}^n \frac{2^i}{2^n-1} \cdot (\frac{1}{2^i})^2$ = $\frac{1}{2^n-1}\sum\limits_{i = 0}^n \frac{1}{2^i} = \frac{1}{{2^n}-1} \cdot \frac{\frac{1}{2^{n+1}} -1}{1-\frac{1}{2}} = \frac{1}{2^{n-1}}$
This method is the nuts and bolts. A little bit of fiddle with geometric series but fairly intuitive.
Method two
This method seems much nicer. I thought it was legitimate and it gets the same answer but I found a big hole in it explained at the end.
Let the positions of the contestants be $C_1 , C_2, C_3 , ... , C_{2^n} $. Let $M_{i,j}$ denote the event that contestant $i$ meets contestant $j$ By full symmetry the probability of $M_{i,j}$ is the same for all $i \not= j \in [1,2^n] $.
We have a total of $2^n - 1$ games in the tournament as each game removes a single player.
We have a total of $2^n$ choose $2$ =  $\frac{2^n \cdot (2^n - 1)}{2} = 2^{2n-1} -2^{n-1}$ couplings of $M_{i,j}$.
($\star$) Matches played are like picking $2^n -1$ balls from a bag with $2^{2n-1} -2^{n-1}$  balls in it. So the probability you and your friend meet is $\frac{2^n -1}{2^{2n-1} -2^{n-1}} = \frac{1}{2^{n-1}}$.
Nifty huh, we get the same answer as before but much cleaner. However this method is wrong!
Step $(\star)$ is a violation. We cannot for example pick the balls $M_{1,2} , M_{1,3} , M_{1,4} , ..., M_{1,2^n}$ as contestant $1$ cannot play everyone!
Can someone help me make the second method work? Im sure its not far off. Or is it just a coincidence that it works?

A: In a $2^n =k$ player knockout tournament,  you will have a total of   $k-1$ matches to knock out all but the winner
Since with random pairing and even odds, all pairings are equally likely,
P(you and your friend meet) $= \dfrac{k-1}{\binom{k}2} = \dfrac{2}{k}$

A: Here is another way to get the answer.
In a knockout tournament with $2^n$ players, so that each player plays at most $n$ rounds, you can expect to play
$$2-{1\over2^{n-1}}$$
games. This is easy to see by induction. It's certainly true for $n=1$, because there's just one game. And when you go from $2^n$ to $2^{n+1}$ players, you'll start in a bracket with $2^n$ players, in which you can (inductively) expect to play $2-1/2^{n-1}$ games, with the prospect of playing one additional game (namely the championship final) only if you win that bracket, which happens with probability $1/2^n$, for an expected total of $2-{1\over2^{n-1}}+{1\over2^n}=1-{1\over2^n}$ games.
Now $2-1/2^{n-1}=(2^n-1)/2^{n-1}$, and there are $2^n-1$ other players, so the probability your friend will be among the opponents you can expect to face is $1/2^{n-1}$.


text:
Q: How to get ruby on rails production mount-point included in url_helpers for email? tl;dnr: My page links are fine, but links erb-olated into non-page text (email) lack the production app mount-point.
detail: My RoR app uses slightly different URLs in dev and production: in dev, the top-level entity is the resource model:
http://localhost:3000/ENTITY/1/edit

But in production, the app is mounted one level down, so URLS have an extra term:
https://server.example.com/APP/ENTITY/1/edit

This works fine for most cases: url_helpers like edit_entity_url return the URLs as I've shown them. Frankly, I'm not clear exactly how that works; I suppose Phusion Passenger and Rack work it out?
However, when I send email (such as to confirm a password reset), it's not working: edit_entity_url never adds the APP mount-point. Short of my own conditional logic in ERB, how can I get that "/APP" in there?
Things I've tried:

*

*Setting `Rails.application.routes.default_url_options[:host] to include "/registry" (no effect)

*using <%= link_to 'Reset', edit_entity_url(...) %>   (no help)

Version info:

*

*actionmailer (4.0.2)

*Rails 4.0.2

*ruby 2.1.0p0

*rack (1.5.2)

*passenger (4.0.35)

The Apache "sites-enabled" file that ties things together (and the only place I can find that the "/registry" token is defined):
<VirtualHost *:80>
    ServerName server.example.com
        DocumentRoot /var/www
        <Directory />
                Options FollowSymLinks
                AllowOverride None
        </Directory>
        <Directory /var/www/>
                Options Indexes FollowSymLinks MultiViews
                AllowOverride None
                Order allow,deny
                allow from all
        </Directory>

    Alias /registry /app01/capapp/registry/current/public
    <Location /registry>
        PassengerBaseURI /registry
        PassengerAppRoot /app01/capapp/registry/current
    </Location>
    <Directory /app01/capapp/registry/current/public>
        Allow from all
        Options -MultiViews
    </Directory>

    ScriptAlias /cgi-bin/ /usr/lib/cgi-bin/
    <Directory "/usr/lib/cgi-bin">
        AllowOverride None
        Options +ExecCGI -MultiViews +SymLinksIfOwnerMatch
        Order allow,deny
        Allow from all
    </Directory>

    ErrorLog ${APACHE_LOG_DIR}/error.log

    LogLevel warn

    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /doc/ "/usr/share/doc/"
    <Directory "/usr/share/doc/">
        Options Indexes MultiViews FollowSymLinks
        AllowOverride None
        Order deny,allow
        Deny from all
        Allow from 127.0.0.0/255.0.0.0 ::1/128
    </Directory>

</VirtualHost>

The Rails config/environments/production.rb file.
Registration::Application.configure do
  config.cache_classes = true
  config.eager_load = true
  config.consider_all_requests_local       = false
  config.action_controller.perform_caching = true
  config.serve_static_assets = false
  config.assets.js_compressor = :uglifier
  config.assets.compile = false
  config.assets.digest = true
  config.assets.version = '1.0'
  config.log_level = :debug
  config.i18n.fallbacks = true
  config.active_support.deprecation = :notify
  config.log_formatter = ::Logger::Formatter.new
  Rails.application.routes.default_url_options[:host] = "server.example.com"
end

Registration::Application.config.middleware.use ExceptionNotification::Rack,
:email => {
  :email_prefix => "[Registration]",
  :sender_address => %{"Admin" <XXX@example.com>},
  :exception_recipients => %w{XXX@example.com}
}

View for the email (app/views/user_mailer/password_reset.text.erb):
To reset your password click the URL below.

<%= edit_password_reset_url(@user.password_reset_token) %>

If you did not request your password to be reset please ignore this email
and your password will stay as it is.

Yes, it's odd to base the URL on the reset_token not the user_id, but it's handled in the controller. Structure based on Railscast #274

A: Well, this is a disgusting hack, but I "solved" this by manual intervention. In app/views/user_mailer/password_reset.text.erb, I now say:
To reset your password click the URL below.

<%  url = root_url.chomp('/') %>
<%  url += "/registry" if Rails.env.production? %>
<%= url + edit_password_reset_path(@user.password_reset_token) %>

Still interested if anyone has a better idea!

A: You can pass the :script_name parameter to url_for (or other methods based on url_for) to set the mount point.   I use
url_for( :only_path => false,
:host => some.host,
:script_name => Rails.application.config.relative_url_root
...

and set config.relative_url_root = '/your-mount-point' in the config.
More details about it here:
how-to-get-ruby-on-rails-production-mount-point-included-in-url-helpers-for-email


text:
Q: Can you connect two questions with a comma? I find myself doing this sometimes.  Part of me questions whether it looks totally correct.
Would that be ok, what type of ticket do I need?

Should it be the crazy looking version I found on line:
Would that be ok? what type of ticket do I need?

Should it be two sentences:
Would that be ok? What type of ticket do I need?

Thanks, for you advice.
FYI: The context was getting an approval.  And then I also wanted to know what type of ticket would be needed.  Assuming it was allowed.

A: Only when you make a list of more than 2 items can you use commas, but you must use 'and' to join the final two items.
For example:

What time does it start, where is it, and do I need a ticket?

Just two questions would require you to use 'and' and would not need a comma:

Where is it and what time does it start?

However, your two questions don't seem to fit well together. Maybe more context would make that clearer to me, but we would only normally group questions together in this way as a means of gathering all the information needed to achieve one overall purpose. In my example, all three questions are about attending an event. But your first question of "would that be okay?" could presumably attract the answer "no". So what if 'it' isn't okay? Will you still need to ask about tickets? They just sound like two questions one would not join together, unless I'm missing something. If your second question depends on the answer to the first question being positive, then most people would ask the questions separately - check it is 'okay' first, and then ask about the ticket.


text:
Q: Rails Whenever gem not executing repetitive crontab task with Ubuntu and Docker Compose I'm trying to run a repetitive task using the Whenever gem for my rails app. It is running in a Docker container created using Docker Compose and  hosted on an Ubuntu server.
I can successfully create and update the crontab file using the Whenever gem but it doesn't seem to be executing the task.
The task I want to execute repetitively in the background while the app is running is:
rake searchkick:reindex CLASS=Property

I usually execute this command successfully from the terminal after creating a web run container using 'docker-compose run web bash'. This reindexes my ElasticSearch server using the searchkick gem.
The relevant versions are below:
- ruby 2.7.2p137
- rails (6.0.3.6)
- elasticsearch (6.8.3)
  - elasticsearch-api (= 6.8.3)
  - elasticsearch-transport (= 6.8.3)
- searchkick (4.4.4)
  - activemodel (>= 5)
  - elasticsearch (>= 6)
  - hashie
- whenever (1.0.0)
  - chronic (>= 0.6.3)

Cron is installed using the Dockerfile:
RUN apt-get update -qq && \
    apt-get install -y curl \
    build-essential \
    libpq-dev \
    cron \
    vim \
    nano \
    postgresql \
    postgresql-contrib \
    postgresql-client

The Dockerfile runs a script when the container is created:
COPY entrypoint.sh /usr/bin/
RUN chmod +x /usr/bin/entrypoint.sh
ENTRYPOINT ["entrypoint.sh"]
EXPOSE 3000

The script (entrypoint.sh) creates a crontab file.
#!/bin/bash
set -e

# For development check if the gems as installed, if not, then uninstall them.
if ! [ bundle check ]; then
    bundle install
fi

# Remove a potentially pre-existing server.pid for Rails.
rm -f /myapp/tmp/pids/server.pid

# Yarn - Check Files.
yarn install --check-files

# Create empty crontab file.
crontab -l | { cat; echo ""; } | crontab -

# Update crontab file using whenever command.
bundle exec whenever --set 'environment=production' --update-crontab

# Run the command - runs any arguments passed into this entrypoint file.
exec "$@"

The 'bundle exec whenever --set 'environment=production' --update-crontab' command above updates the crontab file as per the schedule.rb file below:
set :output, "log/cron_log.log"
env :PATH, ENV['PATH']

# Reindex Property records every 3 mins.
every 3.minutes do
    rake "searchkick:reindex CLASS=Property"
end

I've also tried using this:
every 3.minutes do
    command "cd /myapp && rake searchkick:reindex CLASS=Property"
end

When I execute 'docker-compose run web bash' to use the rails terminal, I see this response at the end:
no crontab for root
[write] crontab file updated

To check that it was created correctly, I view the crontab file in the rails app with 'crontab -l' and it shows:
# Begin Whenever generated tasks for: /myapp/config/schedule.rb at: 2021-04-24 13:07:12 +0000
PATH=/usr/local/bundle/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin

0,3,6,9,12,15,18,21,24,27,30,33,36,39,42,45,48,51,54,57 * * * * /bin/bash -l -c 'cd /myapp && RAILS_ENV=production bundle exec rake searchkick:reindex CLASS=Property --silent >> log/cron_log.log 2>&1'

# End Whenever generated tasks for: /myapp/config/schedule.rb at: 2021-04-24 13:07:12 +0000

Update: After using cron service status and cron service start, the logs in myApp/log/cron_log.log show the following:
bundler: failed to load command: rake (/usr/local/bin/rake)
Bundler::GemNotFound: Could not find rake-13.0.3 in any of the sources
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:86:in `block in materialize'
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:80:in `map!'
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:80:in `materialize'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:170:in `specs'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:237:in `specs_for'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:226:in `requested_specs'
  /usr/local/lib/ruby/2.7.0/bundler/runtime.rb:101:in `block in definition_method'
  /usr/local/lib/ruby/2.7.0/bundler/runtime.rb:20:in `setup'
  /usr/local/lib/ruby/2.7.0/bundler.rb:149:in `setup'
  /usr/local/lib/ruby/2.7.0/bundler/setup.rb:20:in `block in <top (required)>'
  /usr/local/lib/ruby/2.7.0/bundler/ui/shell.rb:136:in `with_level'
  /usr/local/lib/ruby/2.7.0/bundler/ui/shell.rb:88:in `silence'
  /usr/local/lib/ruby/2.7.0/bundler/setup.rb:20:in `<top (required)>'
bundler: failed to load command: rake (/usr/local/bin/rake)
Bundler::GemNotFound: Could not find rake-13.0.3 in any of the sources
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:86:in `block in materialize'
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:80:in `map!'
  /usr/local/lib/ruby/2.7.0/bundler/spec_set.rb:80:in `materialize'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:170:in `specs'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:237:in `specs_for'
  /usr/local/lib/ruby/2.7.0/bundler/definition.rb:226:in `requested_specs'
  /usr/local/lib/ruby/2.7.0/bundler/runtime.rb:101:in `block in definition_method'
  /usr/local/lib/ruby/2.7.0/bundler/runtime.rb:20:in `setup'
  /usr/local/lib/ruby/2.7.0/bundler.rb:149:in `setup'
  /usr/local/lib/ruby/2.7.0/bundler/setup.rb:20:in `block in <top (required)>'
  /usr/local/lib/ruby/2.7.0/bundler/ui/shell.rb:136:in `with_level'
  /usr/local/lib/ruby/2.7.0/bundler/ui/shell.rb:88:in `silence'
  /usr/local/lib/ruby/2.7.0/bundler/setup.rb:20:in `<top (required)>'

So it seems to have set up the crontab file and the cronjob is trying to run but it is not finding rake-13.0.3. I'm going to check if this is an issue with the bundler gem version versus what is in the gemfile.
Appreciate any help.

A: *

*you can run cron to start cron service (linux) in your entrypoint.sh
# Update crontab file using whenever command.
cron && bundle exec whenever --set 'environment=production' --update-crontab

*schedule don't know the gems path so the Bundler::GemNotFound error be throw, to solve this, you can avoid missing paths by setting all ENV in schedule.rb
set :output, "log/cron_log.log"
ENV.each { |k, v| env(k, v) }
# ...


text:
Q: Find the index location of an element in a Numpy array If I have:
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))

for item in range(3):
    choice = random.choice(x)

How can I get the index number of the random choice taken from the array?
I tried:
indexNum = np.where(x == choice)
print(indexNum[0])

But it didn't work.
I want the output, for example, to be something like:
chosenIndices = [1 5 8]

A: Another possibility is using np.where and np.intersect1d. Here random choice without repetition.
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))

res=[]
cont = 0

while cont<3:
    choice = random.choice(x)
    ind = np.intersect1d(np.where(choice[0]==x[:,0]),np.where(choice[1]==x[:,1]))[0]
    if ind not in res:
        res.append(ind)
        cont+=1

print (res)

# Output [8, 1, 5]

A: You can achieve this by converting the numpy array to list of tuples and then apply the index function.
This would work:
import random
import numpy as np
chosenIndices = []
x = np.array(([1,4], [2,5], [2,6], [3,4], [3,6], [3,7], [4,3], [4,5], [5,2]))
x = x.T
x = list(zip(x[0],x[1]))
item = 0
while len(chosenIndices)!=3:
    choice = random.choice(x)
    indexNum = x.index(choice)
    if indexNum in chosenIndices: # if index already exist, then it will rerun that particular iteration again.
        item-=1
    else:
        chosenIndices.append(indexNum)
print(chosenIndices) # Thus all different results.

Output:
[1, 3, 2]


text:
Q: Set "Run as Administrator" for shortcut automaticlly In Windows 7, you can set a property of a shortcut to "Run as Administrator", so that the application is invoked with Administrator privileges or the user is asked for an admin account.
I know I can request/force Administrator privileges with a manifest file for my application, but I need to set the privileges for applications that are not mine. As Installer Software I use SetUp Factory 8. It will create a shortcut but doesn't set "Run as Administrator".
So far I set the option with every customer manually after install but that is a lot of work.
How can I set "Run as Administrator" for application shortcuts via a program/script (like editing the shortcut) or in any other way.

A: You know that you can embed a manifest, but it seems like you don't know you can also have an external manifest. You don't need to compile the executable for this. Just name the file whatever.exe.manifest and put it in the same folder as whatever.exe. If that manifest says requireAdministrator, you'll request elevation on every run. Have your installer copy the manifest wherever it copies the exe.


text:
Q: rake assets:precompile error I'm getting an error when running rake assets:precompile on my production server. As far as I can tell, I didn't do anything differently before this happened. Running rake assets:precompile on my development machine doesn't yield any errors. I'm not sure how to debug this. Suggestions? I tried running with the --trace option, but it didn't really give me any more useful information to point me toward a bug in the code.
deploy@example.com:~/www/example.com/app/assets/stylesheets$ rake assets:precompile
(in /home/deploy/www/example.com)
/home/deploy/.rvm/rubies/ruby-1.9.3-p194/bin/ruby /home/deploy/.rvm/gems/ruby-1.9.3-p194@global/bin/rake assets:precompile:all RAILS_ENV=production RAILS_GROUPS=assets
rake aborted!
Invalid CSS after "...4882640c.png"")": expected "{", was ";background-pos..."
  (in /home/deploy/www/example.com/app/assets/stylesheets/application.css)

Tasks: TOP => assets:precompile:primary
(See full trace by running task with --trace)
rake aborted!
Command failed with status (1): [/home/deploy/.rvm/rubies/ruby-1.9.3-p194/b...]

Tasks: TOP => assets:precompile
(See full trace by running task with --trace)

A: You have an error in the application.css file
It says
Invalid CSS after "...4882640c.png"")": expected "{", was ";background-pos..."

So it looks is where you set a background image.
If you need help to find the error. Post the css file

A: What Andreas Lyngstad said is mostly right, except when you run precompile on your assets, everything is being added to the application.css file, so the error isn't necessarily in that file, it's just that you have an error somewhere in any of the css files that are getting included in the application.css file. So you'll need to check for that error in all the css files being included, you could do a text search across all your css files and try to find that one line depending on whatever editor your using.
Anyways, hope this helps.

A: I ended up resolving this. As it turns out, this was a problem with the Twitter bootstrap rails gem I was using. I was using https://github.com/seyhunak/twitter-bootstrap-rails. It turns out this was an error in one of the sheets being imported in the bootstrap_and_overrides.less file. The solution for me was freezing the gem in my Gemfile to version 2.1.7 and dealing with any dependency issues that cropped up afterwards.


text:
Q: Ubuntu server HDMI hot-pluggable on a RPi3b? Hot plugging of HDMI seems to work well on Raspberry Pi OS (see here). I tried to achieve the same with Ubuntu Server 20.04 on my RPi3B+ by adding the same lines to /boot/firmware/usercfg.txt:
hdmi_force_hotplug=1
hdmi_group=1
hdmi_mode=16

... but it doesn't seem to work. Is there a way to achieve hot HDMI switching on Ubuntu Server 20.04 for RPi series?


text:
Q: Are animals in the matrix real or programs? There are animals in the matrix. Does this mean that real animals are hooked up to the machine and give it energy and exist in the matrix? Or every time there is an animal seen in the matrix, it's just a program?
I don't think this question is a duplicate of "why there is no animals in the matrix?". Why are there only programmed animals in the Matrix? Why wouldn't they use animals as a source of energy as they use humans?

A: They are not real according to the Wachowski's

TheTrinityACMXCL: What about the animals in the Matrix? Are they real animals or just computer-generated images?
Wachowski's: Sadly, they are all computer generated images.

And also according to The Art of The Matrix

Phil Osterhoose: A lot of people have asked if the animals in the Matrix are also hooked up in pods. Unfortunately, they are not. They're all computer-generated images."

This is all contained in the answer provided by Richard here
I was going to put some stuff about the cat and Deja Vu but it would be superfluous to an answer that already answers your question.


text:
Q: gridOption is not receiving my data from controller I am new to angularjs and I am trying to populate a ui grid with data from a data base. I have tried searching for other issue sbut I haven't found anything similar to my issue online.  The table shows just fine but none of my data is populating.  I have seen it in the developer tools in Chrome under Source and it appears to be properly formated as a Json object but I cant get it to display anything in the table.  I know it is probably something small I am doing or not doing any help would be appreciated.
Below is my controller js
var app = angular.module('skill', ["ui.grid",
                                "ui.grid.edit",
                                "ui.grid.selection",
                                "ui.grid.pagination",
                                "ui.grid.exporter",
                                "ui.grid.cellNav"]);
app.controller('SkillEntryController', function ($scope, $http, $interval,   uiGridConstants, SkillService) {
$scope.data = [];
SkillService.GetSkills().then(function (d) {
    $scope.data = d.data;
}, function () {
    alert('Failed');
});
$scope.columns = [
        { name: "SkillName", displayName: "Skill Code", minWidth: 150, width: "33%"  },
        { name: "Category", minWidth: 150, width: "33%"  },
        { name: "Description", minWidth: 150, width: "33%" }
];
$scope.gridOptions = {
    enableSorting: true,
    enableRowSelection: true,
    enableCellEditOnFocus: true,
    exporterHeaderFilterUseName: true,
    treeRowHeaderAlwaysVisible: false,
    paginationPageSizes: [25, 50, 75],
    paginationPageSize: 25,
    columnDefs: $scope.columns,
    data: $scope.data,
    onRegisterApi: function (gridApi) {
        $scope.gridApi = gridApi;
    }
};
}).factory('SkillService', function ($http) {
var fac = {}
fac.GetSkills = function () {
    return $http.get('/Skills/GetSkills');
}
return fac;
});

Here is my factory method:
public JsonResult GetSkills()
    {
        List<Skill> c = new List<Skill>();
        return new JsonResult { Data = c.Select(x => new { x.Category, x.Description, x.SkillCodeID, x.SkillName }), JsonRequestBehavior = JsonRequestBehavior.AllowGet };
    }

And here is my cshtml file:
@model IEnumerable<SkillResourceCenterApp.Models.Skill>
@using Newtonsoft.Json;
@{
    ViewData["Title"] = "Add Skill";
}
@section scripts{
    <link href="~/Content/ui-grid.css" rel="stylesheet" />

}

@ViewData["Title"]

    @Html.ActionLink("Create New", "Create")

        <button type="button" ng-click="addNewRow()" class="btn btn-default col-sm-3 col-md-2">
             Add Row
        </button>
        <button type="button" ng-click="deleteSelected()" class="btn btn-default col-sm-3 col-md-2">
             Delete Selected
        </button>
        <button type="button" ng-click="exportToCSV()" class="btn btn-default col-sm-3 col-md-2">
             Export to Excel
        </button>
        <button type="button" ng-click="save()" class="btn btn-primary col-md-offset-4 pull-right col-sm-2">
            Save
        </button>

                    No Results

A: You're missing the field definition in columnDefs.  Have a look at https://github.com/angular-ui/ui-grid/wiki/Defining-columns
var columnDefs: [{
    field: 'foo',
    displayName: 'my foo',
    visible: true,
    maxWidth: 90,
    enableColumnResizing: false,
    cellTemplate: "
{{row.entity.foo}}
"
}];


text:
Q: Proving $(\lambda^{-1}-A^{-1})^{-1}=\lambda-\lambda^2(\lambda-A)^{-1}$ Let $X$ be a Banach space over $\mathbb{K}=\mathbb{R}$ or $\mathbb{C}$, let $A\subset X\oplus X$ be a linear relation and let $\lambda\in\mathbb{K}\setminus\{0\}$
I want to prove that $(\lambda^{-1}-A^{-1})^{-1}=\lambda-\lambda^2(\lambda-A)^{-1}$.
Note that $A=\lambda-R(\lambda,A)^{-1}=\lambda-(\lambda -A)$; hence
$\lambda-\lambda^2(\lambda-A)^{-1}=\lambda-\lambda^2(\lambda-\lambda+(\lambda-A))=\lambda-\lambda^2(\lambda-A)$
which would imply that $(\lambda-A)^{-1}=(\lambda -A)$, but that can't be correct. I would appreciate some hints on solving this problem

A: It works in the reals without commuting multiplication, so it should work here.
$$\begin {align}\lambda-\lambda^2(\lambda-A)^{-1} &=[(\lambda^2-\lambda A)-\lambda)^2](\lambda-A)^{-1}\\
&=-\lambda A(\lambda - A)^{-1}\\
&=-(A^{-1}-\lambda^{-1})^{-1}\\
&=(\lambda^{-1}-A^{-1})^{-1}\end {align}$$

A: Factor out $\lambda^{-1}A^{-1}$ and follow your nose:
\begin{align}
   (\lambda^{-1}-A^{-1})^{-1} &= \{ \lambda^{-1}A^{-1}(A-\lambda))^{-1} \\
    &= (A-\lambda)^{-1}\lambda A \\
    &= (A-\lambda)^{-1}(\lambda (A-\lambda)+\lambda) \\
    &= \lambda-\lambda^2(A-\lambda)^{-1}.
\end{align}


text:
Q: PHP count() always return 1 I have a JSON object that im trying to iterate to count how many value there are inside the object.
My JSON;
[{
    "accountId": "1746756959",
    "containerId": "7454209",
    "containerVersionId": "7",
    "container": {
        "accountId": "1746756959",
        "containerId": "7454209"
    },
    "tag": [{
        "accountId": "1746756959",
        "name": "Universal Analytics",
        "parameter": [{
            "key": "overrideGaSettings",
            "type": "boolean",
            "value": "false"
        }]
    }, {
        "accountId": "1746756959",
        "parameter": [{
            "key": "detectTitle",
            "type": "boolean",
            "value": "true"
        }]
    }, {
        "accountId": "1746756959",
        "name": "contentEngagement",
        "parameter": [{
            "key": "html",
            "type": "template",
            "value": "


text:
Q: open new window to print element try to open a new window to include the element for print only. but it did not work in IE8.
function printElement(elementId) {
  var printWindow = window.open('', '_blank',
    'status=0,toolbar=0,location=0,menubar=1,resizable=1,scrollbars=1');

  printWindow.document.write("");

  var head = jQuery('head').clone();
  var printElement = jQuery('#' + elementId).clone();

  jQuery(printWindow.document).find('head').replaceWith(head);  // does not work in IE8
  var body = jQuery(printWindow.document).find('body');
  body.empty();
  body.append(printElement);  // does not work in IE8
  return false;
}

Thanks for help.

A: How about this? If I understand what you're wanting to do correctly, this should work for you. Tested in IE 8.
Working example on JSBin.
HTML:
Print One
Print Two

JavaScript:
var $trigger = $(".trigger"),
    printElement = function(id) {
        var printWindow = window.open('','_blank','status=0,toolbar=0,location=0,menubar=1,resizable=1,scrollbars=1'),
            html = $('html').clone(),
            printElement = $('#' + id).clone(),
            body;

      printWindow.document.write("<!DOCTYPE html>");

      $(printWindow.document).find('html')
                            .replaceWith(html);

      body = $(printWindow.document).find('body')
                                    .html(printElement);
    };

$trigger.on("click", function(e) {
  var id = $(this).attr("id");

  e.preventDefault();

  printElement(id);
});


text:
Q: Stuck vim adventure level 6 Kansas I am unable to find a way to delete the "to" from into word in the last step of level 6. The phrase that said "I think we aren't in kansas...".
Someone can help me?

A: At the end I solved the puzzle, it took me some time.
Solved : de --> delete the character to the end of word.
I used dw, withouth success


text:
Q: Grails Restful Controller UPDATE-Method does not take updated Data from PUT I set up a Restful Controller in my Grails 2.3.5 app. When sending an object via PUT to my endpoint the object won't get updated. My println does not show the updated data, but the original. I don't understand why.
Restful controller:
import grails.rest.RestfulController

class PluginSettingController extends RestfulController {
    static responseFormats = ['json', 'xml']

    PluginSettingController() {
        super(PluginSetting)
    }

    @Override
    def update(PluginSetting setting){
        println(setting.name)
        // This prints out the old name: "Old name"
    }

Domain class:
class PluginSetting {
    String name
    String value

    static constraints = {
        name(nullable:false, blank:false, unique: true)
        value(nullable:false, blank:false)
    }
}

curl request:
curl -i -X PUT -d "{'name':'NEW','value':'my value', 'id':1}" http://localhost:8080/app/pluginSettings/1

old object (this is what i get when sending a GET to the URL 'http://localhost:8080/app/pluginSettings/1')
{
    "class": "configuration.PluginSetting",
    "id": 1,
    "name": "Old name",
    "value": "my value"
}

A: This finally worked for me with Grails 2.5.4 - it was suprise that the normal methods did not work when using a second controller.
@Transactional(readOnly=false)  // not needed
class EngineController extends RestfulController<PluginSettings> {
    static responseFormats = ['json', 'xml']
    EngineController() {
        super(PluginSettings)
    }
}

class UrlMappings {
    static mappings = {
        "/$controller/$action?/$id?(.$format)?"{
            constraints {
               // apply constraints here
           }
        }

        "/"(view:"/index")
        "500"(view:'/error')
    }
}

#Show
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/index
curl -i -X GET -H "Accept: application/json" localhost:8080/app/engine/show/1
#Create
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/save
#Update
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/engine/update/1
#Delete
curl -i -X DELETE http://localhost:8080/app/engine/delete/1

However when I modified the urlMappings to include
"/api/engines"(resources:"Engine")

I had to use
curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/
curl -i -X GET -H "Accept: application/json" localhost:8080/app/api/engines/1
curl -i -X POST -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/
curl -i -X PUT -H "Content-Type: application/json" -d '{"name":"Along Came A Spider"}' localhost:8080/app/api/engines/1
curl -i -X DELETE http://localhost:8080/app/api/engines/1


text:
Q: How various properties of numbers, operations are found? I know that how the term "property" is defined.
Definition:

An attribute, quality, or characteristic of something.

Like one of the property of addition is "commutativity" which behaves like,
$a+b=b+a$
And similarly associativity,
$a+(b+c)$ = $a+(b+c)$
But I always keep apprehending that How were they found and so properties similar to them?, How were they proved true for all numbers?, Does it need some type of induction proof?
When I asked my cousin about that, he said, "They have no need to be proved since they are properties like you possess and so you can make sense of them". But I replied him, "As far as properties of addition, multiplication are concerned, I can make sense of them but what about these types of properties,
Exponential property: $a^n=\frac{1}{a^{-n}}$.
So he suggested me to ask about it on SE and so I'm doing.

A: Most of calculus books begin introducing one way or another the real numbers. And most of these books incroduce them with a set of axioms, which are the properties that you are talking about.
There are not only operation related properties. There are also order properties and a topological property.
But some books begin with the Peano axioms, which give some very basic properties of the natural numbers. With these Peano's axioms at hand, you can define the addition and the product of natural numbers and prove their properties. That is, what were axioms in the former approach, are theorems now. Then you can build the integer numbers, the rational numbers, and finally the real numbers. But all this construction is rather long, and it is usually omitted, favoring the axiomatic approach.
But things can be done even more from scratch. You can start with a somewhat standarized set of axioms called Zermelo-Fränkel (ZF) and construct the set of natural numbers and prove the Peano's "axioms" (which are theorems now). This is also a long work. Just a tip: the number zero is defined to be the empty set, and the successor of a given natural number $n$ is $n\cup\{n\}$. So, yes, natural numbers are sets.
I'm sorry, but I don't have at hand good bibliography about these constructions. Surely somebody can help with this.

A: Your definition of property is more English than mathematical. In mathematics, a property is a formula in logic with a free variable. Any object that can be substituted for the free variable and make the formula 'true' is said to have that property.
For example, the property $E(x)$ meaning $x$ is even could be represented by the formula $\exists n \in \mathbb{N}(2*n = x)$. This formula basically says that there exists a natural number such that two times that number equals $x$. Any even number plugged into this formula for $x$ will make it true, while any other number will not.
Now depending on the context, these properties are simply defined, or require proof.
For example, after constructing the natural numbers and real numbers from within set theory as ajotatxe suggests, in order to demonstrate that the construction is valid, we need to prove that our construction satisfies all the necessary properties.
Or, we could simply state that $R$ is a real closed field. Then we are working under the assumption that every element of $R$ has the properties you describe, and no proof is necessary.

A: A property (also called a "predicate" or "propositional function") is simply something that can be true or false of some objects. In logic, the notation $P(x)$ represents the statement that "object x has property P." We could even have predicates that take multiple arguments, like P(x,y); usually a predicate with more than one argument is called a relation.
Some examples of predicates include:

*

*"$x$ is an even number";

*"$x=0$";

*"$4x-y=73$";

*"the polynomial P has at least 2 real zeroes";

*"$x+y=y+x$".

Of course a statement like P(x) does not have any meaning until we decide on a value for $x$. There are many ways to do this: if we already have an object a, we can set $x=a$ and ask if $P(a)$ is true.
Even if we don't have any specific objects, we can still ask meaningful questions. In this case we can quantify over the range of possible values that our variable can take, whatever those might be. So we can ask whether $P(x)$ holds for all $x$ ("universal quantification"), or we could ask if it is true for some $x$ ("existential quantification").
If we know when a predicate P is true, we can use this fact to deduce other things. For instance, if we have an object a such that P(a) holds, then obviously there is at least one such object - namely a. If we have an object b such that P(b) is false, then we know that not all objects have the property P.
Predicate logic is the logical system that formalizes this reasoning about properties of objects. Statements in predicate logic look like $\forall x \forall y(Sxy \leftrightarrow \forall z(Ezx \to Ezy))$. This is read as, "for all x and y, S(x,y) is true if and only if, for all z, E(z,x) implies E(z,y).
Another example: $\forall x(Px \to \exists y Sxy)$ means "for all x, if P(x), then there is a y such that S(x,y).
Armed with the rules of predicate logic, and some initial assumptions (axioms) that we decide on beforehand, we can proceed to prove statements about the objects we're studying.


text:
Q: Mocking Joda DateTime method using Mockito I want millis to return specified value.
public long myMethod(){
    DateTime nowDateTime = new DateTime(DateTimeZone.UTC);
    long millis = nowDateTime.getMillis();
    System.out.println(millis);
}

I tried this with no luck.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ DateTime.class })
@PowerMockIgnore({ "javax.crypto.*", "javax.management*" })
...
...
public void testMyMethod(){
    DateTime nowDateTime = PowerMockito.mock(DateTime.class);
    Mockito.when(nowDateTime.getMillis()).thenReturn(10L);
}

How can I fix this?

A: Just use the org.joda.time.DateTimeUtils#setCurrentMillisFixed method of JodaTime which was designed to fix new DateTime() to a different time than the current time. To return to the normal time use org.joda.time.DateTimeUtils#setCurrentMillisSystem afterwards. No mocking needed.

@Test
public void test() {
DateTimeUtils.setCurrentMillisFixed(10L);
// .. your code
}

@After
public void cleanup() {
// Make sure to cleanup afterwards
DateTimeUtils.setCurrentMillisSystem()
}


text:
Q: Take an xml feed from the internet and put it in my assets Currently i am developping an android application and i'm using an xml feed that i take from the internet.the problem is when my phone doesn't have an internet connection, my application crashs. I would like to obtain my xml file and put it in the assets.
My question is : is it possible ? And if yes, what's the best solution to do it ?

A: Writing an xml file or any file in assets folder at runtime is impossible. Folders or resources in res folder are "read only" but, you can write an XML file on your application's internal data folder.
Just use the Context.openFileInput(String) and Context.openFileOutput(String, int). Here
Update 1:
This question might come on your mind.
"If I write an XML file on my app's data folder, how to parse it?"
You can use XMLPullParser class to parse an XML File. Here's an example
XMLPullParser parser = Xml.newPullParser();
parser.setInput(new InputStreamReader(openFileInput("my_XML_file.xml")));

A: *

*Check for Network connection:
    public static boolean isConnectedToInternet(Context context) {
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity != null)
    {
        NetworkInfo[] info = connectivity.getAllNetworkInfo();
        if (info != null)
            for (int i = 0; i < info.length; i++)
                if (info[i].getState() == NetworkInfo.State.CONNECTED)
                {
                    return true;
                }
    }
    return false;
}

*Download XML String
  public String getXMLString(String url) {

    try
    {
        URL url1 = new URL(url);
        URLConnection tc = url1.openConnection();
        tc.setConnectTimeout(timeout);
        tc.setReadTimeout(timeout);
        BufferedReader br = new BufferedReader((new InputStreamReader(tc.getInputStream())));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null)
        {
            sb.append(line + "\n");
        }
        br.close();
        return sb.toString();
    } catch (Exception e)
    {
        Log.d("Error", "In XMLdownloading");
    }

    return null;
}

*Save String to any directory in SD Card:
   private void writeStringToTextFile(String s, String f) {

    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath());
    dir.mkdirs();

    File file = new File(dir, f);
    try
    {
        FileOutputStream f1 = new FileOutputStream(file, false);
        PrintStream p = new PrintStream(f1);
        p.print(s);
        p.close();
        f1.close();
    } catch (FileNotFoundException e)
    {
    } catch (IOException e)
    {
    }
    }
    }

A: Add this method to your activity:
private boolean isNetworkAvailable() {
    ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager
            .getActiveNetworkInfo();
    return activeNetworkInfo != null;
}

and in onCreate or before you load your feed check like this:
        if (!isNetworkAvailable()) {
            Toast.makeText(
                    Player.this,
                    "No active internet connection found.",
                    Toast.LENGTH_LONG).show();
            finish();
            return;
        }


text:
Q: ado.recordset "losing" fields I'm working on an old classic asp project. The database is structured terribly, each row is well in excess of limits (18 different nvarchar(2000), numerous nvarchar(256), and more...)
I made a small fix which changes the order in which the fields are retrieved from the recordset.
What I am now seeing  has me mystified. Fields that do initially exist disappear as I use other fields.
For Example, I have:
if(RS.Fields('field1').value){
   //do something
}
if((RS.Fields('field2').value){
   //do something
}

In some of my results, field2 is not showing up when checked (after field1), but if I check immediately before field1, it does exist.
Is this a known behavior? Is there a work around?

A: It seems that the problem was two fold:
One, the order the fields appear in code needed to match up with the order they were in the DB. Yeah, don't know, but it works.
Two, the fields need to be immediately loaded into variables.
if(RS.Fields('f1')){
   doWork(RS.Fields('f1'));
}

does not work, but
var f1 = RS.Fields('f1');

if(f1){
   doWork(f1)
}

does.


text:
Q: Ionic 4 start tabs project Lifecycle hooks broken Step1:
ionic start stacktabs tabs --type=angular
ionic cordova platform add android
ionic cordova run android --prod

Everything works.
Step 2: Check current routings:
//START: app-routing.module.ts:
   path: '',
   loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)

//END: app-routing.module.ts:
// START: tabs-routing.module.ts:
            const routes: Routes = [
            {
            path: 'tabs',
                component: TabsPage,
                children: [
                 {
                    path: 'tab1',
                    children: [
                  {
                    path: '',
                    loadChildren: () =>
                      import('../tab1/tab1.module').then(m => m.Tab1PageModule)
                  }
                ]
              },
              {
                path: 'tab2',
                children: [
                  {
                    path: '',
                    loadChildren: () =>
                      import('../tab2/tab2.module').then(m => m.Tab2PageModule)
                  }
                ]
              },
              {
                path: 'tab3',
                children: [
                  {
                    path: '',
                    loadChildren: () =>
                      import('../tab3/tab3.module').then(m => m.Tab3PageModule)
                  }
                ]
              },
              {
                path: '',
                redirectTo: '/tabs/tab1',
                pathMatch: 'full'
              }
            ]
          },
          {
            path: '',
            redirectTo: '/tabs/tab1',
            pathMatch: 'full'
          }
        ];

// END: tabs-routing.module.ts:
Step: 3 Add console.log for constructor, ionViewWillEnter, ionViewDidEnter inside
tabs.page.ts
tab1.page.ts
tab2.page.ts

Re-run and everythings works as expected with the following console.log info:

            Inside tabs.page.ts constructor()....
            Inside tab1.page.ts constructor()....
            Inside tab1.page.ts ionViewWillEnter()....
            Inside tab1.page.ts ionViewDidEnter()....
            Inside tabs.page.ts ionViewWillEnter()....
            Inside tabs.page.ts ionViewDidEnter()....

Press tab2:
            Inside tab2.page.ts constructor()....
            Inside tab2.page.ts ionViewWillEnter()....
            Inside tab2.page.ts ionViewDidEnter()....

Press tab1:

    Inside tab1.page.ts ionViewWillEnter()....
    Inside tab1.page.ts ionViewDidEnter()....

Add a new page: initPage
ionic g page initPage

Check app-routing.module.ts
    const routes: Routes = [
      {
        path: '',
        loadChildren: () => import('./tabs/tabs.module').then(m => m.TabsPageModule)
      },
      {
        path: 'init-page',
        loadChildren: () => import('./init-page/init-page.module').then( m => m.InitPagePageModule)
      }
    ];

Step 4:
Add ion-button in tab1.page.html which will route to initPage:
<ion-button expand="full" (click)="gotoInitPage()">Go to InitPage</ion-button>

gotoInitPage()
{
this.navController.navigateForward('/init-page');
}

initPage shown up with no issues.
Step 5:
Add ion-button in init-page.page.html which will route back to tabs page:
<ion-button expand="full" (click)="backToTabsPage()">Back to TabsPage</ion-button>

backToTabsPage()
{
this.navController.navigateForward('/tabs/tab1');
}

Note: The bottom tabs button and tab1 page shown up for the view but from the chrome debugger:
tab1 modules never fired up at all, ie Only the tabs.page.ts got executed:
Only show tabs page log
Inside tabs.page.ts ionViewWillEnter()....
Inside tabs.page.ts ionViewDidEnter()....

Tested again by adding a back button inside initPage:
The result is the same, tab1 page module not fired up.
<ion-header>
    <ion-toolbar color="primary">
        <ion-buttons slot="start">
           <ion-back-button defaultHref="/tabs/tab1"></ion-back-button>
        </ion-buttons>
        <ion-title>InitPage</ion-title>
    </ion-toolbar>
</ion-header>

I tried with different method on routing inside initPage with no luck:
this.navController.navigateRoot('/tabs/tab1');
this.router.navigateByUrl('/tabs/tab1');

Envirnoment:
        Ionic CLI                     : 5.4.16
        Ionic Framework               : @ionic/angular 5.0.4
        @angular-devkit/build-angular : 0.803.25
        @angular-devkit/schematics    : 8.3.25
        @angular/cli                  : 8.3.25
        @ionic/angular-toolkit        : 2.2.0

        Cordova:
        Cordova CLI       : 9.0.0 (cordova-lib@9.0.1)
        Cordova Platforms : android 8.1.0
        Cordova Plugins   : cordova-plugin-ionic-keyboard 2.2.0, cordova-plugin-ionic-webview 4.1.3, (and 4 other plugins)

        Utility:
        cordova-res : 0.8.1
        native-run  : 0.3.0

        System:
        Android SDK Tools : 26.1.1 (C:\Users\louie\AppData\Local\Android\Sdk)
        NodeJS            : v12.14.0 (D:\Program Files\nodejs\node.exe)
        npm               : 6.13.4
        OS                : Windows 10

Please help...thanks in advance

A: Just for someone having the same problem. It turns out that you need to use
this.navController.navigateRoot('/some-route') inside the tab1 page. And
inside the initPage you need to issue the same, ie this.navController.navigateRoot('/tabs/tab1');
Credit to this URL: https://www.joshmorony.com/using-angular-routing-with-ionic-4/

A: You can use canDeactivate guard for parent route.
Full demo

const routes: Routes = [
  {
    path: '',
    component: TabsComponent,
    canDeactivate: [IonRouterOutletHooks],
   }
 }

import { Injectable, Injector } from '@angular/core';
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot,
  UrlTree,
  CanDeactivate,
  ActivatedRoute
} from '@angular/router';
import { Observable } from 'rxjs';
import { IonRouterOutlet } from '@ionic/angular';
import { LIFECYCLE_WILL_LEAVE, LIFECYCLE_DID_LEAVE } from '@ionic/core';

export interface INestedPageDeactivate {
  ionRouterOutlet: IonRouterOutlet;
  // activatedRoute: ActivatedRoute;
}

@Injectable()
export class IonRouterOutletHooks implements CanActivate, CanDeactivate<any> {
  constructor(public injector: Injector) {}

  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean|UrlTree>|Promise<boolean|UrlTree>|boolean|UrlTree {
    // console.log(this);
    // console.log(route);
    // console.log(state);
    return true;
  }
  canDeactivate(
    component: INestedPageDeactivate,
    currentRoute: ActivatedRouteSnapshot,
    currentState: RouterStateSnapshot,
    nextState: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    // console.log(component);
    // console.log(currentRoute);
    // console.log(currentState);
    // console.log(nextState);
    if (!component.ionRouterOutlet) {
      alert('IonRouterOutletHooks->component->ionRouterOutlet');
      return false;
    }
    const stackCtrl = (component.ionRouterOutlet as any).stackCtrl;
    stackCtrl.views.reverse().forEach((view) => {
      if (!view.ref.hostView.destroyed){
        view.element.dispatchEvent(new CustomEvent(LIFECYCLE_WILL_LEAVE, {
          bubbles: false,
          cancelable: false,
        }));
        view.element.dispatchEvent(new CustomEvent(LIFECYCLE_DID_LEAVE, {
          bubbles: false,
          cancelable: false,
        }));
      }
    });
    return true;
  }
}


text:
Q: Forcing an enter on a program fired off in Python by os.system I'm using the dirty way of executing a program from python. That program requires an enter from the user before it finishes. How can I force an enter. The issue of course is that I cannot issue any further command until the first command has fully executed so this won't work:
os.system(command)
os.linesep('\r\n')

On of the reasons I went back to using os.system(command) is that I couldn't get command line parameters in in the correct format. One issue is the requirement for command setting="xyz.txt" with the double inverted commas appearing correctly, I've not found a smart way to do this as yet.
Is there a way around this? I'm doing this on Windows 7. I'm concerned that I'll need to examine the output and break when I can see the program has ended. Is there anyway to detected that program is taking keyboard input and use this fact?

A: Check out the subprocess module, in particular subprocess.Popen(). Once your subprocess is running, you can communicate with it, along with other useful functions.

A: If you want the script at some point to simulate a user's key stroke, then you can follow the solution here:
Simulating a key press event in Python 2.7
You will need to download and install pywin32.

A: This is the answer in reality based on subprocess and works on Windows 7.
p = Popen([batch_file], stdout=PIPE, stdin=PIPE, bufsize=1, shell=True)
while p.poll() is None:
    line = p.stdout.readline()
    if line.startswith('End'):
        p.communicate('\r\n')


text:
Q: Observable that buffers items when no subscribers, then emits them and clears the buffer when it is subscribed to? I want an observable that:

*

*Can emit items on demand and never really completes (a hot observable?)

*Is aware of when it has subscribers or not

*If no subscribers, it will buffer items that I tell it to emit

*When subscribed, it will emit the buffered items in order, then clear the buffer, and then continue to allow me to emit more items

*When unsubscribed (subscriber is disposed?), it will go back to buffering.

Also:

*

*There is only expected to be one subscriber at a time

*It does not need to be thread safe
Here's sort of a pseudocode of what I am thinking -- I don't have the necessary callbacks though to do this the right way.  Also it would be nice if I could wrap it all up in an Observable or Subject.
class RxEventSender {
    private val publishSubject = PublishSubject.create<Action>()

    val observable: Observable<Action> = publishSubject

    private val bufferedActions = arrayListOf<Action>()

    private var hasSubscribers = false

    fun send(action: Action) {
        if (hasSubscribers) {
            publishSubject.onNext(action)
        } else {
            bufferedActions.add(action)
        }
    }

    //Subject was subscribed to -- not a real callback
    fun onSubscribed() {
        hasSubscribers = true
        bufferedActions.forEach {action ->
            publishSubject.onNext(action)
        }
        bufferedActions.clear()
    }

    //Subject was unsubscribed -- not a real callback
    fun onUnsubscribed() {
        hasSubscribers = false
    }
}

A: Use a ReplaySubject. It has unbounded and bounded versions if you get worried about the buffer getting too big.

A: After spending some time, I think this works well enough for my needs.  It's not wrapped up nicely in a Subject or Observable but all I needed was to emit items and subscribe.
class RxEventSender<T> {
    private val bufferedEvents = arrayListOf<T>()

    private val publishSubject = PublishSubject.create<T>()

    val observable: Observable<T> = publishSubject
            .mergeWith(Observable.fromIterable(bufferedEvents))
            .doOnDispose {
                bufferedEvents.clear()
            }

    fun send(event: T) {
        if (publishSubject.hasObservers()) {
            publishSubject.onNext(event)
        } else {
            bufferedEvents.add(event)
        }
    }
}


text:
Q: Is there a BigQuery function to extract a nested JSON? [
  {
    "SnapshotDate": 20220224,
    "EquityUSD": 5530.22,
    "BalanceUSD": 25506.95,
    "jsonTransactions": "[{\"TransactionDate\":20220224,\"AccountTransactionID\":144155779,\"TransactionType\":\"Deposit\",\"AmountUSD\":2000},{\"TransactionDate\":20220224,\"AccountTransactionID\":144155791,\"TransactionType\":\"Deposit\",\"AmountUSD\":2000}]"
  }
]

Can somenone help me to extract this json string on bigquery. I can seem to get JSON_EXTRACT to work as it does not have a root element

A: The double quotes in jsonTransactions are making the JSON invalid. JSON_EXTRACT_SCALAR(json_data, "$[0].jsonTransactions") returns [{ because the first pair of double quotes enclose [{. To circumvent this, I used regex to remove the double quotes of the jsonTransactions value. Now, the inner JSON string is considered an array.
After regex replacement, the outermost quotes have been removed as shown below. I replaced "[ and ]" with [ and ] respectively in the JSON string.
"jsonTransactions": [{"TransactionDate":20220224,"AccountTransactionID":144155779,"TransactionType":"Deposit","AmountUSD":2000},{"TransactionDate":20220224,"AccountTransactionID":144155791,"TransactionType":"Deposit","AmountUSD":2000}]

Consider the below query for your requirement. The JSON path for AmountUSD will be "$[0].jsonTransactions[0].AmountUSD".
WITH
  sample_table AS (
  SELECT
    '[{"SnapshotDate": 20220224,"EquityUSD": 5530.22,"BalanceUSD": 25506.95,"jsonTransactions": "[{\"TransactionDate\":20220224,\"AccountTransactionID\":144155779,\"TransactionType\":\"Deposit\",\"AmountUSD\":2000},{\"TransactionDate\":20220224,\"AccountTransactionID\":144155791,\"TransactionType\":\"Deposit\",\"AmountUSD\":2000}]"}]'
  AS json_data) as json_extracted
SELECT
  JSON_EXTRACT(REGEXP_REPLACE(REGEXP_REPLACE(json_data, r'"\[', '['), r'\]"', ']'),
    '$[0].jsonTransactions')
FROM
  sample_table;

Output:

As you had mentioned in the comments section, it is better to store the JSON itself in a more accessible format (one valid JSON object) instead of nesting JSON strings.

A: You might have to build a temp table to do this.
This first create statement would take a denormalized table convert it to a table with an array of structs.
The second create statement would take that temp table and embed the array into a (array of) struct(s).
You could remove the internal struct from the first query, and array wrapper the second query to build a strict struct of arrays. But this should be flexibe enough that you can create an array of structs, a struct of arrays or any combination of the two as many times as you want up to the 15 levels deep that BigQuery allows you to max out at.
The final outcome of this could would be a table with one column (column1) of a standard datatype, as well as an array of structs called OutsideArrayOfStructs. That Struct has two columns of "standard" datatypes, as well as an array of structs called InsideArrayOfStructs.
 CREATE OR REPLACE TABLE dataset.tempTable as (
     select
         column1,
         column2,
         column3,
         ARRAY_AGG(
                 STRUCT(
                     ArrayObjectColumn1,
                     ArrayObjectColumn2,
                     ArrayObjectColumn3
                 )
             ) as InsideArrayOfStructs
     FROM
         sourceDataset.sourceTable
     GROUP BY
         column1,
         column2,
         column3 )

 CREATE OR REPLACE TABLE dataset.finalTable as (
     select
         column1,
         ARRAY_AGG(
                 STRUCT(
                     column2,
                     column3,
                     InsideArrayOfStructs
                 )
        ) as OutsideArrayOfStructs
     FROM
         dataset.tempTable
     GROUP BY
         Column1 )