text:
Q: Arduino - Android data transfer throughout HC-06 socket problem Evening fellow programmers,
am relatively new to android studio, and it's my first time dealing with bluetooth, receivers, broadcasts and such stuff.. I followed some tutorials and created my monitoring app, the app is supposed to read data sent by HC-06 module from arduino, yet I had a pump with the connect thread, it keeps catching the socket.close() instead of trying the socket.connect() and I have no idea why is that happening..
here is the code for my ConnectThread.run():
public ConnectThread(BluetoothDevice device, UUID uuid) {
        Log.d(TAG, "ConnectThread: started.");
        mmDevice = device;
        deviceUUID = uuid;
    }

    public void run(){
        BluetoothSocket tmp = null;
        Log.i(TAG, "RUN mConnectThread ");

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice
        try {
            Log.d(TAG, "ConnectThread: Trying to create InsecureRfcommSocket
using UUID: "
                    +MY_UUID_INSECURE );
            tmp = mmDevice.createRfcommSocketToServiceRecord(deviceUUID);
        } catch (IOException e) {
            Log.e(TAG, "ConnectThread: Could not create InsecureRfcommSocket
" + e.getMessage());
        }

        mmSocket = tmp;

        // Always cancel discovery because it will slow down a connection
        mBluetoothAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket

        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();

            Log.d(TAG, "run: ConnectThread connected.");
        } catch (IOException e) {
            // Close the socket
            try {
                mmSocket.close();
                Log.d(TAG, "run: Closed Socket.");
            } catch (IOException e1) {
                Log.e(TAG, "mConnectThread: run: Unable to close connection
in socket " + e1.getMessage());
            }
            Log.d(TAG, "run: ConnectThread: Could not connect to UUID: " +
MY_UUID_INSECURE );
        }

        connected(mmSocket,mmDevice);
    }

And the thrown exception:
D/BluetoothSocket: close() this: android.bluetooth.BluetoothSocket@3390c6f, mSocketState: INIT
D/BluetoothConnectionServ: run: Closed Socket.
run: ConnectThread: Could not connect to UUID: 00001101-0000-1000-8000-00805f9b34fb
connected: Starting.

However, connectedThread continues to work even when the socket is closed, idk if that's how it works, but here is the ConnectedThread.run():
public void run(){
        byte[] buffer = new byte[1024];  // buffer store for the stream

        int bytes; // bytes returned from read()

        // Keep listening to the InputStream until an exception occurs
        while (true) {
            // Read from the InputStream
            try {
                bytes = mmInStream.read(buffer);
                String incomingMessage = new String(buffer, 0, bytes);
                Log.d(TAG, "InputStream: " + incomingMessage);

                Intent incomingMessageIntent = new Intent("incomingMessage");
                incomingMessageIntent.putExtra("theMessage",incomingMessage);
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(incomingMessageIntent);

            } catch (IOException e) {
                Log.e(TAG, "write: Error reading Input Stream. " + e.getMessage() );
                break;
            }
        }
    }

And its exceptions:
D/BluetoothConnectionServ: ConnectedThread: Starting.
E/BluetoothConnectionServ: write: Error reading Input Stream. socket closed


text:
Q: Unable to find css property I have used HTML5 template to build a simple web site http://glassta.com , however from past one week i am struggling with a css issue. From attached image you can see there is a gap in right hand side and bottom. Can you please help me to identify the html element creating that gap and how to fix it. Please let me know if you require any other information. Web site url - http://glassta.com

A: Okay, your problem is when the page loads, there is a massive height that pops up. I'm guessing it's the carousel items that's stacked underneath each other. This causes the vertical scroll bar to appear. The carousel then initializes but is taking the width of the viewport that contains the scroll bar. After the INIT the scroll bar hides and you're left with the space it took up.
I haven't used that library yet so I'm not sure how you'd go about fixing the issue. Maybe place an overflow: hidden; on the body tag.

A: Thank you for providing valuable clues, i looked into master slider documentation http://www.masterslider.com/doc/#quickstart and found the slider height is controlled by javascript not css.
I have modified javascript width and height to solve the problem. This javascript will in your index.php page.
slider.setup('masterslider', {
                width: 1400, // slider standard width
                height: 620, // slider standard height
                space: 1,
                layout: 'fullwidth',
                loop: true,
                preload: 0,
                instantStartLayers: true,
                autoplay: true
            });

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I change $ to > in terminal? In any terminal there is specific meaning of puneet@Puneet-Ubuntu-PC:~$I want to replace '$' symbol with '>'.
Please guide me How can I make this change.

A: Open .bashrc file with your favorite text editor. In my case I used nano. Find the line that looks like
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '

In my case it was at line 53. Replace it with:
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]> '

And you are done. Open a new terminal to see changes.


text:
Q: NotQueryBuilder elasticsearch 2.4 execution modes what is the alternative for .execution("and") in elastic search 2.4? and what exactly its usage –
 NotFilterBuilder excVariantsFilter = FilterBuilders.notFilter(FilterBuilders.termsFilter("products", productIds.toArray()).execution("and"));

A: Filters and queries have been merged in ES 2.0 and the execution mode was only useful in a filter context, so there's no need anymore for that execution parameter in terms queries.
So if you want an equivalent behavior to this
NotFilterBuilder excVariantsFilter = FilterBuilders.notFilter(FilterBuilders.termsFilter("products", productIds.toArray()).execution("and"));

you can now write it like this:
BoolQueryBuilder excVariantsFilter = QueryBuilders.boolQuery();
for (String productId : productIds.toArray()) {
    excVariantsFilter.mustNot(QueryBuilders.termQuery("products", productId));
}

It will produce a bool/must_not query containing a term query for each productId, which is equivalent to the previous not filter containing a terms query with and execution mode


text:
Q: RewriteRule при переносе файлов из корня в директорию Раньше много файлов проекта лежало в корне. В том числе в корне были такие файлы:
index.php
make.php

Чтобы навести порядок, вышеуказанные файлы были переложены в папку /operation/
Вопрос: как написать правило переадресации в .htaccess так, чтобы все ссылки вида
https://myproject.ru/
https://myproject.ru/?var=value
https://myproject.ru/make.php

продолжили работать, и чтобы клиент даже не догадался, что на самом деле обращение идет к файлам
https://myproject.ru/operation/
https://myproject.ru/operation/?var=value
https://myproject.ru/operation/make.php

Если я указываю такие правила в файле .htaccess
RewriteEngine On
RewriteRule ^/?$ /operation/
RewriteRule ^/(.*\.php)$ /operation/$1

то страница https://myproject.ru/ открывается нормально, а вот вызов https://myproject.ru/make.php не работает.

A: Мне помогла такая настройка:
RewriteEngine On
RewriteBase /
RewriteRule ^([^/]*)$ /operation/$1 [NC]


text:
Q: Find the Moment Generating Function $Y$. What is the distribution of $Y$? Let $X_1$ and $X_2$ be independent normal variables with means 2 and 5 and variances 9 and 1.
Let $Y = 3X_1 + 6X_2 - 8$. Find  MGF. What is the distribution of $Y$.
attempt:
Im not sure about the MG.
But for the distribution I got N~[28, 109]. Does this answer this question?

A: Sure the variance is $117$ as it is said in André´s comment. I think you have rather  miscalculated it than not knowing how to calculate it. It seems that you  substracted the constant $8$. But the constant does not affect the variance.
The moment generating function of the normal distribution can be looked up. Let denote the moment generating function of $X$ as $M_X(t)$, where $X$ is normal distributed. Similar for the random variable $Y$. And let $Z=a+bX+cY$
Then the MFG of $Z$ is
$e^{at}\cdot M_X(tb)\cdot M_Y(tc)$

A: Comments:
Looking through the Q and A here, I'm not absolutely sure what
prompted the question. Not truly realizing that this kind of
linear combination of normal random variables is again normal?
Not realizing that once the mean and variance of a normal RV
are known it is trivial to write the MGF? In any case, the
Answer from @callculus should cover most of the technical details (+1).
In case it might help with intuition or visualization, here is a
simulation in R of a million realizations of $Z$.
[Notes: In R the
parameters of a normal distribution are the mean $\mu$ and
the SD $\sigma.$ The null hypothesis of Shapiro-Wilk test
is that the data are from some normal distribution. The
implementation of this test in R will handle up to 5000 observations.]
 m = 10^6;  x1 = rnorm(m, 2, 3);  x2  = rnorm(m, 5, 1)
 z = 3*x1 + 6*x2 - 8
 mean(z);  sd(z)
 ## 27.98318  # aprx pop mean (about 2-3 signif digits)
 ## 10.81479  # aprx pop SD (about 2-3 signif digits)
 shapiro.test(z[1:5000])

    Shapiro-Wilk normality test

 data:  z[1:5000]      # normality test of 1st 5000 simulated z's
 W = 0.9998, p-value = 0.878  # cannot reject normality

The following histogram shows a good match of the million simulated
$Z$'s with the normal distribution having $\mu = 28$ andd $\sigma = \sqrt{117} \approx 10.817,$


text:
Q: Assert Variable is not Null I have a Variable with type DateTime?
In a Function I check it for being null and want to use it afterwards without always having to ?. every call. In e.g. Kotlin the IDE recognizes a check like that and asserts that the variable cannot be null afterwards. Is there a way to do this in C#?
DateTime? BFreigabe = getDateTime();
if (BFreigabe == null) return false;
TimeSpan span = BFreigabe - DateTime.Now;
//Shows Error because it.BFreigabe has the type DateTime?, even though it can't be null

Edit:
When using
TimeSpan span = BFreigabe.Value - DateTime.Now;

instead it works in this case because .Value doesn't have nullsafety at all. However, considering that this would compile even without the null check and just produce an error, the general question still remains. How can one persuade C# that a former nullable variable isn't nullable any more?
Edit 2
Casting DateTime on the Variable works.
TimeSpan span = (DateTime)BFreigabe - DateTime.Now;

Still not as safe as in Kotlin, but similar enough.

A: If you have the previous check, you can access the value. Nullable types always have two properties: HasValue and Value.
You could either cast to DateTime (Without the ?) or use the value property.
DateTime? BFreigabe = getDateTime();
if (!BFreigabe.HasValue == null)
    return false;

TimeSpan span = BFreigabe.Value - DateTime.Now;

Or store the nullable variable in a non nullable variable:
DateTime? BFreigabe = getDateTime();
if (BFreigabe.HasValue == null)
{
    DateTime neverNull = BFreigabe.Value;
    TimeSpan span = neverNull  - DateTime.Now;
}

This will get full editor support and guarantee that there is no NullReferenceExcpetion.
EDIT: Because your question states Assert.  Assert usually means that we will throw an exception if the state is invalid.
In this case, omit the check for nullness. If you access var.Value while var is null, this will throw a NullReferenceException. This moves the responsibility to the caller.
Another option would be to not use the nullable variable. Either by converting it (see the second listing) or by not accepting Nullable types as a parameter.
function TimeSpan Calc(DateTime time)
{
    // here we know for sure, that time is never null
}

