text:
Q: postfix mail receive: how to wait for DNS caching? Postfix server is working with local Bind DNS configured as:

*

*a recursive DNS

*a caching DNS

Postfix is configured to check incoming client reverse hostname. The problem is that when a new hostname is not into DNS cache, the postfix log an error:
450 4.7.1 Client host rejected: cannot find your reverse hostname

Consequently this add a delay on mail reception, due to waiting for a new attempt from the client SMTP server.
My question: Is there a specific postfix parameter in order to wait more longer for DNS response? Is there another solution?


text:
Q: Efficiently ploting a table in csv format using Python I am trying to plot a csv formatted table using Python. So far, I was able to get the result I wanted by reading similar questions on the site, but my solution doesn't seem too "pythonic", nor did I found a very straightforward way of doing this. I am sure there is a more efficient way for plotting a table, so I'm asking this question to learn more about Python and let others have a straight answer for the same problem. Here it goes:
I have a table with data, which have headers and a first column. In my case, it is months and years respectively. i.e.:

Year,JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DIC
  1998,,0.78,0.60,0.50,0.50,,,,,0.62,,0.45
  1999,0.40,0.30,0.28,0.22,0.26,0.50,0.52,0.76,0.89,0.85,0.74,0.67
  2000,0.58,0.58,0.51,0.47,0.63,0.92,1.00,1.00,0.99,1.00,0.96,0.91
  2001,0.86,0.83,0.80,0.71,0.83,0.98,1.05,1.11,1.09,0.99,0.87,0.80
  ...

As you can see, there is missing data too.
My solution was the following:
import numpy as np
from matplotlib import pyplot as plt

#Import Data
Data=np.genfromtxt('LakeLevels.csv',delimiter=',',names=True,dtype=float)

#Extract data
Months=list(Data.dtype.names[1:])
Years=Data['Year']
Level=Data.view(dtype=float).reshape(Data.shape + (-1,))[:,1:]
Level_masked= np.ma.array (Level, mask=np.isnan(Level))

#Plot
fig=plt.pcolor(np.linspace(1,12,12),Years,Level_masked)
plt.colorbar()
plt.xticks(range(12),Months,rotation=45)

I found the solution was too complex for a very simple task. Is there a better way of achieving the same result or parts of the code I can improve? Maybe even a function that does this automatically.
Thanks in advance.

A: You might consider using Pandas for this munging + plotting of data.
I didn't follow through your logic all the way (i.e., the mask), but here is the output of the following two lines (on part of your data):
import pandas as pd

df = pd.read_csv('stuff.csv', delimiter=',', index_col='year').T.plot();

The more stuff you have (e.g., handling missing data, etc.) - the longer the difference in lines of code will become. Numpy is great, but you should probably use higher-level libraries (built over it!) - for this sort of stuff.

A: I will post my final solution based on @Ami Tavory's answer.
import pandas as pd
import seaborn as sns

df = pd.read_csv('LakeLevels.csv', delimiter=',', index_col='Year')
sns.heatmap(df)