A: How about this?
DateTime? BFreigabe = getDateTime();
if (!BFreigabe.HasValue) return false;
DateTime BFreigabeValue = BFreigabe.Value;
TimeSpan span = BFreigabeValue - DateTime.Now;

A: Try to convert NULL value to any value, that is irrelevant.
DateTime? BFreigabe = getDateTime();
if (BFreigabe == null) return false;
TimeSpan span = (BFreigabe??DateTime.Now) - DateTime.Now;


text:
Q: Too Many Query Rows 50001 - even with limit I'm getting a "Too Many Query Row 50001" error even if I have a limit of 1000.  Want to know what I'm doing wrong or clause I am missing.
public Task[] getListTasks() {
  List<Contact> cntct = [SELECT Id, Name FROM Contact];
  List<Id> contactIds = new List<Id>();

  for(Contact cn : cntct) {
   contactIds.add(cn.Id);
  }

  taskList = 'select whoid,subject,status,LastModifiedDate, WhatID, Description, Primary_Contact_Phone_Number__c, Primary_Contact_Email_Address__c, Call_Result__c, Last_Call_Date__c, Last_Call_Agent__c from task where CreatedbyId=\''+currentUser+'\'order by LastModifiedDate asc limit 1000 WHERE CreatedDate > 2013-06-11T10:00:00-08:00';

  //delete duplicate property records
  List<Task> tskList = Database.query(taskList);

  for (Integer d = 0; d < tskList.size(); d++){
    String checkWhat=tskList[d].WhatID;

    for (Integer i = 0; i < tskList.size(); i++){
      if(tskList[i].WhatID == checkWhat){
        String debugV=tskList[i].WhatID;
        tskList.remove(i);
      }
      else{
        String debugV=tskList[i].WhatID;
      }
    }
  }

  return tskList;
}

public void reset(){
  taskList = 'select whoid,subject,status,LastModifiedDate, WhatID, Description, Primary_Contact_Phone_Number__c, Primary_Contact_Email_Address__c, Call_Result__c, Last_Call_Date__c, Last_Call_Agent__c from task where id !=null   order by LastModifiedDate desc Limit 1000';
  List<Task> tskList = Database.query(taskList);
}

Can you guys help out?

A: This probably isn't all of the problem, but at least in part, your SOQL statements are out of order, and that might be why the LIMIT isn't having any effect on at least the task query. Adrian's right though, your code is likely failing before it even hits that, at the contacts query because you don't have either a LIMIT or a WHERE clause to narrow down the number of returned records.
It should be:
task = 'SELECT WhoId, Subject, Status, LastModifiedDate, WhatId, Description, Primary_Contact_Phone_Number__c, Primary_Contact_Email_Address__c, Call_Result__c, Last_Call_Date__c, Last_Call_Agent__c FROM Task WHERE CreatedbyId=\''+currentUser+'\' AND  CreatedDate > 2013-06-11T10:00:00-08:00 ORDER BY LastModifiedDate ASC LIMIT 1000';

Also: I'm going to "suggest an edit" and clean up your post if that's alright. Remove the debugs, commented out lines, and re-indent it so it's easier for everyone to read.

A: the only way to fetch more than 50000 rows it to move your code to a batch class and then call this batch class from within your code.
The batch documentation says:

For example, a batch Apex job for the Account object can return a QueryLocator for all account records (up to 50 million records) in an org.

Here you can get some further information about apex batch https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_batch_interface.htm


text:
Q: typescript string interpolation with lodash In my application, I have a H custom component that takes in a header and a subheader as props.
For my header prop, I want to concatenate the lodash expression with a string. See below my code.
        <H
          header= `${_.startCase(type)} SomeString`
          subheader= "Lorem ipsum do eiusmod"
        />

I have tried the suggestions here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals, but maybe because I am using lodash it is not working.

A: The syntax for your prop is incorrect:
header={`${_.startCase(type)} SomeString`}

In React, any prop value that contains code must be enclosed in {}.
Only constant strings like prop="a string" may be passed without a pair of enclosing {}. All other values require it*.

* Well, there are two special cases.
children which is set like the following. Here children is something like <>content</>.
<MyComponent>content</MyComponent>

And boolean shorthand props. Here isCool is true.
<MyComponent isCool />

Although, if you want to set it to false you need curly braces again:
<MyComponent isCool={false} />


text:
Q: Generating 3D point cloud with predicted Depths I was trying to generate a 3D point cloud (PC) from an image with predicted depths. The camera intrinsics and the ground truth depth images are given. Firstly, I am generating a PC with the GT depth using the camera intrinsic and it looks like this:

But, when I try to generate the PC for the same image with the predicted depths, the PC looks weird. Here is the PC with the predicted depths:

I am using the same camera intrinsics for doing this. I am using the same code and procedure for both the PC generations. I was expecting two PCs to be close but what I am getting is really weird. What am I doing wrong?
My code for generating the point cloud is as follows:
int rows = RGB.size[0];
int cols = RGB.size[1];
for (int v = 0; v < rows; v++) {
    for (int u = 0; u < cols; u++) {
        auto z = depth.at<ushort>(v, u) / 5000;
        auto x = (u - intrinsics.cx) * z / intrinsics.fx;
        auto y = (v - intrinsics.cy) * z / intrinsics.fy;

        // std::cout<<"x = "<< x << " y = " << y <<std::endl;
        point3d << x, y, z;
        pc.vertices.push_back(point3d);
        pc.colors.push_back(RGB.at<cv::Vec3b>(v, u));

    }
}

The GT depth image:

The predicted depth image:

Edit: I found the mistake. The depth values were scaled by 5000. So, I missed that part and didn't divide the value of z while constructing the point cloud. After dividing by 5000, the problem was resolved.

A: The depth value should have been divided by 5000 while constructing the 3D scene as the depth values were scaled by 5000 originally.
For details The camera intrinsics and guide on how to construct the 3D point cloud


text:
Q: CSS selector to get preceding sibling Is there any way using pure CSS(3) to select an element that is a preceding sibling of an element with a particular class?
i.e.:
html:

css:
#box1{ /*some styling*/ }
#box2{ /*some styling*/ }

#box2.active .....

Now, when #box2 has the class active I want to select and do something to the style of #element-to-find.  Is there anyway to accomplish this?

A: There were multiple proposals to CSSWG in www-style@w3.org mailing list as for previous-sibling combinator: my one (2012), another 1, 2 (2013).
Common answer by Tab Atkins is like "we already have subject indicator for this". For selecting descendants of previous sibling (which would be trivial with previous-sibling combinator, e.g. .example - UL > LI), he suggests to use :matches() functional pseudoclass, e.g. :matches(!UL + .example) > LI. Both subject indicator and :matches() are currently in draft state and cannot be used in real world yet.
So you should add a regular class to the element-to-find element or (much less desired if your active class is added not via JS) use JavaScript to emulate previous-sibling-combinator functionality.

A: Without knowing any more of your selectors, you could potentially use CSS's :not() selector.
div:not(#box1), div:not(#box2) {
    /*some style here*/
}

I would just suggest giving your #element-to-find a class as well when you select box2 and have a style ready for it.


text:
Q: "LIMIT" using column as delimiter Hello Fellow PHP/MySQL Gurus
Today, I was presented with a problem while coding a project. The problem is as follows. I am polling information from my user account table to be displayed and later used as a webpage account editor. I have all of the background PHP complete. It works fine. While "SELECT"ing my information, I am asking for 2 columns. User ID and Full Name. Below is example data:
User ID | Full Name
11234   | John Doe
11235   | Jane Doe
11236   | Amanda Hug
11236   | Amanda's Tablet

This data (as with my physical data) has users whose name and uid is saved. In this example (and again, my physical data), a user (Amanda) has 2 accounts, stored under the same UID (this is done intentionally for personal reasons). When I "SELECT" the users, I want to only have one Amanda appear. Such as:
$q=mysql_query("SELECT `uid`,`Name` FROM `User_Accounts` WHERE ... ");

The ... representing the portion of code where I "LIMIT 1" to the UID field.

A: $q=mysql_query("SELECT `uid`,`Name` FROM `User_Accounts` GROUP BY `uid`");

GROUP BY is the best way to extract multiple data, since that data has the same ID you can use GROUP BY.


text:
Q: Obtaining sinusoidal expression I have the question " The instantaneous values of two alternating currents are given by i1 = 20sinwt amperes and
i2 = 10sin(wt + pi/3) amperes. By plotting i1 and i2 on the same axes, using the same scale, over one cycle, and adding ordinates at intervals, obtain a sinusoidal expression for i1 + i2."
The graph for the question is:

The answer for the sinusoidal expression is:

I understand everything except for the 19 degrees. The solutions say that the resultant waveform leads the curve i1 = 20sinwt by 19 degrees which is 0.332 rads, however I do not understand where the 19 degrees came from.

A: Let the resultant equation be $26.5\sin (wt+a) $ now at any time $t $ resultant displacements of two waves and this new wave should be equal as both are equal. Now for simplifications put $t=0$ for first two currents the resultant is $0+8.66$ this should be equal to $26.5 \sin (0+a) $ thus $8.66=26.5\sin (a) $ which gives $a\approx 19^\circ. $


text:
Q: How to Disable a CSS Property and Make It Invalid Okay, so here is the concept. My HTML document has a button that onClick runs a Javascript function. On the web page there are two big divisions, and the purpose of the button is to swap the divisions' places. For example, the one that was on the left goes the right, and the one on the right to the left.
The problem is, the "left" CSS property has dominance over the "right" property, so if both the left and right properties are set to 0 on a div with a fixed width, it will go to the left. Therefore, I cannot get what is on the left over to the right because the "left" property is still present.
I need some way to make the left property invalid, as if I had never even set it so the div will go to the right.
The two divs are called "content" and "navigation" and here is my JS:
var order = 0;
var current;
var switchLayout = function() {
    if(order === 0) {
        current = document.getElementById('content');
        current.style.position = 'absolute';
        current = document.getElementById('navigation');
        current.style.left = '0';
        order = 1;
    } else {
        current = document.getElementById('content');
        current.style.position = 'relative';
        current = document.getElementById('navigation');
        current.style.left = 'null';
        current.style.right = '0';
        order = 0;
    }
}

Any help is appreciated. Thanks!

A: Dont do your css in Javascript. The easiest way to solve this is have two css classes
.left{
 /* styling */
}
.right {
/* styling */
}

var switchLayout = function() {
    var content = document.getElementById('content'),
        nav = document.getElementById('navigation');
    if (content.className === "left") {
        content.className = "right";
        nav.className = "left";
    } else {
        content.className = "left";
        nav.className = "right";
    }
}


text:
Q: How to push persistent events from a central server to others? I have a system that consists of one central server, many mobile clients and many worker server. Each worker server has its own database and may be on the customer infrastructure (when he purchases the on premise installation).
In my current design, mobile clients send updates to the central server, which updates its database. The worker servers periodically pull the central to get updated information. This "pull model" creates a lot of requests and is still not suficient, because workers often use outdated information.
I want a "push model", where the central server can "post" updates to "somewhere", which persist the last version of the data. Then workers can "subscribe" to this "somewhere" and be always up-to-date.
The main problems are:

*

*A worker server may be offline when an update happen. When it come back online, it should receive the updates it lost.

*A new worker server may be created and need to get the updated data, even the data that was posted before it exists.

A bonus point:

*Not needing to manage this "somewhere" myself. My application is deployed at AWS, so if there's any combination of services I can use to achieve that would be great. Everything I found has limited time data retention.

A: The problems with a push model are:

*

*If clients are offline, the central system would need a retry method, which would generate many more requests than a push model

*The clients might be behind firewalls, so cannot receive the message

*It is not scalable

A pull model is much more efficient:

*

*Clients should retrieve the latest data when the start, and also at regular intervals

*New clients simply connect to the central server -- no need to update the central server with a list of clients (depending upon your security needs)

*It is much more scalable

There are several options for serving traffic to pull requests:

*

*Via an API call, powered by AWS API Gateway. You would then need an AWS Lambda function or a web server to handle the request.

*Directly from DynamoDB (but the clients would require access credentials)

*From an Amazon S3 bucket

Using an S3 bucket has many advantages: Highly scalable, a good range of security options (public; via credentials; via pre-signed URLs), no servers required.
Simply put the data in an S3 bucket and have the clients "pull" the data. You could have one set of files for "every" client, and a specific file for each individual client, thereby enabling individual configuration. Just think of S3 as a very large key-value datastore.


text:
Q: text inside double brackets follow borders text inside {{payment.lastappointment}} if its too long will go beyond the card borders is there any trick to make follow the card borders (text will array in lines when no more width to accommodate the whole text)??

<q-card-section>

Work Done: {{payment.lastappointment }}

{{paymentdateAdded(payment.paymentdate)}}

<q-badge   color="green"  >Money Paid: {{formatPrice(payment.moneypaid)}} {{payment.currencypaid}}</q-badge>

<q-badge  color="orange"  >Total To Pay: {{formatPrice(payment.moneyhavetopay)}} {{payment.currencyhavetopay}}</q-badge>

<q-badge color="green"  >Paid: {{formatPrice(payment.moneypaid)}} {{payment.currencypaid}}</q-badge>

<q-badge  color="orange"   >Total: {{formatPrice(payment.moneyhavetopay)}} {{payment.currencyhavetopay}}</q-badge>

  </q-card-section>

A: Just trying to understand the use case of inner div element
. We can remove this element as this is the only div element available under col-8. Which results in resolve the issue.
Demo :

body { padding: 20px; }
.container {
  padding-right: 15px;
  padding-left: 15px;
}
[class*="col-"] {
  padding-top: 15px;
  padding-bottom: 15px;
  background-color: #eee;
  background-color: rgba(86,61,124,.15);
  border: 1px solid #ddd;
  border: 1px solid rgba(86,61,124,.2);
  font-size: 11px;
}

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
Q: ¿Cómo pasar datos del html a flask, para guardarse en mongoDB? Estoy aprendiendo el uso de mongodb con pytHon, utilizando el Framework Flask.
Intento guardar el nombre, sexo y la calificación, después de dar clic en botón agregar; después de que realizo esa operación me arroja un error en la página web:

Method Not Allowed
The method is not allowed for the requested URL.

He intentado buscar información al respecto, pero no consigo respuestas idóneas, o tal vez estoy realizando una búsqueda equivocada.
app.py
from flask import Flask
from flask import render_template, request
import pymongo

app = Flask(__name__)

MONGO_HOST = "localhost"
MONGO_PUERTO = "27017"
MONGO_TIEMPO_FUERA = 1000

MONGO_URI = "mongodb://"+MONGO_HOST+":"+MONGO_PUERTO+"/"

MONGO_BASEDATOS = "escuela"
MONGO_COLECCION = "alumnos"

try:
    cliente = pymongo.MongoClient(
    MONGO_URI, serverSelectionTimeoutMS=MONGO_TIEMPO_FUERA)
    baseDatos = cliente[MONGO_BASEDATOS]
    coleccion = baseDatos[MONGO_COLECCION]
    cliente.server_info()
    print("Conexión establecida satisfactoriamente")
    cliente.close
except pymongo.errors.ServerSelectionTimeoutError as errorTiempo:
    print("Tiempo excedido"+errorTiempo)
except pymongo.errors.ConnectionFailure as errorConexion:
    print("Falló al conectarse a la base de datos"+errorConexion)

@app.route("/")
def index():
    return render_template('empleados/index.html')

@app.route("/registrar")
def registrar():
   return render_template('empleados/create.html')

@app.route("/store", methods = ['POST'])
def storage():
    nombre_recibido = request.args['txtNombre']
    sexo_recibido = request.args['txtSexo']
    calificacion_recibido = request.args['txtCalificacion']
    baseDatos.coleccion.insert_one({
        'nombre':nombre_recibido,
        'sexo': sexo_recibido,
        'calificacion': calificacion_recibido
    })
    return render_template('empleados/create.html')

if __name__ == "__main__":
    app.run(debug=True)

create.html
<form action="" method="post" action="/store" enctype="multipart/form-data">
  Nombre:
  <input type="text" name="txtNombre" id="txtNombre">

  Sexo:
  <input type="text" name="txtSexo" id="txtSexo">

  Calificación:
  <input type="text" name="txtCalificacion" id="txtCalificacion">

  <input type="submit" value="Agregar">
</form>

A: Hola estimado Hoffman:
Tienes 2 errores en tu aplicacion:

*

*Error
Por lo general las peticiones de un formulario van a ir directamente a la url cuya función la renderizo en este caso a tu función registrar, pero como dicha función no permite el método POST te muestra el error.
Si lo que deseas hacer es enviar a otro endpoint debes emplear url_for en el action del form para asignar el endpoint:
<form action="{{ url_for("store") }}" method="post" enctype="multipart/form-data">
  Nombre:
  <input type="text" name="txtNombre" id="txtNombre">

  Sexo:
  <input type="text" name="txtSexo" id="txtSexo">

  Calificación:
  <input type="text" name="txtCalificacion" id="txtCalificacion">

  <input type="submit" value="Agregar">
</form>

*error

Para acceder a los valores enviados desde el formulario debes utilizar request.form["CAMPO"] en lugar de request.args["CAMPO"]
@app.route("/store", methods = ['POST'])
def storage():
    nombre_recibido = request.form['txtNombre']
    sexo_recibido = request.form['txtSexo']
    calificacion_recibido = request.form['txtCalificacion']
    baseDatos.coleccion.insert_one({
        'nombre':nombre_recibido,
        'sexo': sexo_recibido,
        'calificacion': calificacion_recibido
    })
    return render_template('empleados/create.html')


text:
Q: How to properly demux this PES packet from the program stream file? I'm demuxing one program stream file and I can't figure out what one PES packet is carrying. (see picture below).
Stream ID is 0xE0, so it is a video stream. Since I'm reading a program stream file, it is the only video stream. As you can see, the packet length is 0x9C, the next byte 0x80 tells us that first two bits are '10', as expected and PES_scrambling_control, PES_priority, data_alignment_indicator, copyright and original_or_copy are all 0 (not set). The next byte 0x09 tells us that we have DSM_trick_mode_flag and PES_extension_flag set. The next byte 0x78 is PES header length. If we skip PES header, we will be at the first byte in the framed area containing 33 bytes. It begins with 00 37 B0... These 33 bytes should be skipped when demuxing, but I can't figure out why. Any comment or suggestion is very welcome.
PES packet picture
PES packet hex values as text:
00 00 01 e0 00 9c 80 09 78 00 52 40 09 ac 00 3f
40 00 22 00 d7 c0 00 e2 00 da 20 04 8a 00 62 60
02 36 00 46 10 0e a1 00 28 50 01 b9 00 d9 d0 09
cd 00 67 30 0f a3 00 44 b0 04 6b 00 8f b0 0d e7
00 64 f0 00 57 00 41 70 09 d7 00 a7 70 0d 5f 00
73 f0 0c 40 80 f8 88 00 b0 80 23 88 06 68 80 38
88 0b a8 80 be 08 07 b0 80 b3 f0 0a 10 80 67 70
08 90 80 b6 70 03 10 80 7f b0 09 00 80 f1 b0 0f
2f 00 37 b0 09 77 00 a4 70 0e 37 00 ca 70 07 47
00 b1 b0 03 33 00 3e 30 06 bd 00 77 50 05 2d 00
15 50


text:
Q: AlertDialog from non activity class. new activity class dose not work I want to create an alert dialog on non-activity and knew that I can't do it in non activity unless I create an alert activity.
I implemented as follows but it doesn't work - if I click nothing changes.
This is the alert class call in non activity:
    Class alertDeletion=AlertDeletion.class;
    Intent myIntent = new Intent(mContext,alertDeletion );
    mContext.startActivity(myIntent);
    if (getFlag()){ // do some thing }

this is the AlertDialog activity
public class AlertDeletion extends AppCompatActivity  {
private static boolean flag;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alert_deletion);
    flag= confermation();
    finish();
}
public  boolean confermation(){
  //  boolean answer =false;
    AlertDialog.Builder alert = new AlertDialog.Builder(
            this);
    alert.setTitle("Alert!!");
    alert.setMessage("Are you sure to delete ");
    alert.setPositiveButton("YES", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
           setFlag(true);
            dialog.dismiss();
        }
    });
    alert.setNegativeButton("NO", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
         setFlag(false);
            dialog.dismiss();
        }
    });
    AlertDialog builder = alert.create();
    builder.show();
    return getFlag();
}
private void setFlag(boolean t){
 flag=t;
}
public static boolean getFlag(){
    return flag;
}
}