So by using these 2 packages (i.e. pandas and seaborn) I was able to get my desired result in 2 lines!
Best regards.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where do the "fn" and "col" arguments to the Glue column specifications to name columns in dplyr (using `across` and `where` come from? I was going through the vignette (https://cran.r-project.org/web/packages/dplyr/vignettes/colwise.html) for column-wise options in dplyr and I came across this: (copied verbatim from the vignette)

Control how the names are created with the .names argument which takes a glue spec:
starwars %>% summarise(across(where(is.numeric), min_max, .names = "{fn}.{col}"))
#> # A tibble: 1 x 6
#>   min.height max.height min.mass max.mass min.birth_year max.birth_year
#>        <int>      <int>    <dbl>    <dbl>          <dbl>          <dbl>
#> 1         66        264       15     1358              8            896

My question is: where did the variables fn and col come from? I don't see anything about that on the main Glue vignette.  The corresponding arguments to across are .fns and .cols so I don't see the exact correspondence. This seems like too obscure an issue for me to be going on a wild goose chase through the documentation so I was hoping that someone could point me in the right direction.

A: From the online help for across:
.names
A glue specification that describes how to name the output columns. This can use {col} to stand for the selected column name, and {fn} to stand for the name of the function being applied. The default (NULL) is equivalent to {col} for the single function case and {col}_{fn} for the case where a list is used for .fns.


text:
Q: Select TWO rows from table based on ONE row from another table This is the query I have:
$query = "SELECT t1.one_field,t2.another_field FROM table_one t1,
table_two t2 WHERE t2.flag = 2 AND (t1.id = t2.id1 OR t1.id = t2.id2)
AND (t2.id1 = '$comparison' OR t2.id2 = '$comparison') LIMIT 1";

I tried with GROUP BY, DISTINCT, UNIQUE (...) but could never extract what I wanted... I always extract another_field and ONE one_field instead of TWO one_field... what is the best way to accomplish this? Tyvm...
Table 1
one_field | id
example1 | id_example1
example2 | id_example2

Table 2
another_field | flag | id1 | id2
need_to_get | 2 | id_example1 | id_example2

What I want to get
example1, example2, need_to_get (don't care if result is array or associative)

What I get
example2, need_to_get (expected, since one of the results gets overridden since it has the same field_name...)


text:
Q: Strange behavior when adding values to pointers Well, I actually don't know how I should describe this:
uintptr_t * ptr = (uintptr_t *) 0x21CC9004;

std::cout << ptr + 0x10 << std::endl;
std::cout << std::hex << 0x21CC9004 + 0x10 << std::endl;

The first line yields 21CC9044 and the second line yields 21CC9014.
How is that? Can someone explain this and how I can add 0x10 to my pointer to get the result from the second line?

A: In the first case the pointer arithmetic is used. It means that adding 0x10 actually adds 0x10 * sizeof( unsigned int ) to the value of the pointer that is equal to 0x40 provided that sizeof( unsigned int ) = 4.
In the second case there is the usual arithmetic of integer numbers.


text:
Q: DetailView template not displaying it's data within an app I have two models, named Course and Step. Every Step belongs to a Course and each Course has many steps. However, I'm having problem creating a detailview for Steps. For example when i go to the url 'http://127.0.0.1:8000/courses/1' it should display steps for course.objects.get(pk=1). However what i get back is just the page for course, i.e, http://127.0.0.1:8000/courses'.
Model
from django.db import models

# Create your models here.
class Course(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.CharField(max_length= 255)
    description = models.TextField()

    def __str__(self):
        return self.title

class Step(models.Model):
    title = models.CharField(max_length = 255)
    description = models.TextField()
    order = models.IntegerField()
    course = models.ForeignKey(Course)

    def __str__(self):
        return self.title

Url
from django.conf.urls import url
from . import views

urlpatterns = [
    url(r'^$', views.course_list),
    url(r'(?P<pk>\d+)/$', views.course_detail)
]

View
from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
from .models import Course, Step

def course_list(request):
    courses = Course.objects.all()
    return render(request, 'courses/course_list.html', {'courses': courses})

def course_detail(request, pk):
    course = Course.objects.get(pk=pk)
    return render(request, 'courses/course_detail.html', {'course': course})

course_detail.html
{% extends 'layout.html' %}
{% block title %}{{course.title}}{% endblock %}
{% block content %}

{{ course.title }} %

    {{course.description}}

        {% for step in course.step_set.all %}

{{ step.title }}

        {{step.description}}
        {% endfor %}

{% endblock %}

Main Urls
from django.conf.urls import url, include
from django.contrib import admin
from courses.views import course_list
from django.conf import settings
from django.conf.urls.static import static
from . import views

urlpatterns = [
    url(r'^courses/', course_list),
    url(r'^admin/', admin.site.urls),
    url(r'^$', views.hello_world),
]
if settings.DEBUG:
    urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

I just can't seem to recognize where i went wrong

A: I think the you need these url mappings..! This should do the trick.
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^applicationName/$', views.ListView.as_view(), name='courses'),
    url(r'^applicationName/(?P<pk>\d+)$', views.CourseDetailView.as_view(), name='course-detail'),
]

A: The problem is in your main urls.py file - this line makes any URL path starting with 'courses/' resolve to the course_list view:
url(r'^courses/', course_list),

So Django will never reach the course_detail view. Instead, you must "include" the application-specific URLs:
url(r'^courses/', include('myproject.myapp.urls'),

Where myproject is your main project name, and myapp is your app name (make sure you also registered your application under INSTALLED_APPS at your settings.py file).


text:
Q: How to get apache to do a virtual host on all IPs except a few I  have around 130 IPs on my linux server. 125 IPs point to one site, and 5 of them point to another. I would like to make just two virtualhost definitions.
Currently I am doing a wildcard at the top, and then separate Vhosts for each of the 5 IPs..The problem that I run into is sometimes it will trigger to pickup the wildcard (*) vhost when it can't find anything on the other 5.

A: You should be able to define a default virtual host for the 125 IP pointing to the one site as follows
<VirtualHost _default_:80>
...
</VirtualHost>

and then one virtual host for every one of the 5 'special' IPs.

A: I don't think there will be any pretty or elegant way to do this with all those IP's but it looks like this may be your best bet: http://httpd.apache.org/docs/2.0/vhosts/examples.html#intraextra
It looks like you can space separate IP in the VirtualHost declaration
<VirtualHost 192.168.1.1:80 172.20.30.40:80 3.other.IPs>
    DocumentRoot /www/example1
    ServerName www.example1.org
</VirtualHost>

Then just use the default setup to take in the other 125 ips
<VirtualHost _default_:80>
    DocumentRoot /www/example2
    ServerName www.example2.org
</VirtualHost>

Hope this helps!

A: You could write scripts to generate per-ip vhost.


text:
Q: Magento php core. Editing Product List Catalog I've got a quick questions for magento experts. I would like to make changes on the PHP core of magento.
I want to add details on product listings, the details will depends on each product, and I want to display the extra details on the catalog list, so it involves the database & PHP.
So my questions is - where can do this? I am not familiar with the magento file structure and I need this rush, I hope I'll have time to study its structure but it will probably take more time than my deadline.
Take note that I am talking about the admin product list, not the customer carting.

A: You can probably do all of that logic in /template/catalog/product/view.phtml, if is the detail page. If its the category page it would be /template/catalog/product/list.phtml.  Either way it would be the same.
$categories = $product->getCategoryIds();  //this is array of category ids the product exists in

$blueCategoryIds = array(1,2,3,4);
$redCategoryIds = array(5,6,7,8);

if(in_array($blueCategoryIds,$categories)){
    $newClass = 'blue-background';
} elseif (in_array($redCategoryIds,$categories)) {
    $newClass = 'red-background';
} else {
    $newClass='';
}

Define .blue-background and .red-background in a CSS file.
.red-background {background:red;}
.blue-background {background:blue;}

Then use $newClass in what ever html element you want to apply your background to. This probably should be part of a custom module a method, but this should you going quick.


text:
Q: How do I expand a macro in CLion, using the keyboard or menus? How do I expand a macro with CLion other than via the hover window? There doesn't seem to be such an action in the context menu, nor in the Code or Refactor menus. I'm looking for a keyboard-based method (with menu use counting as keyboard-based).
When I search for actions with the word "macro", I get CLion macros, CMake macros, but not C/C++ Preprocessor macros, so no help there.

A: As @uta notes, one can expand macros in CLion - but the action name is different than what you might used to. It's called an "inlining" of a macro, and it's in the Inline... submenu - both in the right-click menu on your macro, and in the Refactor top-level menu.
However, it seems that CLion is rather picky about expanding macros it doesn't believe are part of the project, so expect some more hitches.


text:
Q: Insert Blob Data into Sqlite3 (GeoPackage) I having issues writing WKB or Well Known Binary into a sqlite database/geopackage (they are the same type of database).
Here is the create statement to generate a polyline dataset.
CREATE TABLE line
(OBJECTID INTEGER primary key autoincrement not null,
Shape MULTILINESTRING)

The WKB is as follows:
bytearray(b'\x01\x05\x00\x00\x00\x02\x00\x00\x00\x01\x02\x00\x00\x00\x04\x00\x00\x00\x96C\x8b\x9a\xd0@`\xc18\xd6\xc5=\xd2\xc5RA\x93\xa9\x825\x02=`\xc1\xb0Y\xf5\xd1\xed\xa6RAZd;W\x913`\xc1 Zd\xfb\x1c\xc0RA\xaa\x82Q%p/`\xc18\xcd;\x92\x19\xaeRA\x01\x02\x00\x00\x00\x03\x00\x00\x00z\xc7)TzD`\xc1\xb8\x8d\x06\xb8S\x9fRA\xbb\xb8\x8d:{"`\xc1X\xec/\xb7\xbb\x9eRA\x00\x91~Eo"`\xc1\x00\xb3{F\xff]RA')

When I go to insert the binary data into the column, I do not get an error, it just inserts NULL.

sql = """INSERT INTO line (Shape)
                 VALUES(?)"""
val = [binaryfromabove]
cur.execute(sql, val)

I've also tried using sqlite3.Binary() as well:
sql = """INSERT INTO line (Shape)
                 VALUES(?)"""
val = [sqlite3.Binary(binaryfromabove)]
cur.execute(sql, val)

The row that is insert is always NULL.
Any ideas what is going on?


text:
Q: xpages default value for combobox I found this : Xpages Date Time Picker field defaults to today's date
I tried adding return null as default value for my combobox, but it still returns the first item from the list.
I also tried adding a formula item: @Text(""), but even if the default value is blank, it appears also as an item for the combobox.
Please help, thanks for your time.

A: One thing I do often for defaults..  and I forget if I do this for Comboboxes or not.  But I'll bind the control to a viewScope variable.  Then in beforePageLoad I'll set that viewScope variable to "" basically.  I find this works better then the "default" option on the pretty properties pain.  Maybe you want to give that a try.
In THEORY if that works then it will be blank to begin with.. but once it's changed you might probably can't put it BACK to blank.  In order to to that you'd need to have a blank option at the top of your values list.

A: I am sure that there is a better way to do this, but....
I always use a normal item ojbect with one single space written in as the label and value.  Under that I put my calculated values.  Then for the default value, I put " ".  It might not be pretty, but it gets the job done.  When I read the value, before asking if it is empty, I just use @Trim() to make sure that it is indeed a real value.
Of course you could make the label a single white character space with a value "empty" and then use "empty" as your default value.  The label would then be a single white space character.


text:
Q: C assign array index to another This probably has to do with C pointers cause it's an array problem.
Is it possible to assign an index of one array to another:
int main()
{
    char a[10];
    char b[3] = {'a', 'b', 'c'};
    int num = 1;
    a[1 + num] = b[0];

    int i = 0;
    for(i; i < 3; i++)
    printf("%s", a[i]);

    return 0;
}

I think the output should be what a would be. which i think would be [(null), (null), a]
EDIT
say I add an int array c to the code above:
int c[3] = {1, 2, 3};

I am having trouble with storing values in the array a when I try to do something like this:
a[1 + c[0]] = b[0];

this ended up working as well...
it turns out this was not my issue thanks for the help though

A: You can assign like this. In this There may be a junk characters can available in
the array. So First you assign 0 to all.
char a[10]={0};

Then assign the value to index which you need.
After that while printing that use the %c in printf.
for(; i < 3; i++)
printf("%c", a[i]);

You can get the value which you assigned.


text:
Q: How do you find criteria of this linear transformation $T(x,y,z)$? .
Question
Let $T \in L(\mathbb{R}^3,P_{2})$ such that:
$$T(1,0,0)=3x^2+x+2$$
$$T(0,1,0)=-x+1$$
$$T(0,0,1)=1$$
Determine criteria of T.
I tried the following:
For $(x,y,z)\in \mathbb{R}^3$ so,
$T(x,y,z)=T(x(1,0,0)+y(0,1,0)+z(0,0,1))=3x^2+x+2-x+1+1$
Is it correct?.
Context: Linear Algebra.
What do I need to complete the requested in the question?. Suggestions?.Thanks in advance.

A: Your idea is good, check this:
\begin{align}
T(u,v,w) &= uT(1,0,0) + vT(0,1,0) + wT(0,0,1) \\
&= u(3x^2+x+2) + v(-x+1) + w1 \\
&= (3u)x^2 + (u-v)x + (u+v+w).
\end{align}
Don't confuse the symbols, $u,v$ and $w$ are real numbers, whereas $3x^2+x+2,-x+1$ and $1$ are polynomials.


text:
Q: XCTest Fresh install app in a UITest As of Xcode 9 there is a new launch argument -StartFromCleanState that I assume launches the app after a clean install.  However it doesn't seem to work and googling -StartFromCleanState doesn't yield any results so no documentation to go off of.
source
My goal is to launch my app using a deeplink. The flow of my test is like so:

*

*The UITest begins by launching the app

*UITest opens safari

*UITest enters the webpage that has the deeplink link

*UITest clicks the link and the App opens up

Step for opens the app by bringing it from background state to foreground state.  which means application:didFinishLaunchingWithOptions: only gets called once on step 1.
func test_deeplink() {
    programmaticallyTapDeepLink()
    XCUIApplication().launchArguments = ["-StartFromCleanState", "YES"]
}

Ideally I would like to test the deeplink when the app is fresh/clean installed.
I have tried setting the launch arguments before/after I Programmatically tap the deeplink but it doesn't seem to work the way I would like it to.
Are there any solutions available for this?

A: In the document you specify as the source, the writer provides sample code:
XCTContext.runActivity(named: "Given I have launched app in clean state") { _ in {
    XCUIApplication().launch()
    XCUIApplication().launchArguments = ["-StartFromCleanState", "YES"]
}}

-StartFromCleanState is not a "new launch argument". It's a key and a value being provided to the XCUIApplication().launchArguments method, and it's up to the developer of the application under test (the XCUIApplication) to process the passed launch arguments (["-StartFromCleanState", "YES"]).
This stack overflow answer has some examples:

*

*How to access launchEnvironment and launchArguments set in XCUIApplication, running UI tests in XCode?
You might also want to consider reading up on userDefaults; you might want to trigger a reset on them based on the passed launchArguments in one of these two lifecyle methods:
Launch time:
application(_:willFinishLaunchingWithOptions:)
application(_:didFinishLaunchingWithOptions:)

See this apple doc for more info on the Application life cycle states and delegate methods available to you during each state:

*

*https://developer.apple.com/documentation/uikit/uiapplicationdelegate


text:
Q: Why might a 413 not be flushed to the client immediately? I have my local development server returning status 413 for oversized file uploads and the client is receiving these immediately - as I require.
My remote server is the same version of Nginx and more-or-less the same configuration, but the  413 never reaches the browser.
An error indicating the data is oversized appears in the error log straight away and nothing appears in the access log. The browser continues to send the data and after 30 seconds the 413 status appears in the access log (and again in the error log) and the browser times out with an internal 'connection reset' error.
What configurations on the remote server could cause this delay?

A: The problem is that most HTTP clients don't read the response until they've sent the entire request body. If you're dealing with webbrowsers you're probably out of luck here. The only server side configuration you can do is set keepalive_requests to 0 (which disables persistent connections), which might make nginx close the connection after sending the 413 which should cause the client to stop sending the data. The client is likely to report a network error instead of 413 however.

A: I guess browser must still finish the upload and only then recieve 413 error. The best way to check file size is to check it in JS before hitting the upload button.


text:
Q: Compare User Imputed Data to Pivot Table I am attempting to use an "IF" function to compare a data value from an inventory list in a pivot table with a user editable cell next to the pivot(for a physical inventory count).
=IF(GETPIVOTDATA("CurrentInventoryQuantity",B8)=G8,TRUE,FALSE)

This code returns an #REF! error.
I have to store the inventory data in a pivot so that it can dynamically add new rows as needed.
Any tips on how to get Excel to compare the data?

A: Try using just the cell reference instead of GetPivotData.


text:
Q: Flutter - RevenueCat - There was a credentials issue, Check the underlying error for more details, error is coming after purchase I am integrating in app purchase in my flutter application through RevenueCat and to support both Android and IOS. I have followed all the steps mentioned in the documentation for configuration (https://docs.revenuecat.com/docs/creating-play-service-credentials), added subscription details, created entitlements, offerings, products in revenue cat dashboard.
In code initiated the revenue cat platform in main.dart, fetching the offerings and getting correct data, initiated purchase and it is showing payment successful but as soon as it comes back to application it is showing the error (attaching the log below) :
D/[Purchases] - DEBUG(28086): ℹ SDK Version - 4.0.5
D/[Purchases] - DEBUG(28086):  Initial App User ID - null
D/[Purchases] - DEBUG(28086):  Identifying App User ID: $RCAnonymousID:1990da266b524c10a34f3118b99cef30
D/[Purchases] - DEBUG(28086): ℹ Deleting old synced subscriber attributes that don't belong to $RCAnonymousID:1990da266b524c10a34f3118b99cef30
D/[Purchases] - DEBUG(28086): ℹ App foregrounded
D/[Purchases] - DEBUG(28086): ℹ PurchaserInfo cache is stale, updating from network in foreground.
D/[Purchases] - DEBUG(28086): ℹ Offerings cache is stale, updating from network in foreground
D/[Purchases] - DEBUG(28086):  Offerings updated from network.
D/[Purchases] - DEBUG(28086): ℹ Skipping updating pending purchase queue since BillingClient is not connected yet.
D/[Purchases] - DEBUG(28086): ℹ No subscriber attributes to synchronize.
D/[Purchases] - DEBUG(28086): ℹ Listener set
D/[Purchases] - DEBUG(28086): ℹ Sending latest PurchaserInfo to listener.
D/[Purchases] - DEBUG(28086): ℹ Starting connection for com.android.billingclient.api.BillingClientImpl@a7f65c2
D/[Purchases] - DEBUG(28086): ℹ Ending connection for com.android.billingclient.api.BillingClientImpl@d4289d5
D/[Purchases] - DEBUG(28086): ℹ Billing Service Setup finished for com.android.billingclient.api.BillingClientImpl@a7f65c2
D/[Purchases] - DEBUG(28086): ℹ Updating pending purchase queue
D/[Purchases] - DEBUG(28086): ℹ API request started: GET /subscribers/%24RCAnonymousID%3A1990da266b524c10a34f3118b99cef30
D/[Purchases] - DEBUG(28086): ℹ API request completed with status: GET /subscribers/%24RCAnonymousID%3A1990da266b524c10a34f3118b99cef30 200
D/[Purchases] - DEBUG(28086): ℹ PurchaserInfo updated, sending to listener.
D/[Purchases] - DEBUG(28086): ℹ API request started: GET /subscribers/%24RCAnonymousID%3A1990da266b524c10a34f3118b99cef30/offerings
D/[Purchases] - DEBUG(28086): ℹ API request completed with status: GET /subscribers/%24RCAnonymousID%3A1990da266b524c10a34f3118b99cef30/offerings 200
D/[Purchases] - DEBUG(28086): ℹ Requesting products from the store with identifiers: labh_premium
D/[Purchases] - DEBUG(28086): ℹ Querying subs
D/[Purchases] - DEBUG(28086): ℹ Querying inapp
D/[Purchases] - DEBUG(28086): ℹ Cleaning previously sent tokens
D/[Purchases] - DEBUG(28086): ℹ Tokens already posted: []
D/[Purchases] - DEBUG(28086): ℹ Saving tokens []
D/[Purchases] - DEBUG(28086): ℹ Tokens already posted: []
D/[Purchases] - DEBUG(28086): ℹ Products request finished for labh_premium
D/[Purchases] - DEBUG(28086):  Retrieved skuDetailsList: SkuDetails: {"productId":"labh_premium","type":"subs","price":"₹329.87","price_amount_micros":329870000,"price_currency_code":"INR","title":"Labh Premium (Labh)","description":"To get unlimited product additions, notifications and all features access","subscriptionPeriod":"P1M","freeTrialPeriod":"P12W6D","skuDetailsToken":"AEuhp4LH4Q6C1qQKx2QJ_dGdjtBeF_-zqyo1n6A9ZAt6YOi1tpbQ9n5RvEOUEyxm5bE="}
D/[Purchases] - DEBUG(28086):  labh_premium - SkuDetails: {"productId":"labh_premium","type":"subs","price":"₹329.87","price_amount_micros":329870000,"price_currency_code":"INR","title":"Labh Premium (Labh)","description":"To get unlimited product additions, notifications and all features access","subscriptionPeriod":"P1M","freeTrialPeriod":"P12W6D","skuDetailsToken":"AEuhp4LH4Q6C1qQKx2QJ_dGdjtBeF_-zqyo1n6A9ZAt6YOi1tpbQ9n5RvEOUEyxm5bE="}
D/[Purchases] - DEBUG(28086): ℹ Vending PurchaserInfo from cache.
D/[Purchases] - DEBUG(28086): ℹ Checking if cache is stale AppInBackground false
D/[Purchases] - DEBUG(28086): ℹ Vending Offerings from cache
D/[Purchases] - DEBUG(28086): ℹ Checking if cache is stale AppInBackground false
D/[Purchases] - DEBUG(28086): ℹ Vending Offerings from cache
D/[Purchases] - DEBUG(28086):  Purchase started - product:  SkuDetails: {"productId":"labh_premium","type":"subs","price":"₹329.87","price_amount_micros":329870000,"price_currency_code":"INR","title":"Labh Premium (Labh)","description":"To get unlimited product additions, notifications and all features access","subscriptionPeriod":"P1M","freeTrialPeriod":"P12W6D","skuDetailsToken":"AEuhp4LH4Q6C1qQKx2QJ_dGdjtBeF_-zqyo1n6A9ZAt6YOi1tpbQ9n5RvEOUEyxm5bE="}  - offering: Default
D/[Purchases] - DEBUG(28086):  Purchasing product: labh_premium
D/[Purchases] - DEBUG(28086): ℹ Checking if cache is stale AppInBackground false
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
D/ViewRootImpl(28086): support adaptive color gamut feature!
V/ViewRootImpl(28086): The specified message queue synchronization  barrier token has not been posted or has already been removed
D/ViewRootImpl[MainActivity](28086): windowFocusChanged hasFocus=false inTouchMode=true
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
D/DecorView(28086): onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@a52f5b8[ProxyBillingActivity]
D/ViewRootImpl[ProxyBillingActivity](28086): windowFocusChanged hasFocus=true inTouchMode=true
D/ViewRootImpl[ProxyBillingActivity](28086): windowFocusChanged hasFocus=false inTouchMode=true
W/BillingHelper(28086): Couldn't find purchase lists, trying to find single data.
D/[Purchases] - DEBUG(28086): ℹ BillingWrapper purchases updated: labh_premium GPA.3376-1240-3145-24419 incnbbphcdfjpldpihckgkkn.AO-J1Ozpf81-Sw2aVSSj45AWwZc_-GEoB3UGeyZ2uuXWy34eXFHnBy-O-xrPywEeNuTS7cJz_z1Z2IDjL0E5IOPGCPb6dnSOay5WBpePNJXitLoC29yNFyk
D/[Purchases] - DEBUG(28086): ℹ Requesting products from the store with identifiers: labh_premium
D/DecorView(28086): onWindowFocusChangedFromViewRoot hasFocus: true, DecorView@a4a7730[MainActivity]
D/ViewRootImpl[MainActivity](28086): windowFocusChanged hasFocus=true inTouchMode=true
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
D/[Purchases] - DEBUG(28086): ℹ Products request finished for labh_premium
D/[Purchases] - DEBUG(28086):  Retrieved skuDetailsList: SkuDetails: {"productId":"labh_premium","type":"subs","price":"₹329.87","price_amount_micros":329870000,"price_currency_code":"INR","title":"Labh Premium (Labh)","description":"To get unlimited product additions, notifications and all features access","subscriptionPeriod":"P1M","freeTrialPeriod":"P12W6D","skuDetailsToken":"AEuhp4LH4Q6C1qQKx2QJ_dGdjtBeF_-zqyo1n6A9ZAt6YOi1tpbQ9n5RvEOUEyxm5bE="}
D/[Purchases] - DEBUG(28086):  labh_premium - SkuDetails: {"productId":"labh_premium","type":"subs","price":"₹329.87","price_amount_micros":329870000,"price_currency_code":"INR","title":"Labh Premium (Labh)","description":"To get unlimited product additions, notifications and all features access","subscriptionPeriod":"P1M","freeTrialPeriod":"P12W6D","skuDetailsToken":"AEuhp4LH4Q6C1qQKx2QJ_dGdjtBeF_-zqyo1n6A9ZAt6YOi1tpbQ9n5RvEOUEyxm5bE="}
D/[Purchases] - DEBUG(28086): ℹ Found 0 unsynced attributes for App User ID: $RCAnonymousID:1990da266b524c10a34f3118b99cef30
E/sqlite3_android(28086): [IKR-38846] ONEPLUS_NAME_PARTS_MATCH SQLITE_OK
D/[Purchases] - DEBUG(28086): ℹ API request started: POST /receipts
D/[Purchases] - DEBUG(28086): ℹ API request completed with status: POST /receipts 503
E/[Purchases] - ERROR(28086): ‼ There was a credentials issue. Check the underlying error for more details.

And I am getting the 1st receipt in mail from google play store and after 5 minutes I get cancellation receipt and shows the reason "Purchase is not acknowledged".
Any kind of help will be appreciated. Thanks..

A:
E/[Purchases] - ERROR(28086): ‼ There was a credentials issue. Check the underlying error for more details.

The error is indicating that there's a problem with the Play Store credentials that you've uploaded to RevenueCat. Usually, this is due to the fact that it can take over a day for the credentials to propagate throughout Google - so if you recently set these up this is likely the cause.
Referencing documentation:

*

*Error Handline: https://docs.revenuecat.com/docs/errors#---invalid_credentials

*Play Store Credentials: https://docs.revenuecat.com/docs/creating-play-service-credentials

A: I recreated google credentials and linked the new one with revenuecat and after few hours it worked fine.

A: In my case, I just forgot to do the 'Send a test notification' step in (https://www.revenuecat.com/docs/creating-play-service-credentials), which tells me that I didn't link pub/sub to revenuecat.
Once I did it, and the notification was received, it worked like a charm.


text:
Q: Laravel Route::apiResource Post query didn't work properly I use laravel as an api but the problem is that when I want to store an item (Model : "Bataille"), i make a Post request on the route "api/batailles/" but laravel execute the index() function of my controller instead of the store() function... (all the others routes work)
This is my route :
Route::apiResource('batailles', 'BatailleController');

This is my route list :
    +--------+-----------+--------------------------+-------------------+-------------------------------------------------+------------+
| Domain | Method    | URI                      | Name              | Action                                          | Middleware |
+--------+-----------+--------------------------+-------------------+-------------------------------------------------+------------+
|        | GET|HEAD  | api/batailles            | batailles.index   | App\Http\Controllers\BatailleController@index   | api        |
|        | POST      | api/batailles            | batailles.store   | App\Http\Controllers\BatailleController@store   | api        |
|        | GET|HEAD  | api/batailles/{bataille} | batailles.show    | App\Http\Controllers\BatailleController@show    | api        |
|        | PUT|PATCH | api/batailles/{bataille} | batailles.update  | App\Http\Controllers\BatailleController@update  | api        |
|        | DELETE    | api/batailles/{bataille} | batailles.destroy | App\Http\Controllers\BatailleController@destroy | api        |
|        | GET|HEAD  | api/lieus                | lieus.index       | App\Http\Controllers\LieuxController@index      | api        |
|        | POST      | api/lieus                | lieus.store       | App\Http\Controllers\LieuxController@store      | api        |
|        | GET|HEAD  | api/lieus/{lieu}         | lieus.show        | App\Http\Controllers\LieuxController@show       | api        |
|        | PUT|PATCH | api/lieus/{lieu}         | lieus.update      | App\Http\Controllers\LieuxController@update     | api        |
|        | DELETE    | api/lieus/{lieu}         | lieus.destroy     | App\Http\Controllers\LieuxController@destroy    | api        |
+--------+-----------+--------------------------+-------------------+-------------------------------------------------+------------+

and finally this is my BatailleController :
<?php

namespace App\Http\Controllers;

use App\Bataille;
use Illuminate\Http\Request;

class BatailleController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return string
     */
    public function index()
    {
        return Bataille::all()->toJson();

    }

    /**
     * Store a newly created resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @return false|string
     */
    public function store(Request $request)
    {
        $bataille = new Bataille([
            "nom"       =>$request->input("nom"),
            "date"      =>$request->input("date"),
            "lieus_id"  =>$request->input("lieus_id")
        ]);

        if($bataille->save()) {
            return json_encode([
                "method"=>"store",
                "status"=>"OK"
            ]);
        } else {
            return json_encode([
                "method"=>"store",
                "status"=>"FAILED"
            ]);
        }
    }

    /**
     * Display the specified resource.
     *
     * @param \App\Bataille $bataille
     * @return string
     */
    public function show(Bataille $bataille)
    {
        return Bataille::find($bataille->id)->toJSON();
    }

    /**
     * Update the specified resource in storage.
     *
     * @param \Illuminate\Http\Request $request
     * @param \App\Bataille $bataille
     * @return false|string
     */
    public function update(Request $request, Bataille $bataille)
    {
        $bataille1 = Bataille::find($bataille->id);

        if ($request->input("nom") != null) {
            $bataille1->nom = $request->input("nom");

        }

        if ($request->input("date") != null) {
            $bataille1->date = $request->input("date");
        }

        if ($request->input("lieus_id") != null) {
            $bataille1->lieus_id = $request->input("lieus_id");
        }

       if ($bataille1->save()) {
            return json_encode([
                "method" => "update",
                "status" => "OK"
            ]);
        } else {
            return json_encode([
                "method" => "update",
                "status" => "FAILED"
            ]);
        }
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param \App\Bataille $bataille
     * @return false|string
     */
    public function destroy(Bataille $bataille)
    {
        $batailled = Bataille::find($bataille->id);
        if($batailled->delete()) {
            return json_encode([
                "method"=>"destroy",
                "status"=>"OK"
            ]);
        } else {
            return json_encode([
                "method"=>"destroy",
                "status"=>"FAILED"
            ]);
        }
    }
}

How do I can resolve the problem ?

A: Ensure that your request set to POST method because the routes in resources has the same name but they are different in HTTP methods for example if you use jQuery Ajax set method to POST
$.ajax({
    method: "POST",
    url: window.location.origin + "/api/batailles",
    data: {
        name: "John",
        location: "Boston"
    }
})
.done(function(msg) {
    alert("Data Saved: " + msg);
});

A: Your route:list looks good. If you are hitting index() then you are not POSTing, you are GETing.  Check your ajax call.


text:
Q: Does find_by always return a match to the first of an array of conditions if possible? I want to find a Post model whose title is "foo", but, if the post doesn't exist, "bar" and then "foobar".
For that I wrote this:
Post.find_by(title: %w(foo bar foobar))

It seems to be working fine now, but I'm not sure if the find_by method always finds the first value in the array of strings first.
When there are posts whose titles are "foo" and "bar", does the code above always return the post with the title "foo"?

A: The order of alternatives doesn't matter. Per the documentation, find_by

Finds the first record matching the specified conditions. There is no implied ordering so if order matters, you should specify it yourself.

If you want the posts in a particular order, you'll have to either

*

*add an order clause to the query, e.g.
Post.order("case title when 'foo' then 0 when 'bar' then 1 when 'foobar' then 2 end").
find_by(title: %w(foo bar foobar))

Tested in MySQL; not sure about how widespread that syntax is but at least something similar should be available in any SQL database.
You might need to build the order clause dynamically. From ironsand's solution in the comments:
titles = %w(foo bar foobar)
order_sql = "case #{titles.map.with_index { |title, i| "when '#{title}' then #{i}" }.join ' ' } end"
Post.order(order_sql).find_by(title: titles)

*query all the posts and sort them afterwards
Post.all.sort_by { |post| %w(foo bar foobar).index post.title }.first

This will be slow for a large number of posts, so whether it's useful probably depends on whether you can start with something more specific than Post.all.

A: For this
Post.find_by(title: %w(foo bar foobar))

the sql query run as
SELECT  "posts".* FROM "posts" WHERE "posts"."title" IN ('foo', 'bar', 'foobar') LIMIT 1

the query contains a limit constraint, so you will get only one record eventhough the condition satisfies.
You should use where query to get all recors
Post.where(title: %w(foo bar foobar))


text:
Q: Why doesn't Graphics show up? I want to save all drawstring which is done with the codes at the bottom half. I am saving it by saving the "Points" in a List type. The purpose of saving is because I want to have the ability to delete a particular drawing. All other drawings will be retained and only the one which wants to be deleted will be removed. My main query is why can't I use the same code with some minor editing(Top half of the code is the code I use to add new drawstring) that I use to draw to redraw when I am deleting a particular drawing.
Side_pictureBox.ImageLocation = AppDomain.CurrentDomain.BaseDirectory + @"pictures for app\Bus_Nearside.png";
Side_pictureBox.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"\pictures for app\Bus_Nearside.png");
Bitmap bm = new Bitmap(Side_pictureBox.Image);
if (Tagged_Remarks_listBox.SelectedIndex == 0)
{
  for (int x = 0; x <= NumberingPosition.Count - 1; x++)
  {
    if (x != 0)
    {
      using (Graphics gr = Graphics.FromImage(bm))
      {
        gr.SmoothingMode = SmoothingMode.AntiAlias;
        Font drawFont = new Font("Calibri (Body)", 15);
        SolidBrush drawBrush = new SolidBrush(Color.Blue);
        //MessageBox.Show(Numbering[u] + NumberingPosition[u]);
        gr.DrawString(Numbering[x], drawFont, drawBrush, NumberingPosition[x]);
      }
    }
    Side_pictureBox.Image = bm;
    Side_pictureBox.Invalidate();
  }

//Above code is when I first drawstring ,Below Code is to redraw when deleting particular drawing//
Bitmap bm = new Bitmap(Side_pictureBox.Image);

                    using (Graphics gr = Graphics.FromImage(bm))
                    {
                        gr.SmoothingMode = SmoothingMode.AntiAlias;

                        String drawString = numbering_for_digram.ToString();
                        Font drawFont = new Font("Calibri (Body)", 15);
                        SolidBrush drawBrush = new SolidBrush(Color.Blue);

                        gr.DrawString(drawString, drawFont, drawBrush, lastPoint);
                        Numbering.Add(drawString);

                        drawFont.Dispose();
                        drawBrush.Dispose();
                    }

                    Side_pictureBox.Image = bm;

A: If we're in the Paint() event, then I'd expect to see something more like this:
if (Tagged_Remarks_listBox.SelectedIndex == 0)
{
    Graphics gr = e.Graphics;
    gr.SmoothingMode = SmoothingMode.AntiAlias;
    Font drawFont = new Font("Calibri (Body)", 15);
    SolidBrush drawBrush = new SolidBrush(Color.Blue);
    for (int x = 1; x <= NumberingPosition.Count - 1; x++)
    {
        //MessageBox.Show(Numbering[u] + NumberingPosition[u]);
        gr.DrawString(Numbering[x], drawFont, drawBrush, NumberingPosition[x]);
    }
    drawFont.Dispose();
    drawBrush.Dispose();
}

Note that calling Invalidate() in the Paint() would cause it to repaint itself REPEATEDLY and FOREVER...which might be part of the problem.

A: I found a way to make it work(Maybe not the best, most effective, efficient way), by using Bitmap to take in all the drawings. This bitmap will then be saved as a Png file. Once all drawings are done, I declare the picturebox.image as the bitmap's Png file.
private void Side_pictureBox_Paint(object sender, PaintEventArgs e)
{
    if (Tagged_Remarks_listBox.SelectedIndex == 0 && selectedindexreset == true)
    {
        //Side_pictureBox.ImageLocation = AppDomain.CurrentDomain.BaseDirectory + @"pictures for app\Bus_Nearside.png";
        Side_pictureBox.Image = Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + @"\pictures for app\Bus_Nearside.png");
        Bitmap bmforedit = new Bitmap(Side_pictureBox.Image);

        //MessageBox.Show("inside");

        using (Graphics gr = Graphics.FromImage(bmforedit))
        {
            for (int x = 0; x <= NumberingPosition.Count - 1; x++)
            {
                //MessageBox.Show(x.ToString());
                if (Numbering[x] != "1") // change accordingly
                {
                    //MessageBox.Show(Numbering[x]);
                    gr.SmoothingMode = SmoothingMode.AntiAlias;
                    Font drawFont = new Font("Calibri (Body)", 15);
                    SolidBrush drawBrush = new SolidBrush(Color.Blue);
                    //MessageBox.Show(Numbering[x] + NumberingPosition[x]);

                    gr.DrawString(Numbering[x], drawFont, drawBrush, NumberingPosition[x]);

                    drawFont.Dispose();
                    drawBrush.Dispose();
                }
            }
            // bmforedit.Save(@"C:\Users\user\Desktop\PDI_APP_EDIT_FOR_TO\PDIPROTOTYPE2\bin\Debug\pictures for app\TestImage.png");
            Side_pictureBox.Image.Dispose();
            //bmforedit.Save(@"C:\Users\user\Desktop\PDI_APP_EDIT_FOR_TO\PDIPROTOTYPE2\bin\Debug\pictures for app\TestImage1.png");
            Side_pictureBox.Image = bmforedit;
        }

        for (int u = 0; u <= PrevStore.Count - 1; u++)
        {
            using (Graphics g = Graphics.FromImage(bmforedit))
            {
                if (u < StartDrawCount[0] || u > StopDrawCount[0])
                {
                    g.DrawLine(new Pen(Color.DarkRed, 2), PrevStore[u], NowStore[u]);
                    g.SmoothingMode = SmoothingMode.AntiAlias;
                }
            }
        }

        bmforedit.Save(@"C:\Users\user\Desktop\PDI_APP_EDIT_FOR_TO\PDIPROTOTYPE2\bin\Debug\pictures for app\TestImage2.png");
        selectedindexreset = false;
        Side_pictureBox.ImageLocation = AppDomain.CurrentDomain.BaseDirectory + @"pictures for app\TestImage2.png";
        Side_pictureBox.Refresh();
    }
}


text:
Q: Pthreads. Implementation of cancellation points My question is related to this one pthread_cancel don't work under solaris
I have the same problem. I couldn't find printf implementation without write(write has cancellation point) call on the http://src.opensolaris.org (perhaps I didn't search enough)
I can't find information about cancellation points internals. How does asynchronous cancel work?(through signls or other way) How does defered cancel work?


text:
Q: Run a single cucumber scenario from an executable JAR I would like to package my acceptance tests into an executable JAR where all necessary libraries are included for running the tests and generating the reports. I would also like to either run all tests or a single test.
So far, I'm able to run all tests and although reports are being generated in the location I specified in serenity.properties, the index.html is NOT being generated.
Normally, I would run my tests using maven verify goal which would run the serenity-maven-plugin, but since I'm running from a JAR, I'm not sure how I can achieve the same thing.
I have a main class that looks as follows:
@RunWith(CucumberWithSerenity.class)
@CucumberOptions(features = "classpath:com/cfhayes/test/LookupADefinition.feature")
public class DefinitionTestSuite {
  public static void main(String[] args) throws Exception {
    JUnitCore.main("com.cfhayes.test.DefinitionTestSuite");
  }
}

And my feature file uses tags so that I can specify a single scenario to run:
Feature: Lookup a definition

  @TEST-0001
  Scenario: Looking up the definition of 'apple'
    Given the user is on the Wikionary home page
    When the user looks up the definition of the word 'apple'
    Then they should see the definition 'A common, round fruit produced by the tree Malus domestica, cultivated in temperate climates.'

  @TEST-0002
  Scenario: Looking up the definition of 'pear'
    Given the user is on the Wikionary home page
    When the user looks up the definition of the word 'pear'
    Then they should see the definition 'An edible fruit produced by the pear tree, similar to an apple but elongated towards the stem.'

I'm hoping there is a way I can use JVM args with the executable JAR that would somehow allow me to set the cucumber options. I tried doing something like this:
java -jar my-test-jar.jar -Dcucumber.options="--tags @TEST-0001"

...but that still runs ALL tests.
Any ideas would be greatly appreciated.

A: The way you construct the command might be incorrect. The cucumber options are taken as the arguments to com.cfhayes.test.DefinitionTestSuite::main rather than the java option. Try this:
java -Dcucumber.options="--tags @TEST-0001" -jar my-test-jar.jar

or handle the cucumber options in your class instead.

A: import io.cucumber.core.cli.Main;
public static void main(String args[]) throws Throwable {
try {
Main.main(new String[] {

"-g","com.sadakar.cucumber.common",
"-g","com.sadakar.cucumber.runner",

"classpath:features",

"-t","@SmokeTest",

"-p", "pretty",
"-p", "json:target/cucumber-reports/cucumber.json",
"-p", "html:target/cucumber-reports/cucumberreport.html",

"-m"
});} catch (Exception e) {
e.printStackTrace();
System.out.println("Main method exception : " + e);}}

The above code worked for me to execute the cucumber tests from runnable jar with test frame work as TestNG.
Executing jar: java -jar ProductsAutomation-0.0.1-SNAPSHOT-jar-with-dependencies.jar


text:
Q: MainActivity gets recreated multiple times while measuring certain SIM Data I recently started Android Development and am creating an app that measures certain SIM data, however when some data about the SIM changes mainActivity recreates itself each time certain data changes so I lose all the old data that I need to log and keep track of. How do i prevent mainActivity from recreating itself more than once?

A: Sounds like changing the sim causes a configuraiton change.  Add onConfigChange to your manifest and list... basically I'd put in everything, then you can pull stuff out until you find the minimal set.  I have no idea what config changes a sim might cause.


text:
Q: Python with statement: 'Syntax error: invalid syntax' I tried the following code:
with x as 1:
    y = 1
with z as 1:
    w = 1

The compiler reported a SyntaxError: invalid syntax. What is the problem?
[EDITED:] What I was trying to do is:
import tensorflow as tf
with tf.variable_scope("model"):
    y = 1
with tf.variable_scope("model2"):
    z = 1

I want to change the namescope in tensorflow for sharing variables. I looked at the online tutorial but that doesn't help much.

A: Oversimplifying slightly, your code:
with x as 1:
    y = 1

… translates to something like this:
try:
    1 = x.__enter__()
    y = 1
finally:
    1.__exit__()

Writing 1 = x.__enter__() is obviously going to raise a SyntaxError: can't assign to literal, because it doesn't mean anything to assign a new value to the literal constant 1.
Doing the same thing in a with statement raises the same exception. (In old versions of Python (I think just 2.5?), the error message wasn't quite as useful, and it just said SyntaxError: invalid syntax, but the problem is the same.)

Depending on what was in x, getting past the SyntaxError may well just raise a new exception, AttributeError: __enter__. Only context managers can be used in a with statement. Roughly, these are things that know how to clean up after themselves, and where it's important to get them to clean up at the end of some block of code no matter what. Files are the prototypical example: they call self.close() when you exit the block, which makes sure you don't get OS errors from having hundreds of open files lying around, or fail to flush the last write, or other such problems.
For more information on with, see PEP 343, the proposal that originally added with to Python 2.5, or Understanding Python's "with" statement (from effbot).

So, the question here is: what were you trying to do? If you just want to assign the value 1 to the name x, you already know how to do that, because you did it with y in the very next line: just x = 1. If you were trying to do something different… well, there probably is a way to do it, but with may well be nowhere near the right answer.

A: You misunderstand Python's with statement.  If you tell us what you want to do, we can help.
with context_obj as name:

creates a context (execution environment) with three characteristics:

*

*On entering the context, the object's __enter__ method (function) is called;

*The return value of that function is assigned to name;

*On leaving the context, the object's __exit__ method is called, regardless of how we leave the context.

Your attempt, with x as 1 fails on all characteristics.  x has no __enter__ or __exit__ method; there is no return value; you could not assign that return value to the constant 1.


text:
Q: Flattr API for Java? Is there an official (or otherwise well-maintained) Java library to use the Flattr API? Should work both server-side and on Android. For Android, is there a comfortable SSO-solution similar to what Facebook offers, where other apps can delegate authentication to the official app?

A: There's flattr4j, which is actively maintained (by myself) and works both on server-side and on Android.


text:
Q: Can I access javascripts from iframe parent on another domain I control both domains and could set whatever policies necessary. The domain in the iframe uses pretty much the same libraries and I was hoping to leech them off the parent if possible.
To be clear, I'm not asking how to make a cross-domain request. I'm asking how to get scripts from an iframe's parent, when the parent is on another domain.
I'm getting a permission error with this (trying jQuery here but same with my other libraries):
if (typeof(jQuery) == "undefined") {
  var iframebody = document.getElementsByTagName("body")[0];
  var jQuery = function (selector) { return parent.jQuery(selector, iframebody); };
  var $ = jQuery;
}
$("
Hello World
").appendTo("body");

This would work if they were on the same domain.
I know this is cross-domain and is blocked for security reasons, but considering I control both domains and neither are security sensitive, I could set any policies as lax as I want to.
Can this be done?

A: If you include the js from the same source in both pages, it will be just loaded once, but will be accessible on both sites:
//parent/main.html

//other/iframe.html

So if theyre accessed in the iframe, the script is just loaded once, and if you access each of them without the other, it will still work too.

A: You can use postMessage to pass information back and forth between frames and their parent window.
https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage
You'll have to run the code to modify the element in the domain where it lives, but you can set a post message handlerler in the parent to kick it off.
// child window (iframe content)
parent.postMessage("hi there", "https://parent.domain.here");

// parent window
window.addEventListener("message", function(message){
    $("
"+message+"
").appendTo("body");
});


text:
Q: how to suspend the other threads when one thread is wishing to execute or print something? i am new to multithreading in C(LINUX)
i am doing a multiple client server(single) program ,here i am using threads for   execution of the server,so i need when a client is waiting for reply other threads(other server threads) should not run,
        while(n = read(conn->sock, buffer, sizeof(buffer))  > 0 )
        {
            //HERE I NEED THE LOCK THE OTHER THREADS FROM THEIR EXECUTION

                    //process
                    //process
                    //end of process

            //HERE I NEED TO RELEASE LOCK FOR THE OTHER THREADS EXECUTION

        }
    }

i did not find anything specific on the net,even some example URL will be helpful

A: For this you can use e.g. condition variables, where you can notify all waiting threads.

A: You can use conditions variables from POSIX pthreads if you need pure C.
https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

A: You should use Mutual Exclusion (mutex).  If you're on Windows I would use EnterCriticalSection on a critical section object.
You can also use std::mutex, which has been added in C++11 to try and create a standardized technique for this sort of thing.
Basically you have the thread that needs to transmit or access something take 'ownership' of the mutex and all other threads would check before taking action to see if the mutex is already owned.  If the mutex is owned the other threads would wait until it is released thus waiting their turn to take action.
It is highly advisable to use the operating system built-in method for doing this like my suggestion for Windows.  If you don't, you will not have the same level of fairness.  Most operating systems have built in optimizations for this while the STL objects may not.
Edit:
I some how missed the Linux tag but AlexBG provided the link to POSIX built in mutex usage: https://computing.llnl.gov/tutorials/pthreads/#ConditionVariables

A: Search for thread synchronization.
global variables will be shared by threads so use a global variable and then can acquire lock using that variable.

A: To protect the concurrent access to a shared resource a simple (fast) mutex would do.
#include <pthread.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

[...]

void some_func(void)
{
  [...]

  pthread_mutex_lock(&mutex);

  /* Access to shared resource here (print to stdout for example). */

  pthread_mutex_unlock(&mutex);

  [...]
}

Please note that this code lacks error checking for the sake of readability.


text:
Q: how to return a boolean after completion of coroutine? I have a Boolean method inside that some nested method, I want to return that boolean value after completion of all methods but it first executes that boolean value and returns that.
It prints->Entered, completed and started, end.
  fun syncAll(): Boolean {

    Log.d(TAG, "syncAll: Entered")
   val job= Coroutines.io {
        Log.d(TAG, "syncAll: started")
        method1()
        method2()
        method3()
        Log.d(TAG, "syncAll: end")
    }
    Log.d(TAG, "syncAll: completed")

    return job.isCompleted
}

A: You need to make syncAll() suspend function and call it from CoroutineScope that is at the calling site.
Inside syncAll() you can use withContext() to await result from different methods running on different coroutine(s).

A: syncAll should be a suspend function:
suspend fun syncAll(): Boolean {
    println("sync: started")
    val job = Job()
    CoroutineScope(Dispatchers.IO + job).launch {
        delayFunction(1000)
        delayFunction(2000)
        delayFunction(3000)
        println("sync: end")
    }.join() //Suspends the coroutine until this job is complete
    println("sync: completed")
    return job.complete()
}

suspend fun delayFunction(d: Long) {
    delay(d)
}

you have to call this function inside a coroutine:
val job = Job()
CoroutineScope(Dispatchers.Main + job).launch {
    val result = syncAll()
    println("sync: finished: $result")
}

result:
sync: started
sync: end //after 6 seconds
sync: completed
sync: finished: true


text:
Q: Win32 ListView: Make colored progress bar for full row I want to make a colored progress bar for full row in ListView. I take the idea from here:

In above image, we have colored progress bar, but only fo single cell. What I want is make same think, but for full row.
Here is what I have done:

Not as I expected :) I tried to draw at the CDDS_ITEM | CDDS_POSTPAINT case. The code:
static LRESULT
HandleCustomDraw(NMLVCUSTOMDRAW* pcd)
{
    TCHAR buffer[16];
    LVITEM item;

    switch (pcd->nmcd.dwDrawStage)
    {
        case CDDS_PREPAINT:
            /* Tell the control we are interested in per-item notifications.
            * (We need it just to tell the control we want per-subitem
            * notifications.) */
            return CDRF_DODEFAULT | CDRF_NOTIFYITEMDRAW;

        case (CDDS_ITEM | CDDS_PREPAINT) :
            /* Tell the control we are interested in per-subitem notifications. */
            return CDRF_DODEFAULT | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYSUBITEMDRAW;
        case (CDDS_ITEM | CDDS_POSTPAINT) :
        {
            // Test: assume the progress value is 50%
            float percent = 0.5;
            RECT r = pcd->nmcd.rc;
            r.right = r.left + percent * (r.right - r.left);
            HBRUSH hProgressBrush = CreateSolidBrush(RGB(255, 255, 0));
            FillRect(pcd->nmcd.hdc, &r, hProgressBrush);
            return CDRF_SKIPDEFAULT;
        }
    }
}

The expect result, for example at row Item 8, with percent = 0.5, is a filled rectange from start of the row, to between the third column, and the rest of the row is other color.
How I can achieve that? I know I have to draw different color for selected/focused/inative row, but I'm ok with it.
Edit:
Above image (the second one) is what I get with above code.
Demo what I want:

A: In WM_SIZE handler of the window retrieve and save the list view's client RECT (for example in global variable) with GetClientRect():
RECT list_view_rc;  // Global.
GetClientRect(list_view_hwnd, &list_view_rc);

RECT r = pcd->nmcd.rc; in your HandleCustomDraw() gives you the rectangle of currently drawn item inside list view's client area.
All you have to do now is to replace r.left and r.right with obtained values from list view's client rectangle:
r.left = list_view_rc.left;
r.right = list_view_rc.right;

This will give you a rectangle for the whole row to draw into.
You have to do this only on last item drawn if you're using CDDS_POSTPAINT. This is why you need another global variable list_view_column_count which contains the number of list view columns:
int list_view_column_count;   // Global.
list_view_column_count = Header_GetItemCount(ListView_GetHeader(list_view_hwnd));

With CDDS_POSTPAINT you have to draw the text inside the items by yourself because you destroyed it with rectangle, or try to mix the rectangle with text by changing foreground mix mode with SetROP2().
This is roughly the code you need (without text drawing):
static LRESULT
HandleCustomDraw(NMLVCUSTOMDRAW* pcd)
{
    TCHAR buffer[16];
    LVITEM item;
    // This static variable works only if you're always calling
    // HandleCustomDraw() only for one specific list view.
    static int current_item_count;

    switch (pcd->nmcd.dwDrawStage)
    {
        case CDDS_PREPAINT:
            /* Tell the control we are interested in per-item notifications.
            * (We need it just to tell the control we want per-subitem
            * notifications.) */
            current_item_count=0;
            return CDRF_DODEFAULT | CDRF_NOTIFYITEMDRAW;

        case (CDDS_ITEM | CDDS_PREPAINT) :
            /* Tell the control we are interested in per-subitem notifications. */
            return CDRF_DODEFAULT | CDRF_NOTIFYPOSTPAINT | CDRF_NOTIFYSUBITEMDRAW;
        case (CDDS_ITEM | CDDS_POSTPAINT) :
        if (++current_item_count == list_view_column_count)
        {
            // Test: assume the progress value is 50%
            float percent = 0.5;
            RECT r = pcd->nmcd.rc;
            r.left=list_view_rc.left;
            r.right=list_view_rc.right;
            r.right = r.left + percent * (r.right - r.left);
            HBRUSH hProgressBrush = CreateSolidBrush(RGB(255, 255, 0));
            FillRect(pcd->nmcd.hdc, &r, hProgressBrush);
            return CDRF_SKIPDEFAULT;
        }
    }
}


text:
Q: Translating C# object method chaining to F# Rather silly question, but I can't seem to find the correct terminology for it, so all my searching fails.
I have the following C# chain of method calls:
container.Register(Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifeStyleSingleton);

How do I write the same in F#?
I can do this:
let f0 = Component.For<IMyInterface> () in
let f1 = f0.ImplementedBy<MyClass> () in
let f2 = f1.Named "MyInstance" in
let f3 = f2.LifestyleSingleton () in
ignore (container.Register f3)

But surely there must be some other, nicer way to structure such a call.  No?
Addition
The early answers led me to a solution that worked (I've removed all mentions of ignore since it irrelevant and only confused readers):
container.Register (Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifestyleSingleton())

However, one reply states that this should work:
container.Register <| Component.For<IMyInterface>().ImplementedBy<MyClass>().Named("MyInstance").LifestyleSingleton()

but it doesn't.  The latter part, the expression after <|, generates a type error

This expression was expected to have type unit but here has type ComponentRegistration<IMyInterface>.

A: You can do pretty much the same thing in F#:
container.Register <|
    Component
        .For<IMyInterface>()
        .ImplementedBy<MyClass>()
        .Named("My Instance")
        .LifeStyleSingleton()

Here with some added sugar (<|). You can put the calls on a single line, or like I just did (I prefer that, since it nicely mirrors F# pipelining). One thing to remember is that the arguments need to be parenthesised and with no spaces between function name and the parens (pretty much "C# style").


text:
Q: ImageIO write produces a different file size as compared to the original image file When ImageIO is used to read an image file, then writes the BufferedImage (without any manipulation of the BufferedImage objet) to another file, the file size of the written file is different as compared to the original file.
Does ImageIO reads the full contents (including any metadata, like Exif metadata) of the image file?
And if it does read the full contents, then does ImageIO writes out the image contents including any metadata?

A: Many file formats (including for instance jpeg) can be correctly compressed in several different ways (even for the same quality settings). The decompression is deterministic while the compression may non-deterministic.
The fact that there is no unique right way of compressing an image implies that you can't expect ImageIO to produce a byte-equivalent result after loading / saving a file.


text:
Q: Protect against password cracking in Windows I know that exists tools for get the passwords in plain text from memory in Windows (read memory and decrypt password from LSASS process).
This behavior still exists in The Windows Server 2019 ?
Is there any way of avoiding that a local admin user get the password from a Windows machine using some of this tools, for example Mimikatz?
Thanks.

A: No to avoid it, as to steal kerberos ticket or NTLM hash keep in mind the user must be a local administrator, and the application must be run as a admin too.
Please see that note from mimikatz;

Run Mimikatz as Administrator: Mimikatz needs to be "Run as Admin" to function completely, even if you are using an Administrator account.

As such it fall into the 10 immutable laws of security; See the one in bold;

Law #1: If a bad guy can persuade you to run his program on your
computer, it's not solely your computer anymore.
Law #2: If a bad guy can alter the operating system on your computer, it's not your computer anymore.
Law #3: If a bad guy has unrestricted physical
  access to your computer, it's not your computer anymore.
Law #4: If
  you allow a bad guy to run active content in your website, it's not
  your website any more.
Law #5: Weak passwords trump strong security.
Law #6: A computer is only as secure as the administrator is trustworthy.
Law #7: Encrypted data is only as secure as its
  decryption key.
Law #8: An out-of-date antimalware scanner is only
  marginally better than no scanner at all.
Law #9: Absolute anonymity
  isn't practically achievable, online or offline.
Law #10: Technology
  is not a panacea.

As you fall into the 10 immutable laws of security, Microsoft will never fix that, as a admin can do anything on the computer, even installing a keylogger, who know, as you must understand it's more how you protect your environment against such attack vector that is important.
So at first I would suggest to use restricted group GPO to make sure no one can add itselft to the local admin group.
Secondly I would remove all other boot device than the HDD to secure who can boot on a flash device, to prevent someone that could wipe a local admin account's password.
Thirdly I would protect with a strong password the BIOS.
Lastly, I would use a encryption method for the hard disk, to prevent non-authorized change by a cold boot if someone remove the hard disk from the machine.
There is surelly other tips, but you must abide to a strong security's model if you want to secure your enterprise work space, and enable account auditing if you want to catch a bad actor.

A: With default settings it's not possible to dump clear text WDigest credentials from the LSA memory anymore, but having local administrator privileges all these new security features can still be disabled, as Microsoft loves to keep backwards compatibility. So, after adding a couple of registry keys Mimikatz – or Kiwi for Windows 10 – starts to function again for all passwords entered after the modifications.

*

*In Windows 8.1 security features were added that stops storing WDigest credentials in clear text, and they were backported to earlier Windows versions in KB2871997, fixing every version since Windows 7. When the feature is enabled, Mimikatz starts showing (null) for the password, but it can be disabled with:
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest]
"UseLogonCredential"=dword:00000001

*In Windows 10, Windows Defender Credential Guard is protecting passwords. After disabling the security feature as described above, the passwords are shown, but they are not in clear text:

However, Windows Defender Credential Guard can be disabled through Group Policy. As this policy effectively just adds two registry keys, it's egually easy to disable e.g. from command prompt.
[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceGuard]
"EnableVirtualizationBasedSecurity"=dword:00000000

[HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\LSA]
"LsaCfgFlags"=dword:00000000

Once a user uses his password again, it appears in clear text:

As this could easily be used for stealing Domain Administrator credentials, people should not have local admin privileges on their workstations, and separate accounts without Domain Administrator privileges should be used for local administration.

A: I would like to propose a solution that does actually work fairly well in practice. The other answers hint that it's impossible to protect perfectly, but you can make it difficult enough that most attackers will give up and move on to easier targets.
First, enable Credential Guard. This will move the secrets out of LSA so attackers can't read the passwords out of process memory.
Second, enable LSA Protected Process mode (RunAsPPL=1). This will prevent attackers from injecting code into LSA or reading memory.
Third, enable HVCI to prevent attackers from disabling the above protections from within the kernel.
Forth, lock this all down with UEFI so even if an attacker does screw with the registry keys, it's incredibly difficult to disable since the config is locked in by UEFI boot settings.


text:
Q: Dart and Flutter plugin: Code completion is not working in IntelliJ IDEA 2019.1 Unfortunately, there is a problem with the code completion using Dart and Flutter plugins in the new version IntelliJ IDEA 2019.1. The weird thing is when the Class is written, IntelliJ can find the Dart package correctly, but when I try to write it from the start, the code completion doesn't work, IntelliJ say "No suggestions":
https://imgur.com/ZxbpmEY.gif
Another thing, I don't know why the structure project although the Dart SDK and the flutter plugin are set up, IntelliJ insists to put a different SDK, in my case, JDK, I think the code completion is having problems because of this:
https://i.imgur.com/7HcaVcv.gif
Have ever you these problems? How have you solved it?
Thanks a lot for your help!

A: It doesn't have anything to do with your second screenshot (I think that just has to do with normal Java projects in IntelliJ, which is not applicable here).
It looks like it's just a bug in the current stable version of the Flutter SDK (and the current Dart language version it uses). This bug does not appear to be present in the current beta version however. If you open a terminal into your project directory (it's easiest in IntelliJ by clicking Terminal at the bottom of your window) and write the following:
$ flutter channel beta
$ flutter upgrade

You'll switch to the current beta version of Flutter (with the corresponding Dart language version that seems to have the bug fixed). More information on changing Flutter channels here.
At the time of writing, using the beta channel, these are my current version numbers:
Flutter:
  • version: 1.3.8
  • channel beta
  • https://github.com/flutter/flutter.git
Framework:
  • revision e5b1ed7a7f (4 weeks ago)
  • 2019-03-06 14:23:37 -0800
Engine:
  • revision f4951df193
Tools:
  • Dart 2.2.1 (build 2.2.1-dev.0.0 571ea80e11)
Doing the above fixed the problem for me, and now my code completion works as expected. Obviously you should be aware of the additional caveats of using non-stable build channels, but you can always switch back.
You can read more about how I figured out that I might need to upgrade my SDKs here.
It looks like they've been making great changes lately. I guess the current stable version just has a bug (or it wasn't originally a feature?).


text:
Q: Display error message in jQuery popup or in alert in MVC 4 Am using DataAnnotation for validation, I want to show the error message(Data annotation) in a pop up (dialog/alert) instead of showing it on view....
I have implemented the code using this link..
Project template is Mobile
Let me know if I am missing something ??
http://forums.asp.net/t/1738076.aspx/1
Javascript:-
$('#Test').bind('invalid-form.validate', function (form, validator) {
    alert('InsideTest');
     var $list = $('#errorlist ul:first')
     if ($list.length && validator.errorList.length) {
            $list.empty();
            $.each(validator.errorList, function () {
                $("
").html(this.message).appendTo(list);
            });
            $list.dialog({
                title: 'Please correct following errors:',
            });
 }
});
Forgot to add html...

About.cshtml :-
@model WRDSMobile.Models.Test

@using (Html.BeginForm(null, null, FormMethod.Post, new { name = "Test", id = "Test" }))
{
     @Html.ValidationSummary(true)
     <fieldset>

        <legend>Test</legend>

            @Html.LabelFor(model => model.Name)

            @Html.EditorFor(model => model.Name)
            @Html.ValidationMessageFor(model => model.Name)

            @Html.LabelFor(model => model.Age)

            @Html.EditorFor(model => model.Age)
            @Html.ValidationMessageFor(model => model.Age)

            <input type="submit" value="Create" />
    </fieldset>
}

A: I'm not sure if I understand your question, but you can ajax post to your controller and return a partial view. Then load the partial view into your html element and then pop it up in a dialog box.
 [HttpPost]
    public ActionResult validate(string firstName,string lastName){

        //logic here for validation
         return PartialView();
    }

$.ajax({
            type: "POST",
            data: {firstName: nameVal, lastName: lastNameVal },
            url: "/myController/validate",
            dataType: "html",
            success: function (data) {
                if (data) {
                    var dialog = $('

');
                    dialog.html(data);
                    dialog.dialog({
                        resizable: false,
                        modal: true,
                        overflow: false,
                        maxWidth: 1200,
                        maxHeight: 600,
                        width: 1200,
                        height: 600,
                        border: 0,
                        buttons: {
                            "Cancel": function () { //cancel
                                $(this).dialog("close");
                            }
                        }

                    });
                }
                else {
                    alert("error");

                }
            }
        });

A: Add below following CSS/JS as referance jquery-ui.css, jquery-1.8.2.min.js, jquery-ui-1.8.24.min.js, jquery.validate.min.js, jquery.validate.unobtrusive.min.js
$(document).ready(function () {
        $('#Test').bind('invalid-form.validate', function (form, validator) {
            var $list = $('
')
            if (validator.errorList.length) {
                $.each(validator.errorList, function (i, entity) {
                    $("
").html(entity.message).appendTo($list);
                });
                msgbox('Please correct following errors:', $('
').append($list));
                return false;
            }
        });
    });

    function msgbox(_title, _messageHtml) {
        $('

').appendTo('body')
                    .html(_messageHtml)
                    .dialog({
                        modal: true, title: _title, zIndex: 10000, autoOpen: true,
                        width: 'auto', resizable: false,
                        buttons: {
                            Ok: function () {
                                // $(obj).removeAttr('onclick');
                                // $(obj).parents('.Parent').remove();

                                $(this).dialog("close");
                            }
                        },
                        close: function (event, ui) {
                            $(this).remove();
                        }
                    });
    };

A: public static void method(this ModelStateDictionary modelState)
    {
        StringBuilder errors = new StringBuilder();
        try
        {
            foreach (ModelState model_State in modelState.Values)
                foreach (ModelError error in model_State.Errors)
                    errors.AppendLine(error.ErrorMessage.ToString());
            if (errors.Length > 1)
                throw new Exception();
        }
        catch (Exception ex)
        {
            throw new // your validation helper
        }

}
catch this in ajax sucess false open jquery dialog with this error error message
Note : use mvc error handler it will send the error message with ajax success= false


text:
Q: C# SQLite get real value from DB generates Invalid Cast Exception I am trying to get a real value from a SQLiteDatabase using C#.
Everything is working fine with exception of the real values.
I use the following code to get the data from the database
// Building query...
cmd.CommandText = "SELECT * " +
    "FROM ProductsPrice p " +
    "WHERE p.ProductId = @ProductId " +
    "ORDER BY Date DESC " +
    "LIMIT 1";
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("@ProductId", ProductId);

// Execute query
using (SQLiteConnection conn = DatabaseService.getDbConnection())
using (cmd.Connection = conn)
{

    //Open Connection
    conn.Open();

    using (SQLiteDataReader dr = cmd.ExecuteReader())
        while (dr.Read())
        {
            //var x = dr.GetString(dr.GetOrdinal("NetPrice"));
            //var y = dr["GrossPrice"];
            //var x = dr.GetOrdinal("GrossPrice").GetType();

            price.Id = dr.GetInt32(dr.GetOrdinal("Id"));
            price.NetPrice = dr.GetDouble(dr.GetOrdinal("NetPrice"));
            price.GrossPrice = dr.GetDouble(dr.GetOrdinal("GrossPrice"));
            price.VAT = dr.GetDouble(dr.GetOrdinal("Vat"));
            price.AddedDate = dr.GetDateTime(dr.GetOrdinal("Date"));
        }

}

object price is as follows:
public int Id { get; set; }
public double NetPrice  { get; set; }
public double GrossPrice  { get; set; }
public double VAT  { get; set; }
public DateTime AddedDate { get; set; }

The database columns are as follows:
ID = INTEGER
NetPrice = REAL
GrossPrice = REAL
Vat = REAL
Date = datetime

When I get the NetPrice this works because the value is 2. But when I get the GrossPrice I get an Invalid Cast Exception because this value is 2.42.
What am I doing wrong here?
If I check the GetType() of the GrossPrice it is a Int32. But that is impossible with the value 2.42.
If I use price.GrossPrice = Convert.ToDouble(dr["GrossPrice"]) I get as result 2 (without .42).
If I change the SQLite DB column type to Double or Float. It does not change anything.
I'm out of ideas...


text:
Q: How can I show that $\sum \limits_{i=1}^n i^2$ is $O (n^3)$ I am preparing for an exam, and one of the problems on the study guide is:

Show that $\sum \limits_{i=1}^n i^2$ is $O (n^3)$

If we declare n as some arbitrary number 5, then our summation would read $1^2$ + $2^2$ + $3^2$ + $4^2$ + $5^2$
Everything I have researched would suggest to me that this should be $O (n^2)$.  How do we come up with $O (n^3)$?

A: Hint: Note that
$$\sum_{i=1}^n i^2 = 1^2 + 2^2 + \cdots + n^2 \le n^2 + n^2 + \cdots + n^2.$$

A: It is not difficult to show that
\begin{align}
\sum_{i=1}^{n} i^{2} = \frac{n(n+1)(2n+1)}{6} = \frac{n^{3}}{3} + \frac{n^{2}}{2} + \frac{n}{6}
\end{align}
Since the highest power on $n$ is 3 then it can be stated that
\begin{align}
\sum_{i=1}^{n} i^{2} \sim \mathcal{O}(n^{3})
\end{align}


text:
Q: Mi petición AJAX no se queda ahí Ahora mi problema es que la petición se me envía, todo correcto; PHP7 me captura las variables y me hace la consulta, pero... Al momento de obtener los datos, la consulta no se me queda, si no que se me refresca toda la página de nuevo.
$(document).ready(function(){
        function obtener_datos(){
            $.ajax({
                type:"POST",
                url:"consultar_aprendiz.php",
                success:function(data){
                    $('#consulta').html(data);
                }
            });
        }
        $(document).on("click", "#consultar", function(){
            $.ajax({
                type:"POST",
                url:"consultar_aprendiz.php",
                data:$('form').serialize(),
                success:function(data){
                    alert(data);
                    obtener_datos();
                }
            });
        });
    });

El alert(data) que está en el success, me muestra que la consulta sí se realiza, pero la página no se me muestra. Con otras pruebas, sí sé que la página se refresca y no que no la llama.
Quisiera saber porqué y si alguien me puede ayudar. Muchas gracias.

A: Entiendo
Como no se sabe cómo está el resto del código,te pongo un ejemplo de como tendrías que poner la función AJAX de manera correcta,sin necesidad de llamar a otro método que haga otra consulta para que te lo pinte,por que ya se lo puedes indicar.En contentType,debes poner el formato de los datos que estás enviando a la página,y en el dataType,el tipo de datos que vas a recibir por parte de la página a la que consultas.
 $(document).ready(function(){
    $("#consultar").on("click",function(){
        $.ajax({
            type:"POST",
            contentType:"application/json",
            dataType:"Json",
            url:"consultar_aprendiz.php",
            data:$('form').serialize(),
            success:function(data){
                alert(data);
                 $('#consulta').html(data);
            }
        });
    });
});


text:
Q: Pros and Cons usage await in the map with promise.all I'm wondering about: is there any negative effect for using await in the loops like map / for...of ?
And what is the cons & pros about that ?
await Promise.all(products.map(async (product) => {
      await Product.CreateProductIfDoesntExists(params);
}));

A: You asked about await in loops but your example shows a specific kind of loop, calling map so, await in map
Pro:

*

*Lots of requestw get started, possibly all in parallel so likely much faster depending on what Product.CreateProductIfDoesntExists does

Con:

*

*Potentially uses too much memory depending on how many products there are and what kind of work Product.CreateProductIfDoesntExists does

Here's a simple example: In this case 5 things means 80 meg is used at once but it finishes in 2 seconds

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function processThing() {
  const data = new Uint8Array(1024 * 1024 * 16);
  await wait(2000);
  return data[data.length - 1];  // pretend we use data
}

async function main() {
  const things = ['a', 'b', 'c', 'd', 'e'];

  await Promise.all(things.map(async(thing) => {
        await processThing(thing);
  }));
  console.log('--done--');
}
main();

vs this one, only 16 meg is ever used, but it takes 10 seconds

const wait = (ms) => new Promise(resolve => setTimeout(resolve, ms));

async function processThing() {
  const data = new Uint8Array(1024 * 1024 * 16);
  await wait(2000);
  return data[data.length - 1];  // pretend we use data
}

async function main() {
  const things = ['a', 'b', 'c', 'd', 'e'];

  for (const thing of things) {
     await processThing(thing);
  }
  console.log('--done--');
}
main();

If the first example using map used more memory per thing or had to process 1000 things or 10000s things you could easily run out of memory.
The second example won't run out of memory as it's only processing one thing at a time.
There is nothing wrong with using await in map, unless you know ahead of time that the stuff that's going to happen inside takes tons of memory or the number of items processed will be very large.
The second example is probably less than ideal. If you really wanted to handle 1000 or 10000 things you'd still probably want to process them several at a time (say 10 at a time) and so you'd need a far more complex queue of work to make that efficient.


text:
Q: I added a proxy to Selenium and now the page won't open [Python] My bot successfully worked on my local network.
But by adding proxies as if lost connection to the network...
Here's my code:
from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.chrome.options import Options
from time import sleep

# SMM Setup
VIDEO = 'https://www.youtube.com/watch?v=TjiUC8jeF1o'
VIEWS = 20

# PROBLEM SETUP
PROXIES = [
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000',
    '0.0.0.0:0000'
]
YOUTUBE_ACCEPT_COOKIES_A = '/html/body/ytd-app/ytd-consent-bump-v2-lightbox/tp-yt-paper-dialog/div[4]/div[2]/div[6]/div[1]/ytd-button-renderer[2]/a/tp-yt-paper-button'
YOUTUBE_ACCEPT_COOKIES_B = '/html/body/ytd-app/ytd-consent-bump-v2-lightbox/tp-yt-paper-dialog/div[4]/div[2]/div[6]/div[1]/ytd-button-renderer[2]/yt-button-shape/button'

# start - 153

# Init
global driver

# Create Views
for x in range(len(PROXIES)):
    options = Options()
    options.add_argument('--proxy-server=%s' % PROXIES[x])
    driver = webdriver.Chrome(executable_path='C:/Users/sasha/OneDrive/Desktop/CHROME_DRIVER/chromedriver.exe', chrome_options = options)
    driver.get(VIDEO)
    for y in range(VIEWS / PROXIES):
        driver.refresh()
        try:
            WebDriverWait(driver, 1).until(EC.element_to_be_clickable((By.XPATH, YOUTUBE_ACCEPT_COOKIES_A))).click()
        except TimeoutException:
            try:
                WebDriverWait(driver, 1).until(EC.element_to_be_clickable((By.XPATH, YOUTUBE_ACCEPT_COOKIES_B))).click()
            except:
                print('Any Cookie Accepts Not Found')
        sleep(2)
    driver.quit()

# Close All Tabs
driver.quit()

I tried to remove chrome_options = options. It worked.
But I can't use my local network for some reason.

A: Try to change port
Example: 4444 to 12345 / 55555


text:
Q: Regex to replace @PathVariable values in Spring @RequestMapping URL I have Spring MVC URL's define in Interfaces (just to hold the Constants) like:
String URL_X = "/my-url/{id:[0-9]*}";
String URL_Y = "/my-url/{id:[0-9]*}/blah-blah";

I have a method for my tests that replace the variables in an URL:
private static final String REGEX_PARAMETROS_DA_URL = "(\\{[^\\}]*\\})";
    protected String replaceParametersOnURL(String urlSpring, String... params) {
        String urlAtual = urlSpring;
        for (String parametro : params) {
            urlAtual = urlAtual.replaceFirst(REGEX_PARAMETROS_DA_URL, parametro);
        }
        return urlAtual;
    }

I was using this regex: (\{[^\}]*\}) to match the variables and replace it.
But now i have some URL's that have {} on it and i can't find a properly regex to replace the variable with my value.
Is there any method on Spring that replaces the PathVariable value or can anyone help me with this regex?
Given this URL for instance:
/pessoajuridica/{cnpj:[0-9]{14}}-{slug:[a-zA-Z0-9-]+}/sancoes/resumo

The matches must be: {cnpj:[0-9]{14}}and {slug:[a-zA-Z0-9-]+}

A: Thanks @Matthew. I haven't noticed that the spring test itself can do this!
All i need to do is:
mockMvc.perform(get("/pessoajuridica/{cnpj:[0-9]{14}}-{slug:[a-zA-Z0-9-]+}/sancoes/resumo", var1, var2)) ...


text:
Q: How can I monitor/sample output audio in Java or C? Lately I have been experimenting with real time visualizations on the audio I play on my computer (via any arbitrary program, such as Spotify) but I've been using SoundFlower to pipe the output audio in to a fake line in.
What I'm wondering is if there is a way that is native to C/C++ or Java that will allow me to capture whatever audio is sent to my computer's (I'm using a Mac) line out in a similar way to how I can capture a line in (I.E. a sample buffer that is continually filled with PCM data).
I have no desire to emulate the other features of SoundFlower except for reading the line out data.

A: I suggest having a look at the source code for WavTap, a fork of SoundFlower, which focusses only on capturing the default audio output of the system.
Both SoundFlower and WavTap work by installing a kernel extension, which adds an additional audio device to which audio can be routed. They then captures audio from this device. WavTap makes this the default device when it starts so that the overall output of the system is automatically captured without the user having to explicitly set up the routing.
I believe the WavTap code is MIT licensed and the system extension code is well abstracted so you should be able to adapt it for your own project.
To understand a bit more about how this works, the OS X and iOS Kernel Programming book has an explanation of some of the techniques in Chapter 12 as well as downloadable code for an example audio device and engine.


text:
Q: Update value from table if/else change status vice versa when active then change status in db as inactive
if (isset($_GET['id']) && is_numeric($_GET['id']))
{
$id = $_GET['id'];
$result = mysql_query("UPDATE profile SET status='active' WHERE status='inactive' AND id =$id")
or die(mysql_error());

header("Location: admin-members.php");
}
else{
header("Location: admin-members.php");
}

this is a working code but i wanted it to work both ways. when i click inactive it would change it active and vise versa. i tried it with case too but no luck
?>

A: maybe you only want to filter it by $sid and use CASE to toggle the value of status
UPDATE profile
SET status = (CASE WHEN status = 'active' THEN 'inactive' ELSE 'active' END)
WHERE id = $id

A:     $getStatus =mysql_query(" select status from profile where id =$id")
or     die(mysql_error());
    $stat = mysql_fetch_assoc($getStatus);
    if($stat['status']== 'inactive')
    {
    $result = mysql_query("UPDATE profile SET status='active' AND id =$id");
    }
    elseif($stat['status']== 'active')
    {
    $result = mysql_query("UPDATE profile SET status='inactive' id =$id");

    }

A: You could pass in your status as a $_GET variable too, and check that it is an acceptable value.
if (isset($_GET['id']) && is_numeric($_GET['id']) && in_array($_GET['status'],array('active','inactive')))
{
$id = $_GET['id'];
$status = $_GET['status'];
$result = mysql_query("UPDATE profile SET status='$status' WHERE id =$id")
or die(mysql_error());

header("Location: admin-members.php");
}
else{
header("Location: admin-members.php");
}

*From here you might want to parameterise your query to safeguard against SQL injection too.

A: If active and inactive are all the available options, I mean if there isn't any third option, John Woo's suggestion will do it. Yet here's another approach.
UPDATE `profile`
SET `status` = IF(`status`='active','inactive','active')
WHERE `id` = $id

If there is a third option then you might want to add that in your when clause:
WHERE `id` = $id AND `status` IN ('active','inactive')

or
WHERE `id` = $id AND (`status`='active' OR `status`='inactive')


text:
Q: What is the expected payment that you will have to make the company? The claim amount for medical expenses insurance is modeled with an exponential random variable with mean 20. The insurance company applies a deductible of 5. The payment function of the company is the amount of the claim.
minus the deductible, when this amount is positive and zero otherwise. What is the expected payment that you will have to make
the company?
Let $R$ be the random variable that represents the claim amount then
$$f_R(r)=\frac{1}{20}e^{-\frac{1}{20}r}\mathbb{I}_{[0,\infty)}(r)$$
Then let $P$ be the payment function of the firm then
$$P(r)=\left\{ \begin{array}{lcc} \frac{1}{20}e^{-\frac{1}{20}r}-5 \hspace{1cm} r<-40ln(10)\\0 \hspace{1cm} In\hspace{.2cm} another\hspace{.2cm} case \end{array}\right.$$
It is what I have tried but I suspect that it is wrong, can someone help me?

A: Here $P = (R-5)\cdot\mathsf 1_{(5,\infty)}(R)$. It follows that
$$
\mathbb P(P=0) = \mathbb P(R<5) = \int_0^5 \frac1{20} e^{-\frac1{20} r}\ \mathsf dr = 1-e^{-\frac14},
$$
and for $r>0$
$$
\mathbb P(P>r) = \mathbb P(R>r+5) = \int_{r+5}^\infty\frac1{20} e^{-\frac1{20} r}\ \mathsf dr = e^{-\frac{5+r}{20}}.
$$
From this we may compute
$$
\mathbb E[P] = \int_0^\infty \mathbb P(P>r)\ \mathsf dr = \int_0^\infty e^{-\frac{5+r}{20}}\ \mathsf dr = 20 e^{\frac14}.
$$


text:
Q: when i do a query with spring data jpa , findTop10XX if the value is less the query takes a long time public interface AlarmRepository extends MongoRepository<Alarm, String> {

List<Alarm> queryFirst10ByHubAndDeletedAndDataspace(String idHub, boolean b, String dataspace, Pageable sort);

List<Alarm> queryTop10ByHubAndDeletedAndDataspace(String idHub, boolean b, String dataspace, Pageable sort);

List<Alarm> findTop10ByHubAndDeletedAndDataspace(String idHub, boolean b, String dataspace, Pageable sort);
}

index de hub in alarms
@CompoundIndex(name="alarm_hub_id_index", def = "{'hub.$id' : 1}")
@CompoundIndex(name="alarm_hub_id_dt_event_desc_index", def = "{'hub.$id' : 1, 'dtEvent' : -1}")

postmant get
/rest/titan/v1/alarms/historical?hub=62285d951a110632228d6a0e&dataspace=200&sort=dtEvent,desc

If the data number value is greater than or equal to that indicated in the top, the query time does not exceed 200ms, on the other hand, if the data is less than the value entered in the top or in the page, the query is very slow, even return a timeout
class Alarm
    @Document(collection="alarms")
@CompoundIndex(name="alarm_dt_event_dataspace_index", def = "{'dtEvent' : 1, 'dataspace' : 1}")
@CompoundIndex(name="alarm_hub_id_index", def = "{'hub.$id' : 1}")
@CompoundIndex(name="alarm_hub_id_dt_event_desc_index", def = "{'hub.$id' : 1, 'dtEvent' : -1}")
@CompoundIndex(name="alarm_hub_id_dt_event_desc_dataspace_index", def = "{'hub.$id' : 1, 'dtEvent' : -1, 'dataspace' : 1}")
public class Alarm extends CommonEntity implements Cloneable{
    //@ApiModelProperty(notes = "Date start Alarm")
    //@Field
    @Indexed(name = "dt_event_alarm_index",unique = false)
    private DateTime dtEvent;
    //@ApiModelProperty(notes = "Source of Alarm")
    @Field
    private Source source;
    @Field
    private String comments;
    @Field
    private Boolean active;
    //@ApiModelProperty(notes = "Severity of Alarm")
    @Field
    private Severity severity;
    //@ApiModelProperty(notes = "Detail of Alarm")
    @Field
    private DetailAlarm detail;
    //@ApiModelProperty(notes = "Hub of Alarm",required = false)
    @Field
    @DBRef
    private Hub hub;
    //@ApiModelProperty(notes = "Hub of Alarm",required = false)
    //@Indexed(name = "traffic_controller_alarm_index")
    @Field
    @DBRef
    private TrafficController trafficController;
    @Field
    private ElementTypeAlarm elementType;
    @Transient
    private String dtEventForKafka;
    @Transient
    private String dataspaceForKafka;
    ... geter seters
}


text:
Q: Implementing Pillar Posts; Long Posts yet with Some Page-Like Handling? One of the best blogging practices is that of writing "pillar posts" - featured content that's longer than a typical post and will likely generate a high volume of traffic to your site.  Extensive tutorials, comprehensive user guides, and in-depth product reviews mostly fall into this category.  They're the 1500-word behemoths that sit alongside your daily 300-word "update" articles.
Most of the times, pillar posts can be thrown to the top of your site with stickies.  This makes them visible, directs the user's attention, and keeps timeless content relevant.  After a while, though, you might want to promote these posts to static pages - still searchable and useful, but with their own special spot on the blog.
I have a series of articles I plan to write over the next month or so regarding the XML-RPC API built in to WordPress.  It's a great system, but scantily documented ... so I'm going to put together some comprehensive method documentation.
The thing is, my docs will cover roughly 5-6 different pillar posts.  I want this content to be featured on my blog when it's published (once per week), but I'd also like the entire series to be repeated as a static page on the site.  The static page would be broken up into individual pages (using <!--nextpage--> to divide sections) so that each post is contained in a different section.
How can I have my featured content be both individual posts on the blog and a separate static page?  I'm looking at both usability and SEO here ... having the content duplicated is a huge negative, so a simple copy-paste job with both versions on the site isn't my goal.
My first inkling would be to develop a custom post type for features like this with its own custom taxonomy.  Each "post" would be an individual feature (custom post type) and would be owned by a series (custom taxonomy).  Then each post could be included in the loop when published but also on the archive page for the series.
So my question (and the reason I'm marking this as a wiki), is how would you approach this situation?

A: As I was reading your post I was envisioning almost exactly what you prescribed at the end:

My first inkling would be to develop a
  custom post type for features like
  this with its own custom taxonomy.
  Each "post" would be an individual
  feature (custom post type) and would
  be owned by a series (custom
  taxonomy). Then each post could be
  included in the loop when published
  but also on the archive page for the
  series.

The only difference was I was thinking "Pages" instead of "Features" mostly because you referred to Pages in your question but Features is probably even better.
So your instincts are already spot-on, IMO anyway.

A: You could create a static page with its own loop calling only the posts which belong to your series. Or – much easier – create a custom taxonomie "series" and use the_content() on (/series/xml-rpc/) for the loop instead of the_excerpt().