A: Instead of getFlag() use alertDeletion.getFlag() in the if condition if (getFlag()){ // do some thing }


text:
Q: How can I prevent iCheck from styling certain checkboxes, while still styling others? I just incorporated iCheck (http://icheck.fronteed.com) into my site in order to replace the bland default checkbox elements on the page with the more visually appealing checkbox styles offered by iCheck.
iCheck is working really well for the most part, but for some reason it's breaking the functionality of the columnselector widget (https://mottie.github.io/tablesorter/docs/example-widget-column-selector.html) that I'm using for tablesorter.
To remedy this, I'd love to style every checkbox on my site using iCheck, EXCEPT for any checkboxes that are part of the columnselector widget. Is there a way to either have iCheck ignore a specific div or checkbox (by adding a class), OR to only have iCheck style checkboxes that are labeled with a specific class?
Thanks in advance for any tips you might be able to suggest!

A: I assume that the checkboxes which you want to style and which you do not want to style will have different classes. If not please add an additional class to the checkboxes which are not supposed to be styled.
For example:
<input type="checkbox" />
<input type="checkbox" class="dont-style" />

//Adding not to the query selector only selects input's without the *dont-style* class
$('input').not('.dont-style').iCheck({
  labelHover: false,
  cursor: true
});

Or else you can just add a class to the checkboxes which you want to style like styleMeand then initialize the plugin like this:
$('.styleMe').iCheck({
      labelHover: false,
      cursor: true
    });


text:
Q: Put a particular image next to a different text for a recycleview using Kotlin I want to create a UI where display is kind of linear form with an text beside each image. I have lot of text but few images. So How do I assign a certain image to any random text.

A: It can be done.
In the onBindViewHolder method of the adapter class we can add the following codesnippet.
holder?.view?.imageView?.setImageResource(R.drawable.pink)

Here pink refers to the name of the image.
I am assuming that we have dropped the images you want to display in the drawable folder.
The above code snippet can be placed in an if clause where we are choosing a certain text and the desired view comes.


text:
Q: Sybase ASE + .NetCore (+ Dapper) Exception: request to send or receive data was disallowed because the socket is not connected ... no address I'm calling sybase ase via Dapper with parameterized sql in .NetCore 2, using AdoDotNetCore.AdoClient.Using it to hit a sybase DB.
I keep getting the "A request to send or receive data was disallowed because the socket is not connected and (when sending on a datagram socket using a sendto call) no address was supplied." error
but the error seems to mean "something went wrong" Its been bad data types on return object, connection timeouts etc.
I'm spending a ton of time trying to brute force debug these errors. Is there a better way to debug these to get to the root issue?
example working code:
var aseSqlConnectionString = Configuration.GetConnectionString("SybaseDBDapper");

            StringBuilder query = new StringBuilder();

            query.Append("SELECT stud_id, ad_guid, ad_name, ad_pass_expire_dt, ad_last_login_dt, alumni");
            query.Append("      from student  ");
            query.Append("  where LOWER( ad_name ) = Lower( @studentAdName )   ");

            string sql = query.ToString();

            DapperTools.DapperCustomMapping< StudentAdDataResponse >( );

            try
            {
                using ( IDbConnection db = new AseConnection(aseSqlConnectionString) )
                {
                    var arguments = new
                                        {
                                            studentAdName = sAdName,
                                        };

                    List< StudentAdDataResponse > ll = new List< StudentAdDataResponse >();
                    //StudentAdDataResponse res =  db.QueryFirst<StudentAdDataResponse>(sql, arguments);
                    //ll.Add( res );

                    ll = db.Query<StudentAdDataResponse>(sql, arguments).ToList();
                    return ll;
                }
            }
            catch (Exception ex)
            {
                Trace.WriteLine( ex.ToString(  ) );
                return null;
            }

example bad code
string sql        = " SELECT period.period_day_cd,    " +
                                "           period.period_no,    " +
                                "           period.period_start_tm,    " +
                                "           period.period_end_tm,    " +
                                "           classroom.clsrm_loc_cd,    " +
                                "           classroom.clsrm_no,    " +
                                "           course.course_name,    " +
                                "           student_schedule.stud_sched_eff_dt,    " +
                                "           student_schedule.sched_type_cd,    " +
                                "           code.code_desc,    " +
                                "           staff.staff_lname,    " +
                                "           staff.staff_fname,    " +
                                "           staff.staff_mi, " +
                                "           'N' as first_eff_dt" +
                                "      FROM code,    " +
                                "           classroom,    " +
                                "           course,    " +
                                "           period,    " +
                                "           staff,    " +
                                "           student_schedule,    " +
                                "           class,    " +
                                "           class_period,    " +
                                "           schedule_item,    " +
                                "           stud_class_sched   " +
                                "     WHERE ( student_schedule.sched_type_cd  = code.code_id ) and   " +
                                "           ( class.clsrm_id = classroom.clsrm_id ) and   " +
                                "           ( schedule_item.sched_item_id = course.sched_item_id ) and   " +
                                "           ( student_schedule.stud_sched_id = stud_class_sched.stud_sched_id ) and   " +
                                "           ( class_period.cls_period_id = stud_class_sched.cls_period_id ) and   " +
                                "           ( class_period.period_id = period.period_id ) and   " +
                                "           ( class_period.cls_id = class.cls_id ) and   " +
                                "           ( class.staff_id = staff.staff_id ) and   " +
                                "           ( class.sched_item_id = schedule_item.sched_item_id ) and   " +
                                "           ( student_schedule.enrtype_id = @enrtypeid ) " +
                                "           order by student_schedule.stud_sched_eff_dt desc,   " +
                                "                   code.code_desc,   " +
                                "                   period.period_day_cd, " +
                                "                   period.period_start_tm  ";

            var aseSqlConnectionString = configuration.GetConnectionString("SybaseDBDapper");
            dapperTools.DapperCustomMapping<StdInfoScheduleCV>();

            try
            {
                List<StdInfoScheduleCV> ll = new List<StdInfoScheduleCV>();

                using ( IDbConnection db = new AseConnection( aseSqlConnectionString ) )
                {
                    try
                    {
                        db.Open(    );

                        var arguments = new
                                            {
                                                enrtypeid = EnrTypeId,
                                            };

                        ll = jcdcDbQuery< StdInfoScheduleCV >( db, sql, arguments );
                    }
                    catch ( Exception ex )
                    {
                        throw;
                    }
                    finally
                    {
                        db.Close();
                    }

                    return ll;
                }
            }
            catch ( Exception ex )
            {
                Trace.WriteLine(ex.ToString());
                //return new List< StdInfoScheduleCV >();
                throw;
            }

I've tried everything I can think of, but can't find the issue.
What steps can I take to diagnose the Sybase ASE + Dapper issue.
The non working code was ported over from a working asp.net mvc 4.5 app, and the db code converted to dapper and .netcore

A: Turns out that the Sybase driver, had issues with int64s.
In my query objects (in and out) I changed all the int64s to int32s, and Sybase was was happy and the error went away.
P.S. I have also gotten the same error for sending "DateTime.ToString()" in as a date, you need to send it as a short date string "DateTime.ToShortDateString()".


text:
Q: Nulls and the MERGE statement: I need to set a value to infinity. How? In SQL Server with a MERGE code, everything is fine except when there are 2 nullable columns.
If I pass a null value and the target isn't null, MERGE doesn't see a difference (evals against null = false). If I use IsNull on both sides (source & target) that works, but has the issue of potentially mis-evaluating a value.
What I mean by the last statement is, if I say:
WHEN MATCHED AND NOT (IsNull(tgt.C, 0) = IsNull(src.C, 0)) THEN

then if tgt.C is null and src.C = 0, no update will be performed. No matter what substitute value I choose, I'll have this problem.
I also tried the "AND NOT (...true...)" syntax since BOL states that evaluations against null result in FALSE. However, it seems they actually result in NULL and do not result in my multi-part statement becoming false.
I thought one solution is to use NaN or -INF or +INF since these are not valid in target. But I can't find a way to express this in the SQL.
Any ideas how to solve this?
EDIT:
The following logic solves the problem, but it's verbose and won't make for fast evals:
declare @i int, @j int

set @j = 0
set @i = 0

if ISNULL(@i, 0) != ISNULL(@j, 0) OR
    ((@i is null or @j is null) and not (@i is null and @j is null))
    print 'update';

A: Actually, this works better. Just add another substitution value as an OR :-
WHEN MATCHED AND
    (
    NOT (IsNull(tgt.C, 0) = IsNull(src.C, 0)) OR NOT (IsNull(tgt.C, 1) = IsNull(src.C, 1))
    )
THEN ....

A: You can use
WHEN MATCHED AND EXISTS (SELECT tgt.C EXCEPT SELECT src.C)

See this article for more on this issue.

A: WHEN MATCHED AND tgt.c <> src.c OR tgt.c IS NULL AND src.c IS NOT NULL OR tgt.c IS NOT NULL AND src.c IS NULL

A: Have  you tried SET ANSI_NULLS OFF, which will make NULL=NULL return true?  This may create additional issues but it could be a script-level workaround (turn it off then on once you run your proc).

A: This works as well and may be better when you have multiple columns that you want to check if they are different.
  MERGE @t2 a

  using @t1 b

  ON a.PK = b.PK

  WHEN MATCHED AND CHECKSUM(a.PK,a.VALUE)!= CHECKSUM(b.pk,b.VALUE)

  THEN UPDATE SET a.VALUE = b.VALUE;

A: You can change the ON part of the merge statement, putting in a check for when both source and target are null.
MERGE tgt
USING src
ON ( -- enter non-nullable columns to match on ...
    tgt.A = src.A
    AND (tgt.C = src.C OR (tgt.C IS NULL AND src.C IS NULL))
)
WHEN MATCHED -- ...

A: You can check for null in the ON Clause:
MERGE TargetTable
USING (VALUES (0)) as s(x)
ON last_run is not null
WHEN not matched then
insert (last_run) values(getdate())
when matched then
update set last_run=getDate();

A: Instead of using 0 when the values are null, why not use a value that is highly unlikely to exist?
EG (IsNull(tgt.C, 2093128301).
The datatypes are int so you have a lot to play with......

A: WHEN MATCHED AND
(
   NULLIF(tgt.C, src.C) IS NOT NULL OR NULLIF(src.C, tgt.C) IS NOT NULL
)
THEN


text:
Q: Frontend plugin which is included via typoScript does not work in TYPO3 8.7 anymore in TYPO3 7.6 I defined a Frontend Plugin which is of type "PLUGIN_TYPE_CONTENT_ELEMENT".
ext_localconf.php:
ExtensionUtility::configurePlugin(
    'MyVendor.' . $_EXTKEY,
    'Maildownload',
    ['Maildownload' => 'show'],
    [],
    ExtensionUtility::PLUGIN_TYPE_CONTENT_ELEMENT
);

the configurePlugin method creates a typoScript Setup, where the the "run()" method of Extbase's Bootstrap class is called:
...
tt_content.myext_maildownload.20 = USER
tt_content.myext_maildownload20.userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
...

This means Extbase processes the request by calling the action "show" in the controller "Maildownload" of my extension.
I Call my plugin via ajax. That means, I define a page with a separate typenum and include the plugin via typoScript:
setup.ts:
ajax_page = PAGE
ajax_page {
  typeNum = 123
  config.disableAllHeaderCode = 1
  config.metaCharset = UTF-8
  config.debug = 0
  config.additionalHeaders = Content-type:application/json
  config.xhtml_cleaning = 0
  config.adminPanel = 0

  10 < tt_content.myext_maildownload
}

When I call the page index.php?type=123 the action "show" in the controller "Maildownload" will be executed.
After upgrading to TYPO3 8.7 this behaviour has obviously changed.
The generated typoScript code of the "configurePlugin()" method is still the same. When I call page index.php?type=123 TYPO3 renders it like an ordinary content element and does not call the TYPO3\CMS\Extbase\Core\Bootstrap->run method anymore. So my showAction method will not be called.
I could define a dataProcessor class now and move the showAction into it.
But that is not a great solution, because I don't want to bypass the complete extbase renderering process.
Is there now a new way to include my plugin into the page so that it will be treated like an extbase plugin and not like a content element?

A: @andrei thank you for your reply, but it did not hit the point.
Meanwhile I found out that the cause for the problem was this breaking change in TYPO3 8.5: https://docs.typo3.org/typo3cms/extensions/core/Changelog/8.5/Breaking-78002-EnforceCHashArgumentForExtbaseActions.html?highlight=chash
so a possible solution is to set the requireCHashArgumentForActionArguments to false in the typoScript plugin settings:
plugin.tx_myextension {

   features.requireCHashArgumentForActionArguments = 0

   ...

}


text:
Q: Making rows NaN based on many conditions If I have a dataframe with some index and some value as follows:
import pandas as pd
from random import random

my_index = []
my_vals = []
for i in range(1000):
    my_index.append(i+random())
    my_vals.append(random())

df_vals = pd.DataFrame({'my_index': my_index, 'my_vals': my_vals})

And I have a second dataframe with a column start and end, a row must be read as an interval, so the first row would be interval from 1 to 4 (including 1 and 4). It is the following dataframe:
df_intervals = pd.DataFrame({'start': [1, 7, 54, 73, 136, 235, 645, 785, 968], 'end': [4, 34, 65, 90, 200, 510, 700, 805, 988]})

I would like to make all values in the my_vals column of df_vals a NaN if the row's index (my_index) does not fall in to one of the intervals specified in the df_intervals dataframe. What is the best way to go about this automatically rather than specifying each condition manually?
(In my actual data set there are more than 9 intervals, this is some example data)
EDIT: in my actual data these indeces are not strictly integers, these can also be random floats

A: One way would be to create an array that would include all the values of your intervals, for example when start = 1 and end = 4, the array would be [1,2,3,4]. Similarly when start = 7 and end = 34, the array would be [7,8,9,10 ... , 34].
intervals_exp = df_intervals.apply(lambda row: [n for n in range(row['start'],row['end']+1)],axis=1).explode().values
intervals_exp

array([1, 2, 3, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21,
       22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 54, 55, 56, 57, 58,
       59, 60, 61, 62, 63, 64, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, .. 986, 987], dtype=object)]

Then you can use isin to check which values of 'my_index' are in the above array using np.where:
df_vals['my_vals refined'] = np.where(df_vals['my_index'].isin(intervals_exp),df_vals['my_index'],np.nan)

which prints:
     my_index   my_vals  my_vals refined
0           0  0.564172              NaN
1           1  0.852806              1.0
2           2  0.643407              2.0
3           3  0.719642              3.0
4           4  0.233949              4.0
..        ...       ...              ...
995       995  0.355014              NaN
996       996  0.842957              NaN
997       997  0.143479              NaN
998       998  0.915176              NaN
999       999  0.147195              NaN

[1000 rows x 3 columns]

A: I believe this is a possible solution,
def index_in_range(index, df):
    for index_, row in df.iterrows():
        if (index >= row['start']) and (index <= row['end']):
            return True

    return False

df_vals['my_vals'] = df_vals.apply(lambda row: row['my_vals'] if index_in_range(row['my_index'], df_intervals) else None, axis=1)

To accomplish this without using a lambda function, you can do the following,
def index_in_range(index, df):
    for index_, row in df.iterrows():
        if (index >= row['start']) and (index <= row['end']):
            return True

    return False

for index_, row in df_vals.iterrows():
    if not index_in_range(row['my_index'], df_intervals):
        df_vals.at[index_, 'my_vals'] = None

Output:
    my_index    my_vals
0   0   NaN
1   1   0.126647
2   2   0.769215
3   3   0.819891
4   4   0.674466
... ... ...
995 995 NaN
996 996 NaN
997 997 NaN
998 998 NaN
999 999 NaN


text:
Q: SYS_B_x in Oracle query result column name I've faced with some weird behaviour of Oracle 11 DB.
I have a simple query selecting data from a view:
select
    (case when exists(select 1 from MY_VIEW v where v.func_name = 'NAME') then 1 else 0 end)
from dual

MY_VIEW looks like:
CREATE OR REPLACE VIEW MY_VIEW
AS
    SELECT a.object_name AS func_name, NULL AS func_desc
    FROM USER_ARGUMENTS a

In the result set, I receive result with columnName: (CASEWHENEXISTS(SELECT:"SYS_B_0"FROMMY_VIEWVWHEREV.FUNC_VALUE=:"SYS_B_1")THEN:"SYS_B_2"ELSE:"SYS_B_3"END)
And when I'm trying to execute this query by Hibernate, it falls with error

SQL Error: 17133 "Invalid identifier or literal"

while extracting column alias.
Error causes when I'm using ojdbc8 driver, with ojdbc6 driver all is OK.
Strange thing is that I have problems only when I'm querying from this particular view.
When I made same query from another View, created from simple table, everything was ok.
Furthermore, I have another Oracle 11 DB and there result set column name for this query looks common:
(CASEWHENEXISTS(SELECT1FROMMY_VIEWVWHEREV.FUNC_VALUE='NAME')THEN1ELSE0END)

My question is: why and when Oracle replaces values in query string on :"SYS_B_x" ?

A: *

*First of all, you need to add an alias for that column.

*You get :SYS_B_x because of the parameter cursor_sharing=force on that database.


text:
Q: How to get the key of indexeddb to be use in put function I am trying to get the key of specific record in indexedDb to be updated. I searched all over the place including IDB's own documentation and have yet to find what I am looking for.
This here is my database ->
IndexedDB records
What I am trying to do in the code below is to grab the keyPath 'id' value to be used to grab the specified record to be updated with the put function.
//Save page when choosen
var cv = document.getElementById('myCanvas');
    let bits = cv.toDataURL("image/png");

    let ob = {
        created: new Date(),
        data: bits
    };

    let trans = db.transaction([currentNotebook], 'readwrite');

    let key = trans.objectStore(currentNotebook).get(getAllKeysRequest.result[currentPage]);

    let editReq = trans.objectStore(currentNotebook).put(ob, key);

    editReq.onerror = function (e) {
        console.log('error storing data');
        console.error(e);
    }

An error occur saying when the above code is being run
<font cUncaught DOMException: Failed to execute 'put' on 'IDBObjectStore': The object store uses in-line keys and the key parameter was provided.

A: So there are two things that seem like they might be giving you trouble.
1) Pertaining to your error of Uncaught DOMException, what the message means is that when you defined your object store you specified an keyPath of id, which means you are using inline keys for this store. This means that when you use the .put() method you cannot pass the key as the second parameter for that method, but you must put it inside the object you are trying to put. So, do ob.id = key and then just pass ob into the put call.
2) The way you get key might also be a problem. The .get() request is an asynchronous call, so there will be an onsuccess event fired when the .get() resolves. So you will want to have a handler to pull the key out of the successful get, and you will want to implement your .put() call inside that.
I've taken your code and modified it to reflect both changes I mentioned:
var cv = document.getElementById('myCanvas');
let bits = cv.toDataURL("image/png");

let ob = {
    created: new Date(),
    data: bits
};

let trans = db.transaction([currentNotebook], 'readwrite');

let key = trans.objectStore(currentNotebook).get(getAllKeysRequest.result[currentPage]);
key.onsuccess = function() {
    let _key = key.result;
    ob.id = _key;

    let editReq = trans.objectStore(currentNotebook).put(ob, key);
    editReq.onerror = function (e) {
        console.log('error storing data');
        console.error(e);
    }
}


text:
Q: Checking if Javascript string is HTML code I have a textbox and submit button which posts the content and a reply to the HTML page.  Is there any way (other than checking if the string's substring at the beginning is

,
,
...,


text:
Q: TPL/PHP: Checkbox checked on page load I need the page to bring this option checked by default in loading the page, but even putting the same check comes in white.
Note that the other field, has a similar structure and comes checked when loading the page.

        <input type="checkbox" name="optInventory"
        {if $gui->projectOptions->inventoryEnabled} checked="checked"  {/if} />
        {$labels.testproject_enable_inventory}

This is checked by default when loading the page:

        <input type="checkbox" name="is_public" {if $gui->is_public eq 1} checked="checked"  {/if} />
        {$labels.public}

A: Output the option value to see if it is really what you expect. Also, I think that Smarty (at least some older versions) don't allow multiple use of -> in an expression. Try to first assign the options to a template variable and then use that in your checkbox:
{assign var=opts value=$gui->projectOptions}
<input type="checkbox" {if $opts->inventoryEnabled}checked="checked"{/if} />


text:
Q: How to query from the dynamic database name inside the function ALTER FUNCTION FnVersion
    (@DBName  NVARCHAR(255),
     @ID  INT)
RETURNS @TABLE TABLE (iD INT, VersionNo INT)
AS
BEGIN
    DECLARE @SQL VARCHAR(2000)

    SET @SQL = @DBName

    SELECT @SQL = 'SELECT iD, VersionNo FROM' + @DBName + '.dbo.ConfigInfo WHERE IdValue = @ID'

    EXECUTE SQL

    RETURN;
END

The db name will be passed as input and the query will be done on dynamic database
The above logic of exec SQL statement caused an error.
What is the way to achieve dynamic query from dynamic database?

A: You can not use dynamic SQL in SQL Function. but make it part of procedure and store those data into temp table with remote procedure call. Performance will be better to use remote procedure rather than remote query.
you can use INSERT INTO with EXEC command. and manipulate temp table with your logic. it would be better approach.


text:
Q: when to clear or make null asp.net mvc models? I am working in an asp .net mvc application. I am using the model and storing some of the values which i need to preserve between the page posts, in the form of datacontexts.
Say my model looks something like this:
public SelectedUser SelectedUserDetails
{
    //get and set has
    //this.datacontext.data.SelectedUser = .....
    //return this.datacontext.data.....
}

Now when this model needs to be cleared? I have many such models with many properties and datacontext. But I don't have an idea on when to clear it. Is there a way or an event that can be triggered automatically when the model is not used for a long time?
Oneway I thought is when i navigate away from a page which uses my underlying model, I can clear that model if its no longer used anywhere and initialize it back as needed. But I need to clear almost many models at many points. Is there an automatic way that can clear models when it is no longer used because care can be taken by my code to initialize them when I need them, but I don't know when to clear them when I no longer need them. I need this to get rid of any memory related issues. Any thoughts or comments?

A: I would use the ASP.NET cache or the Session to keep data between requests.  The cache timeout can be set on the object and it will automatically be removed -- note that you'll need a way to reconstitute it if it is removed before you are done using it.  If you use the session, the objects will be removed when the session times out.  You could also -- by default -- remove it (or replace it) when you hit an action that would start the sequence of actions for which it is needed.


text:
Q: Gstreamer Mac OS install bad plugin I've installed GStreamer SDK for mac os by this tutorial
Gstreamer SDK
But now i need to add a bad plugin in order to work with h264 video
And the question is how i can add bad plugin to framework - based Gstreamer installation?

A: The GStreamer SDK installer for OSX doesn't not install by default plugins with patents issues.
When you launch the installer, make sure you select all the available features in the list to be installed, in particular the FFmpeg one, which provides the H264 decoder you need.


text:
Q: How to convert epoch between timezones in python Hello Amazing people :)
I am just a 17 year old learning to code so please don't be so hard on me, I want to convert an epoch value which is in the timezone UTC +5:30, I want to convert that time stamp to GMT, (London Time), how can I do that in python?
Thank you so much, you all are amazing people :D

A: The time() function returns the number of seconds passed since epoch.
For Unix system, January 1, 1970, 00:00:00 at UTC is epoch (the point where time begins).
import time
seconds = time.time()
print("Seconds since epoch =", seconds)

There is no time difference between Coordinated Universal Time and Greenwich Mean Time 7:17 AM Friday, Coordinated Universal Time (UTC) is 7:17 AM Friday, Greenwich Mean Time (GMT)
Key difference: Both UTC and GMT are time standards that differ in terms of their derivation and their use.
According to timeanddate.com:

The Difference Between GMT and UTC:
Greenwich Mean Time (GMT) is often interchanged or confused with Coordinated Universal Time (UTC). But GMT is a time zone and UTC is a time standard.
Although GMT and UTC share the same current time in practice, there is a basic difference between the two:

*

*GMT is a time zone officially used in some European and African countries. The time can be displayed using both the 24-hour format (0 - 24) or the 12-hour format (1 - 12 am/pm).

*UTC is not a time zone, but a time standard that is the basis for civil time and time zones worldwide. This means that no country or territory officially uses UTC as a local time.


text:
Q: Working remotely in Unity with git repository with my mate. Sync issue Long story short I worked on a game in Unity. Pushed nicely to git repo. Then my mate worked on the project (but he worked on an older version and apparently didn't pull before starting to work) and pushed his changes. He's worked on a different scene but his MainScene is different then mine. So now when I pull his commit my MainScene is back to where it was, discharging all my previous changes.
I made a new branch for my work now. I tried to fork. Nothing really helps and it's a really hard problem to google. I'd appreciate any help.

A: Likely, your mate used git push -f, forcing git to replace your commit by his own. He should have pulled (and hence merged) your changes first.
Good news: Your changes are probably not lost.
Getting back your changes
Assuming both of you worked on the master branch, use git reflog master to find a history of commits that your HEAD was pointing to. Then you can use git branch master <commit-hash> -f to make your own branch point to said commit again (pick the last one that was "yours"). This, at the very first step, restores your local changes.
EDIT: note, you cannot change master in this way if it is currently checked out. Check out anything else before (for example git checkout HEAD^, doesn't matter which). After the git branch master ... -f, checkout your new master with git checkout master.
fsck
If git reflog doesn't show up anything, which can happen even though your commit is still around somewhere, then you can try git fsck --dangling to list all local commits that have nothing pointing to them. See git help fsck how to proceed. A usefull command is
git fsck --dangling | grep commit | awk -- '{print $3}' | xargs git log

Pull
Now, you should be able to pull his changes in. If you then do a git pull, it should really merge his and your changes, and you should be fine.


text:
Q: Prove , there exists $\theta , \phi \in (\frac{\pi}{6},\frac{\pi}{3})$ such that $f'(\theta) = 0$ and $f'(\phi)\neq 0$ Let the function
$$f(\theta) = \begin{vmatrix} \sin\theta & \cos\theta & \tan\theta  \\ \sin(\frac{\pi}{6}) & \cos(\frac{\pi}{6}) & \tan(\frac{\pi}{6}) & \\ \sin(\frac{\pi}{3}) & \cos(\frac{\pi}{3}) & \tan(\frac{\pi}{3})   \end{vmatrix} $$
where
$\theta \in \left[ \frac{\pi}{6},\frac{\pi}{3} \right]$ and $f'(\theta)$     denote the derivative of $f$ with respect to $\theta$. Which of the following statements is/are TRUE?
(I) There exists $\theta \in (\frac{\pi}{6},\frac{\pi}{3})$ such that $f'(\theta) = 0$
(II) There exists $\theta \in (\frac{\pi}{6},\frac{\pi}{3})$ such that $f'(\theta)\neq  0$

*

*I only

*II only

*Both I and II

*Neither I Nor II

I try to explain $:$

$$f(\theta) = \begin{vmatrix} \sin\theta & \cos\theta & \tan\theta  \\ \frac{1}{2} & \frac{\sqrt{3}}{2} & \frac{1}{\sqrt{3}} & \\ \frac{\sqrt{3}}{2} & \frac{1}{2} & \sqrt{3}   \end{vmatrix} $$
$f(\theta) =$$\left(\frac{3}{2}-\frac{1}{2\sqrt{3}}\right)sin\left(\theta\right)-\left(\frac{1}{2\sqrt{3}}-\frac{1}{2}\right)cos\left(\theta\right)+\left(\frac{1}{4}-\frac{3}{4}\right)tan\left(\theta\right)$
Since ,
$f'(\theta) =$$\frac{1}{6}\left(-3\sec ^2\left(\theta\right)-\left(\sqrt{3}-9\right)\cos \left(\theta\right)+\left(\sqrt{3}-3\right)\sin \left(\theta\right)\right)$
I know option (3) is true , since it is possible for both statements .

Can you prove in formal way ?

A: Without explicitly expanding the determinant we see that
$$f(\pi/6) = f(\pi/3) = 0$$
since two of the row are equal in these cases giving us a zero determinant. The mean value theorem then tells us that there exists a $\theta\in(\pi/6,\pi/3)$ where $f'(\theta) = 0$.
If II is false then $f'(\theta) \equiv 0 \implies f(\theta) \equiv 0$ on $(\pi/6,\pi/3)$. Thus a single non-zero value of $f$ on the interval is enough to show that II is true. Take for example $\theta = \pi/4$.


text:
Q: Protecting a method from returning nil on a relation class Recipe < ActiveRecord::Base
  def self.tagged_with(name)
    recipes = Tag.find_by(name: name).recipes
  end
end

In controller
def tag
  @recipes = Recipe.tagged_with(params[:tag])
  render 'index'
end

Routes
get 'tag/:tag', to "recipes#tag"

How can I protect this method from breaking? If I search for a tag that hasn't been created, I get a noMethodError 'recipes' for nil:NilClass. I have tried putting
return false if recipes.nil?

as well as
redirect_to(recipes_path) if recipes.nil?

at the end of the method but nothing as worked.

A: It throws that error because when the value returned by Tag#find_by is nil, it cannot call the method recipes on it. In other words, nil doesn't have a recipes method.
Try checking if the tag exists first, with something like:
class Recipe < ActiveRecord::Base
  def self.tagged_with(name)
    tag = Tag.find_by(name: name)
    recipes = tag.recipes unless tag.nil?
  end
end

I don't know the way you organized your data, but a better way would be something like this probably:
class Recipe < ActiveRecord::Base
  def self.tagged_with(name)
    Recipe.find_by(tag: name)
  end
end

A: def self.tagged_with(name)
     tag = Tag.find_by(name: name)
     if !tag.nil?
        recipes = tag.recipes
     else
        return false
     end

end

In Controller:
def tag
 @recipes = Recipe.tagged_with(params[:tag])
 if @recipes != false
  render 'index'
 else
  redirect_to root_path
 end
end

A: You see NoMethodError because you call method recipies on NilClass.find_by method returns nil if nothing found (by the way, find would raise an exception, and where return empty relation)
So, first you can do is to use try:
`
class Recipe < ActiveRecord::Base
  def self.tagged_with(name)
    recipes = Tag.find_by(name: name).try(:recipes)
  end
end

try will silently return nil
But then you could use a better approach with scope (assuming you have tags relation):
`
class Recipe < ActiveRecord::Base
  has_many :tags
  scope :tagged_with, ->(name) { joins(:tags).where(tags: { name: name }) }
end

Probably, you then want to call uniq on result relation or not to use joins right in a scope etc.


text:
Q: Cannot update repository due to 403 error Trying to update 11.04 to 11.10, I get this:
Failed to fetch
http://pt.archive.ubuntu.com/ubuntu/pool/universe/g/gmp4/libgmp3c2_4.3.2+dfsg-2ubuntu1_amd64.deb
403 Forbidden
Going to the URL in the browser, I see that "gmp4" seems to be empty, trying the same URL for es.archive.ubuntu (for example) has no problem.
Any ideas?
[],
Kharys

A: Edit the current link > http://pt.archive.ubuntu.com/ubuntu/pool/universe/g/gmp4/libgmp3c2_4.3.2+dfsg-2ubuntu1_amd64.deb
To be like this> http://archive.ubuntu.com/ubuntu/pool/universe/g/gmp4/libgmp3c2_4.3.2+dfsg-2ubuntu1_amd64.deb
YOU HAVE AN EXTRA {pt.} in the link.
Otherwise go to the Software Sources> under Download From> change the setting to> Main Server or choose "Other" then "Select Best Server", let it update. Then run sudo apt-get update from a terminal.


text:
Q: Alchemist's problem Consider an alchemist that has many ($N$) sorts of ingredients in his possession. Initial amounts of each of the ingredients is expressed by vector $C^0=(C_1, C_2, \dots, C_N)$.
Alchemist knows several ($M$) recipes of ingredient transmutation, expressed as a set of recipes: $R=\{ R^1, R^2, \dots, R^M\}$. Each recipe $R^i$ is a vector that describes the reagents and the products: $R^i=(R^i_1, R^i_2, \dots, R^i_N)$ such that if $R^i_j, i \in [1 \dots M], j \in [1 \dots N]$ is zero, that means $j'th$ ingredient is not used in mutation, if it is positive, than the ingredient appears in that quantity as a product of a mutation, and if it is negative, than it's quantity is consumed in mutation.
Thus, a single mutation can be expressed as a vector sum: $C^1=C^0+R^i$, where $C^0$ are ingredients before mutation, $C^1$ - after mutation, $R^i$ - mutation recipe.
Consider that we have a market where ingredients are traded. Market prices are fixed and are described by a value vector $v=(v_1, v_2, \dots, v_N)$. Thus, a value of the alchemist's supplies on the $k$-th step can be expressed as a dot product: $V^k=(C^k \cdot v)$.
Question: having the initial supply of ingredients $C^0$, book of recipes $R$ and market prices $v$, how can the alchemist derive such sequence of $L$ mutations $S=(S^0, S^1, S^2, \dots, S^L), \forall t : S^t \in R$ that the price $V^L=(C^L \cdot v)$ of the final set of products $C^L=C^0+S^1+S^2+\dots + S^L$  would be maximal?

A: If you want to solve it via linear programming, you have to make it an integer linear problem.
You could for example define the (boolean) vectors $s^t_i \in \{0, 1\}$ that are 1 when recipe $i$ is applied at time $t$ and 0 if it is not applied.
You then have to add the constraint that $\sum_i s^t_i = 1 \forall t$, in words: Use exactly one recipe at a time.
The next constraint to be added is that $C_j + \sum_i \sum_{t' = 1}^{t} s^{t'}_i R^i_j \geq 0 \forall t, j$, in words: Ingredients can never exist in negative amounts. This is a linear constraint since $R^i_j$ are constants.
Then optimise for $V^L$. You can use e.g. the Gnu Linear Programming Kit to implement this problem.

A: This is precisely the standard linear programming problem.  Any text will discuss it in detail.

A: Since the market prices are fixed and $V^L = C^0 \cdot v + S^0 \cdot v + S^1 \cdot v + \ldots + S^L \cdot v$, you can also assign a value $R^i \cdot v$ to each recipe and use Dijkstras algorithm.
The exact implementation works as follows:

*

*A vertex in the graph is represented by some choice of $n \leq N$ recipes. (You can identify to vertices if the same recipes were chosen in a possibly different order.)

*Two vertices are connected by a directed edge if it is possible to go from one vertex to the next by using one recipe. At this point, one has to take into account that $C^i_k \geq 0$, because if we run out of an ingredient, it is not possible to use it.

*Each edge gets a weight of $O - S \cdot v$ where $O$ is an offset such that all weights are positive (otherwise Dijkstra won't work here) and $S$ is the recipe applied along the edge.

*Identify all vertices that are L steps away from $C^0$ and make this vertex the target vertex.

*Let Dijkstra's algorithm find the shortest way. It has length $L \cdot O - V^L$.


text:
Q: Visual Basic Form stops processes half way through I am running into some interesting issues in my Main form. When I run my program, everything seems to run properly, but after the form loads, some of the functions I put in do not run and variables I have defined do not get new values. I'm not sure what could be causing the blocking of functionality. Below is what I have in the form load action. Below the EmailPort variable is what doesn't run.
I have looked at the question answered before at this link VS2010 does not show unhandled exception message in a WinForms Application on a 64-bit version of Windows and while it gives a good explanation of why this sort of thing happens, I am still unsure of how to make my errors clear so I can debug properly.
    Private Sub MainScreen_Load(sender As Object, e As EventArgs) Handles Me.Load

    'read project path
    Dim path As String = My.Application.Info.DirectoryPath

    'split base path to find root
    Dim BasePath() As String = Split(path, "bin")

    'Sets the current Directory
    Directory.SetCurrentDirectory(BasePath(0) & "Resources")
    'Creates a Path for the file
    Dim Serverpath As String = IO.Path.Combine(BasePath(0), "Resources\Server.ini")
    Dim Configpath As String = IO.Path.Combine(BasePath(0), "Resources\PLCconfig.ini")
    Dim EmailPath As String = IO.Path.Combine(BasePath(0), "Resources\emailIP.ini")

    'Creates a StreamReader
    Dim Server As New StreamReader(Serverpath)
    Dim Config As New StreamReader(Configpath)
    Dim EmailIP As New StreamReader(EmailPath)

    'Read the config file
    Dim allLinesServer As List(Of String) = New List(Of String)
    Do While Not Server.EndOfStream
        allLinesServer.Add(Server.ReadLine())
    Loop
    Server.Close()

    Dim allLinesConfig As List(Of String) = New List(Of String)
    Do While Not Config.EndOfStream
        allLinesConfig.Add(Config.ReadLine())
    Loop
    Config.Close()

    Dim allLinesEmail As List(Of String) = New List(Of String)
    Do While Not EmailIP.EndOfStream
        allLinesEmail.Add(EmailIP.ReadLine())
    Loop
    EmailIP.Close()

    'server information
    ServerName = ReadLine(1, allLinesServer)
    ServerUser = ReadLine(2, allLinesServer)
    ServerPassword = ReadLine(3, allLinesServer)

    'PLC Config Info
    plcIP = ReadLine(1, allLinesConfig)
    plcTag1 = ReadLine(2, allLinesConfig)

    EthernetIPforCLXCom1.IPAddress = plcIP

    EthernetIPforCLXCom1.Write(plcTag1 & ".InputStat", 1)

    'Email Alert Information
    EmailHost = ReadLine(1, allLinesEmail)
    EmailPort = ReadLine(2, allLinesEmail) <--------- Here is where the form stops working

    'Data buffer for intial read in values
    For i As Integer = 0 To 499
        newDatareal(i) = 999.999
        outDatareal(i) = 999.999
        outputDataReals(i) = 999.999
    Next

    For i As Integer = 0 To 999
        newDatabits(i) = vbFalse
        outdatabits(i) = vbFalse
    Next

    'Set up the timer for IO Manager
    outputInitalize = True

    Timer3.Enabled = True
    Timer3.Interval = 1000

    'Checks to see if main screen is open by itself, if it is, open the main dialog screen
    For Each form In My.Application.OpenForms

        If (form.name = Name) Then
            'form is loaded so can do work
            'if you need to check whether it is actually visible

            MainDialogScreen.Show()

            If form.Visible Then
                MainDialogScreen.TopMost = True

            End If
        End If
    Next

End Sub

I am using Visual Studio Community and AdvancedHMI v399a in my code.
Thanks in advance for any guidance you can provide
Edit: I found my error by moving the code I had to a button click like suggested. Because I was using a form load action, I was unable to find where the exception was happening. Lesson Learned. Thanks to Plutonix for the debug tip


text:
Q: Overriden Virtual Function not called I have a struct object that has several virtual functions
object.h
struct object {
public:
    ...
    virtual float intersect(Point, Vector, object*, Point*);
    virtual Vector normal(Point, object*);
};

and they are implemented in another struct called sphere
sphere.h
struct sphere: public object {
        ...
        // intersect ray with sphere
        float intersect(Point, Vector, object*, Point*) override;
        // return the unit normal at a point on sphere
        Vector normal(Point, object*) override;
    };

I and create and store pointers to spheres in a vector via
extern vector<object*> scene;
sphere *new_sphere;
new_sphere = (sphere *) malloc(sizeof(sphere));
...
scene.push_back(new_sphere);

So the problem happens when I try calling intersect with the following code
extern std::vector<object*> scene;
...
object *intersect_scene(Point p, Vector u, Point *intersect, int ignore) {
    for (vector<object*>::iterator it = scene.begin(); it != scene.end(); ++it) {
            float intersect_point = (*it)->intersect(p, u, *it, &temp_hit);
    }

I get the following error from gdb
Program received signal SIGSEGV, Segmentation fault.
0x00000000004042ef in intersect_scene (p=..., u=..., intersect=0x7fffffffdcd0,
    ignore=-1) at trace.cpp:70
70          float intersect_point = (*it)->intersect(p, u, *it, &temp_hit);

Can someone give me some insight as to what's going on here?
by request:
struct Point{
  float x;
  float y;
  float z;
};

struct Vector{
  float x;
  float y;
  float z;
};

A: Do not use malloc to construct non-POD objects.  Use new instead.
All malloc does is allocate bytes -- it does not construct objects.  Your sphere object has virtual functions, is derived from a base class, etc.  These types must be properly constructed, and malloc doesn't do the job.
In addition, if you have calls to free(), they must also be changed to call delete.
The only time to use malloc in terms of object construction is if you're using placement-new, which your code is not doing.


text:
Q: Getting a Mathematica image in Java I am attempting to use J/Link to get an image from Mathematica to Java.  I am able to print the image in Mathematica like this:
Print[ Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ]  ];

I've tried returning the data from the Mathematica function in various ways:
Return [ Image[Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ]] ];

Return [ Graphics[Raster[ img[[1]] ], AspectRatio->Automatic, ImageSize->530 ] ];

Return [ Raster[ note1[[1]] ] ];

Return [ note1[[1]] ];

My Java code:
ml.evaluate("tmp = renderImageGeneric[" + sampleId + ", noteText," + sizeX + "," + sizeY + ", margin," + dpi + "," + lineStep + "," + tabStep + "," + ligatureMatch + "," + maxLigHeightDiff + "," + mmSearch + "," + highToLowGap + "," + lowToHighGap + "," + wordBaselineVariance + "," + debugFlag + "]");

ml.discardAnswer();
byte[] res = ml.evaluateToImage("tmp", 0, 0);
ByteArrayInputStream strm = new ByteArrayInputStream(res);
BufferedImage imag = ImageIO.read(strm);
//BufferedImage imag = ImageIO.read(new InputStream(res));
if(imag != null) {
      ImageIO.write(imag, "png", new File("/Users/Rebecca/","test.png"));
}else {
      System.out.println("image is null");
}

When debugging, I get a large byte array in res.  The image does get saved, but it's blank (i.e. a white image).
If I return just a string ("blue"), an image with the string blue gets saved.
I'm assuming that I need to return something differently in renderImageGeneric, but I can't figure out what.
Thanks!

A: I wasn't able to get the return from the function correctly.  However, I changed course and had Mathematica output the image to a file.  I passed a path to the Mathematica function so that Java would know where it is.  Not the best solution but it does the trick.

A: Did you try somenthing like
     Return[ExportString[Graphics[Disk[], ImageSize -> 100], "PNG"]]


text:
Q: Memcached server service suddenly stops working We have a Memcached server service installed on Windows Server 2012 R2. Default settings are used. Sometimes the service stops working without any errors. Firewall and antivirus are disabled.
I wrote an utility that collects Memcached statistics every 30 mins, and the statistics looks fine: evictions and listen_disabled_num are always 0, curr_connections is around 30, accepting_conns is 1.
What can cause the Memcached service to stop?

A: The problem was in exceeding maximum item size. We used version 1.2.6 and this version din't want to work with objects greater than 1024 kB. After moving to version 1.4.5 the problem has gone. The newer version introduces -I command-line parameter, which allows to adjust maximum item size up to 128MB.


text:
Q: how to change player icon in xamarin forms Please i need some one to help me on how to change player icon into my player page in xamarin forms
This is my code:
PlayerPage.xaml
                              <StackLayout>
                                           <Button x:Name="btnpause"
                                                    WidthRequest="20"
                                                    HeightRequest="20"
                                                    HorizontalOptions="Center"
                                                    ImageSource="pause.png" />
                                           <Button x:Name="btnPlay"
                                                    WidthRequest="20"
                                                    HeightRequest="20"
                                                    HorizontalOptions="Center"
                                                    ImageSource="play.png" />
                                        <Switch x:Name="switchLoop" IsToggled="False" />
                            </StackLayout>

PlayerPage.xaml.cs
        ISimpleAudioPlayer player;
        public PlayerPage()
        {
            InitializeComponent();

            var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;

            player.Load("music.mp3");

            btnPlay.Clicked += BtnPlayClicked;
            switchLoop.Toggled += SwitchLoopToggled;
        }

        private void SwitchLoopToggled(object sender, ToggledEventArgs e)
        {
            Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Loop = switchLoop.IsToggled;
        }

        private void BtnPlayClicked(object sender, EventArgs e)
        {
            Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Play();
        }

Thank you.

A: Take a look at PlaybackEnded , it is raised when  audio playback completes successfully  .
You can control the button's visibility  in the event .
Code example
var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;
player.PlaybackEnded += (sender,e)=>
{
     btnPlay.IsVisible = true;
     btnpause.IsVisible = false;
};

A: I think you mean like this ,did not added the image .Use a ImageButton instead.
On start the button play and the loop switch , when the switch is True the sounds repeats it self. When start the pause button is showing push it the Play is showing again to resume. The  example project is on Github https://github.com/borisoprit/MusicStackOverflow
<StackLayout>
        <ImageButton
            x:Name="btnPlay"
            HeightRequest="50"
            HorizontalOptions="Center"
            Source="Play.png"
            VerticalOptions="Center"
            WidthRequest="50" />
        <ImageButton
            x:Name="btnPause"
            HeightRequest="50"
            HorizontalOptions="Center"
            Source="pause.png"
            VerticalOptions="Center"
            WidthRequest="50"
            IsVisible="false"/>
        <Label
            HorizontalOptions="Start"
            Text="Loop:"
            VerticalOptions="Center" />
        <Switch
            x:Name="switchLoop"
            HorizontalOptions="Start"
            IsToggled="False"
            VerticalOptions="Center" />
    </StackLayout>

PlayerPage.xaml.cs i also place the OnAppearing. This is the state of the btnpause Isvisible = false .Music ended the Play button is there and pause is hiding again.
 public HeadProjectAudioPage()
    {
        InitializeComponent();

        btnPause.IsVisible = false;

        var player = Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current;

        player.PlaybackEnded += (sender, e) =>
        {
            btnPlay.IsVisible = true;
            btnPause.IsVisible = false;
        };
        player.Load("running.mp3");

        btnPlay.Clicked += BtnPlayClicked;
        btnPause.Clicked += BtnPauseClicked;
        switchLoop.Toggled += SwitchLoopToggled;
    }
    protected override void OnAppearing()
    {
        base.OnAppearing();
        btnPause.IsVisible = false;
    }

    private void SwitchLoopToggled(object sender, ToggledEventArgs e)
    {
        Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Loop = switchLoop.IsToggled;
    }

    private void BtnPlayClicked(object sender, EventArgs e)
    {
        btnPause.IsVisible = true;

        btnPlay.IsVisible = false;
        Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Play();

    }
    private void BtnPauseClicked(object sender, EventArgs e)
    {
        btnPlay.IsVisible = true;
        btnPause.IsVisible = false;
        Plugin.SimpleAudioPlayer.CrossSimpleAudioPlayer.Current.Pause();
    }

}


text:
Q: Taking sum with filter condition in pyspark I'm doing some aggregation in pyspark dataframes.
I which I need to check PAYMNT_STATUS column and based on that I need to take the sum of different columns and need to assign in a new column.
also, I am taking count of distinct state and assigning it in a new column.
I am writing my pyspark query as below:
   result=df1.groupby(countrry,year).withColumn('Amt1',sf.when(sf.col('PAYMNT_STATUS')==='A1',
   sf.sum('Amt1_RS'))).withColumn("Amt2",sf.when(sf.col("PAYMNT_STATUS")==="B1",
   sf.sum("Amt2_RS"))).agg(sf.sum("amt3").alias("amt_rs"))
    .agg(countDistinct("state")).alias("state_count")

But getting a syntax error.
Can someone please guide me? How should I rewrite this code?
Equivalent SQL:
    SUM(DECODE(PAYMNT_STATUS, 'A1', NVL(Amt1_RS, 0))) AS Amt1,
        SUM(DECODE(PAYMNT_STATUS, 'B1', NVL(Amt2_RS, 0))) AS Amt2,
        SUM(ISNULL(amt3, 0)) AS amt_rs,
        COUNT(DISTINCTstate) as state_count

As of now I'm not considering this NVL and ISNULL part.

A: You can try something like this
String filteringCondition = "PAYMNT_STATUS==Al" (could be extended to many)
String filteringCondition2 = "PAYMNT_STATUS==Bl" (could be extended to many)

result=df1.groupby(countrry,year).withColumn('Amt1',sum(when(expr(filteringCondition),col('Amt1_RS')).otherwise(0))
.withColumn("Amt2", sum(when(expr(filteringCondition2), col("Amt2_RS")).otherwise(0))


text:
Q: What do I need to do to get cocoapods to build with C++? I'm trying to build a library to distribute via Cocoapods. The library is written mainly in Objective C, but includes a few C++ files. None of the C++ headers are part of the library's public API. The library builds fine in Xcode, and I can distribute as a framework, but a pod is probably easier for others to consume, right?
This is my first time attempting to build a cocoapod, so I may be doing something obviously wrong.
When I run pod lib lint or try to build the demo app that depends on the pod, I get error messages that suggest that the build system doesn't understand C++ at all.
in a C++ header file:
class CGuard {
> unknown type name 'class'; did you mean 'Class'?

in another C++ header file:
template<typename T>
class CContexts {
> unknown type name 'template'

My podspec file includes
spec.xcconfig = {
  'CLANG_CXX_LANGUAGE_STANDARD' => 'c++11',
  'CLANG_CXX_LIBRARY' => 'libc++'
}
spec.library = "c++"

What else can I do to tell the build system to use the C++ compiler?

A: It looks like the key was adding private_header_files entries to remove the C++ headers from the framework that Cocoapods exports.
Although Cocoapods is documented to only include the files from public_header_files in the generated module umbrella header, it looks like each subspec section has all of its headers included if that subspec section doesn't have its own public_header_files entry.
The C++ files were all compiled in a subspec section to let me use different compiler settings, so the private_header_files entry needed to be inside that subspec section as well.


text:
Q: record does not exist or has been deleted.\\n(record: account.move.line(5398,), user: 7) in odoo while updating I'm getting record does not exist or has been deleted.\n(record: account.move.line(5398,), user: 7) error while updating data to odoo. Following is my code can anyone help to solve this problem.
   import xmlrpc.client
   endpoint_url = "/api/account.move/"
   obj = get_object_or_404(OrderItem, order__id=order_id)
   invoice_date = obj.order.created_on
   name = obj.product.varient_name
   price = obj.total
   quantity = obj.quantity
   payment_source =  obj.order.payment_method
   payment_reference = obj.order.order_number
   common = xmlrpc.client.ServerProxy('{}/xmlrpc/2/common'.format(url))
   uid = common.authenticate(db, username, password, {})
   models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(url))
   ids = models.execute_kw(db, uid, password, 'account.move', 'search_read', [[['source_document', '=', payment_reference]]], {'fields': ['partner_id', 'id']})
   invoice_id = ids[0]['id']
   partner_id_ = ids[0]['partner_id'][0]
   headers = {
            "access-token":tokens,
            "Content-type":"application/jsonp",
            "Cookie":session_id
      }
   api_invoice_line_id = [(1, invoice_id,{'name':name, 'price_unit':price, 'quantity':quantity})]
   data = {
      "partner_id":partner_id_,
      "invoice_date":str(invoice_date),
      "move_type":"out_invoice",
      "__api__invoice_line_ids":str(api_invoice_line_id),
      "payment_source":payment_source,
      "source_document": payment_reference,
      "rider":rider_name,
       "ref":""
   }
   datas_ = json.dumps(data, indent=4)
   req = requests.put(url+endpoint_url+str(invoice_id), headers=headers, data=datas_)
   if req.status_code == 200:
      status = "Update Successful"
   else:
      status = str(req.text)
   return status

A: It looks like your code is failing because of the tuple you give to insert/update data in __api__invoice_line_ids.
I suppose it's some account.move.line Many2many or One2many field.
I see you are using the command 1 with invoice_id (an account.move id) and some data in a dict.
The problem here is that you are then trying to add that in the field pointing to account.move.line. So your ID 5398 is the account.move id, not an account.move.line id.
Not sure what your goal is to achieve here. If it's to push/update some account.move records with new data, change your __api__invoice_line_ids to point to account.move.
If your goal is to push/update some account.move.line records, then you better loop on the line_ids of your invoice_id :)
If I wasn't clear on something or you have any other question don't hesitate asking !


text:
Q: Two curves for orthogonal trajectory of $y=mx$
Find the orthogonal trajectory of $y=mx$.

We know,
$$\frac{dy}{dx} = m$$
For the orthogonal trajectory,
$$-\frac{dx}{dy} = m$$
Integrating both sides we get,
$$y=-\frac{x}{m}$$
But then if I substitute $m$ and then integrate, I get a totally different curve.
$$x^2+y^2=c$$
Are both curves considered to be orthogonal curves to our original equation? I have seen books which give only the second curve as the answer. But is not the first curve orthogonal too? If not, where am I going wrong?
Any help would be appreciated.


text:
Q: How to display object from json in js I have json code
{
    "dezui": {
        "title": "DezUI CSS Framework",
        "description": "",
        "organizer": [""],
        "status": true,
        "homepage": "",
        "link": [""],
        "date": [18, 10, 2021],
        ...
    },
    ...
}

I want to display with loop in my page. Previous json code:
{
    "portfolio": [
        {
            "title": "DezUI CSS Framework",
            "description": "",
            "organizer": [""],
            "status": true,
            "homepage": "",
            ...
        },
        ...
    ]
}

With the previous code, I display the data with the code below:

fetch("/portfolio/portfolio.json")
.then(response => {return response.json()})
.then(data => {
    for (let i = 0; i < data.portfolio.length; i++) {
        if (data.portfolio[i].status == true) {
            document.getElementById("portfolio").innerHTML += `

${data.portfolio[i].tag}

${data.portfolio[i].title}

`
        }
    }
})

I'm confused how I display in the form of an object(?)
Please help me

A: Since your data shape changed you'll need to update your code. You no longer need to loop through it as there is only one entry. So you can reference that object and change it from portfolio to dezui. ex:
fetch("/portfolio/portfolio.json")
    .then(response => {return response.json()})
    .then(data => {
        if (data.dezui.status == true) {
            document.getElementById("portfolio").innerHTML += `

${data.dezui.tag}

${data.dezui.title}

`
    }
})


text:
Q: GitHub, how to get all repository permission setting? Right now, I'm working on my customer repository, I don't have permission to look into the project setting, and we work remotely.
One way to figure it out is to ask a customer to screen capture the permission page. But will I have to do this all the time?
I wondered if GitHub already has some API to get all of the permission already.