text:
Q: Entity-relationship (modifying my current digram) I'm practicing ERD (entity-relationship diagram); i was trying to solve this particular exercise:

We work to build an e-commerce platform that facilitates B2C (business to consumer) and C2C (consumer to consumer) sales. On our
  platform, anyone who wants to make a sale (be it a company or a
  person) has a registered user and a catalog of products that they can
  sell. They can be used or new. For each product that is published for
  sale, a general definition of parameters is established (the same
  product may be published more than once with different payment options
  and / or promotions). Normally, sellers who sell used products have a
  single unit, while sellers of new products generally handle varied
  stocks. The available stock of a product can be obtained by being
  connected to your system (this allows online updating) or manually
  maintained in our application. Each seller maintains his own product
  catalog, with the name and details that he considers. Each product is
  in a category, which makes it easy to search, and can be related to
  other items (products). We use this a lot for cross selling (for
  example, someone who buys a battery may be interested in purchasing a
  charger). In the same purchase I can buy multiple products and / or
  quantities of each one while they are from the same seller. In case of
  acquiring multiple items, the seller can pack them together (example
  if I buy 2 headphones) to simplify and make shipping cheaper or,
  otherwise, each item will have a different shipping (with a separate
  cost for each). For each shipment I will have a particular tracking /
  tracking id (this is done in the supplier of the same, example FedEx).
  Each purchase has a single shipping address, even if they are divided
  into multiple packages. A buyer must always be logged in and for each
  of them we have their personal data, the rating that sellers have
  given them for their purchases, accumulated points (which give them
  benefits) and we maintain a history of their operations. With each of
  the purchases made, our customers add points, which allow them to
  access many benefits, among which we can mention: Free shipping,
  discounts on future purchases, etc. The benefits that our buyers have
  are determined by categories, which are divided by range of points. It
  should be noted that, in addition, you can also be a seller. Sellers
  are interested in knowing if it is a company or an individual, their
  basic tax data (for legal reasons), the rating given by buyers (they
  are rated between 1 and 5 based on the service and attention
  provided), how many operations they carried out , what kind of
  shipments do you make and accepted payment methods. Daily we establish
  discounts on some publications and they last a few hours. In general
  they are discounts of between 2% and 10% but they help us to improve
  sales. This discount does not affect the seller's profit but we absorb
  it from our company.

I modeled this diagram, i think it is okay:

The problem is:

How would you change the exercise (the statement) in order to create
  another ternary relationship?
  Also, what information is relevant if
  you want to award prizes to buyers for the qualification obtained
  based on purchases made in the last 3 months and whose amount exceeds
  500 dollars on average?


text:
Q: How to update selected sharepoint list items with javascript, Hi this works fine on button click ; it loops selected items in the view, alerts the id & calls the updateListItem function
function ViewSelectedItems(){
var selectedItems = SP.ListOperation.Selection.getSelectedItems();for (var i = 0; i < selectedItems.length; i++) { alert("Item with Id = " + selectedItems[i].id+ " is selected");  updateListItem(selectedItems[i].id)}
                 window.location.href = window.location.href;
}

the updateListItem reports onQuerySucceeded but the field value is not set to the new value. Any ideas please?
    function updateListItem(passedid) {

 var siteUrl = '/supportdepts/hr/';

 var newval = 999;

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle('Staffing Control Panel Request');
    this.oListItem = oList.getItemById(passedid);
    oListItem.set_item("RefNumber", newval);
    oListItem.update();
    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),

    Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
    alert('Item updated!');
}

function onQueryFailed(sender, args) {
    alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

A: I am not so very familiar with the case but I do know that when this kind of trouble occur even though the code seems OK, the values which should navigate the code are probably mistaken. In other words, maybe the list name you are using is not the real name but the display name. You should make sure the names you are using are the real schema's names of the lists and fields and not just the display ones.
I hope I did help somehow. G o o d   L u c k!!!

A: Did you tried to refresh the browser?
The same code worked for me, but i need to refresh browser to view item's new values.

A: Well I had the same issue and it's due to the fact that the page refresh occurs before the async event is done, which means the context is lost. So that the item is not saved, even though everything seems perfect before calling executeQueryAsync.
If you remove the refresh, it should work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Reference request: Rate of convergence of sequence of functions Suppose you are given a sequence of functions $f_n \rightarrow F$ with a certain notion of convergence. Suppose that in your setting where this implies that $f_n^{'} \rightarrow F^{'}$ with the same notion of convergence.
We will say that ``the rate of convergence of the sequence of derivatives is at least as fast as the rate of convergence of the sequence of functions'' if the following holds:
there exists a constant $C>0$ (independent of $n$) such that
$|\frac{f_n^{'}-F^{'}}{f_n-F}| \leq C$
In plain language, what conditions should your sequence of functions satisfy
in order to guarantee that the rate of convergence under taking the derivative gets no worse?
In particular, let us suppose that we are in the setting where our functions
are complex-analytic, and the convergence is uniform convergence. In this situation,
we have the ``Weirstrass Uniform Convergence Theorem'' that tells us that the derivatives
converge uniformly as well. But can we conclude anything about the rate of convergence?
Any type of reference where a problem of this type is considered would be much appreciated.

A: Consider the special case of  holomorphic functions. We can assume that $F=0$.   Denote by $D_R$ the disk $\lbrace |z|\leq R\rbrace$.    Denote by $Z(n, R)$ the number of zeros of $f_n$ in  the interior of $D_R$.  Then
$$2\pi Z(n,R)= \left|\int_{\partial D_R} \frac{f_n'}{f_n} dz\right|  \leq \int_{\partial D_R} \left|\frac{f_n'}{f_n}\right| dz. $$
Let
$$f_n(z) = \frac{1}{n!} \prod_{k=1}^n\left( z-\frac{1}{k}\right). $$
Observe that
$$ \sup_{z\in D_R} |f_n(z)|\leq \frac{(R+1)^n}{n!}, $$
so that $f_n$ converges uniformly on compacts to $F\equiv 0$. On the other hand for a fixed  $R>1$ we have
$$ Z(n, R)= n. $$
Now you see the problem.


text:
Q: Is there a free program for easily managing network locations? I move around from the office and elsewhere quite a lot. When I'm in the office, I need a static IP, elsewhere I don't. I have network locations set up, but it's extremely tedious opening up Network Preferences to change it essentially every day.
Ideally I'd like an app where I can just select from the taskbar menu, like I can with Wireless networks, or a way to apply the IP config whenever I connect to that specific network.
I've found paying apps, like Sidekick, which are massive overkill (I don't want to shell out £20 for an app I'll only use one function of), I just want a tiny utility. Is there such a thing?

A: Check out something called ControlPlane. I've been using it for a while now and it can automatically change a whole array of settings from networks to printers on your mac depending on where you are like sidekick, but its free and so much better.
Lifehacker and Mac AppStorm featured it not long ago.

A: I found an applescript solution that does what I need. I've tweaked it a bit from the original, but it provides a one-button solution for switching my network location.
Here's the code I used:
tell application "System Events"
        tell network preferences

                set activeLocation to the name of current location

                set allLocations to the name of every location
                copy "Quit" to the end of allLocations

                set deleteFromList to {activeLocation}
                set changeLocations to {}
                repeat with i from 1 to count allLocations
                        if {allLocations's item i} is not in deleteFromList then
                                set changeLocations's end to allLocations's item i
                        end if
                end repeat

                if (text of choiceLocation) = "Quit" then
                else
                        do shell script "scselect '" & (text of choiceLocation) & "'"
                end if
        end tell
end tell

Exporting this from AppleScript as an Application, and pinning it to my app bar gives me a one-button Network Location Switcher.

A: You can do that with Network locations. You can defined for example two profiles: work (fixed IP) and home (DHCP).
As you said chancing the location from System Preferences is tedious. However you can do the same from the  menu:  > Location.


text:
Q: Is there an intended watching order for the Lego and Rebels Star Wars shorts on Disney Plus? I am talking about these short series:

A: These collections of shorts are not consistent stories to be played in order. They jump around in time, location, and sometimes even in characters. Having watched the Rebels shorts, I believe each episode would be spread throughout the regular Rebels seasons.
TLDR; No, there is no particular order to watching these as they do not hold to a consistent, consecutive time period themselves.


text:
Q: Proving if k-algebras are finitely generated and noetherian Given two $k$-algebras $R:=k\oplus x^2 \, k[x] \subseteq k[x]$ and $S:= k\oplus xy \,\, k[x,y] \subseteq k[x,y]$ I need to show if they are finitely generated and if they are noetherian.
For $R$ to be finitely generated k-Algebra, we need to show that there exist finitely many elements, $a_1, a_2,....a_n$ such that $R=k[a_1,a_2,...a_n].$ But we know that it is contained in $k[x]$. For the second Question I Need to show if there is an ascending chain of ideals.
Can somebody give me a hint as how to proceed ? Many thanks.

A: $R = k \oplus x^2 k[x] = k [ x^2, x^3 ]$
Also, $S$ is isomorphic to the semi-group algebra $k [ \mathbb N \times \mathbb N ]$, which is not a finitely generated semi-group.
None of the $(n, 1)$ can be written in terms of others. So $S$ is not Noetherian.


text:
Q: How to quit a script but not the GUI application I have got a GUI aplication which includes five python scripts.
I  have already found an error in the IO data, and then I'd like to include a escape condition to quit the python script and show a QT message but stay the GUI application.
one of the scripts
        if len(Numero_Unidades) != 1:
            quit()
        else:
            pass

        block

but it quits  python
and I want to stay in the GUI application, maintaining the main window open.
if self.ui.radioButton3.isChecked()== True:
        myscript.myscript()
        QtGui.QMessageBox.information(self,'message')

How can I do that?

A: You can start another python process to launch your script
By using os.system("script.py")

A: Assuming that the quit() function is the built-in quit, you can monkey-patch it and raise an error instead of quitting the whole appliaction:
import myscript
import __builtin__

def myquit():
    raise RuntimeError('script quit!')

__builtin__.quit = myquit

try:
    myscript.myscript()
except RuntimeError as exception:
    print(exception)
else:
    print('keep calm and carry on')


text:
Q: htaccess HTTP 200 message body How can i add a message body to my HTTP 200 response from .htaccess ?
like Hello world! :

HTTP/1.1 200 OK
Date: Sun, 10 Oct 2010 23:26:07 GMT
Server: Apache/2.2.8 (Ubuntu) mod_ssl/2.2.8 OpenSSL/0.9.8g
Last-Modified: Sun, 26 Sep 2010 22:04:35 GMT
ETag: "45b6-834-49130cc1182c0"
Accept-Ranges: bytes
Content-Length: 13
Connection: close
Content-Type: text/html

Hello world!

A: This isn't something you do in .htaccess alone. Short of directly requesting a file that returns the "Hello World!" response, what you can do in .htaccess is rewrite the requested URL to a file that returns the "Hello World!" response.
For example, given a request for http://example.com/foo then you could rewrite this request using mod_rewrite in .htaccess to a plain text file that outputs the response. For example:
In /.htaccess:
RewriteEngine On
RewriteRule ^foo$ hello-world.txt [L]

In /hello-world.txt:
Hello World!

Of course, you could simply request http://example.com/hello-world.txt directly (unless you add additional directives to redirect such direct requests).


text:
Q: SED find and replace - MapReduce file Im trying to find and replace all "^A" characters with a "\t" so that I can import the data into a mysql database. The command Im using on OSX is:
sed -i '' 's/^A/\t/' item_info_20130203 > item_info_20130203_tab

This just deletes all the contents in the file. Where am I going wrong?

A: The command should actually be something like this:
sed 's/'`echo "\001"`'/\t/g' item_info_20130203 > item_info_20130203_tab

or the more modern way
sed 's/'$(echo "\001")'/\t/g' item_info_20130203 > item_info_20130203_tab

or to affect the original file:
sed -i 's/'`echo "\001"`'/\t/g' item_info_20130203

If you are using GNU sed, you can use this:
sed -i 's/\x01/\t/g' item_info_20130203

A: According to this post, sed's -i option finds/replaces text in the original file, so the syntax > item_info_20120203_tab at the end of your command is a NOP and hence the output file is empty.


text:
Q: Convert dates to %y-%m-%d format in Python I have a csv file with column 'date' which has dates in many different formats like ddmmyy, mmddyy,yymmdd. I want to convert all the dates to y-m-d format
df=pd.read_csv(file)
df=df['date] .dt.strftime(%y-%m-%d)

This code gives error: "Can only use .dt accessor with datetimelike values"

A: You can utilise pd.to_datetime -
>>> import pandas as pd
>>>
>>> df = pd.DataFrame(['1/2/2020','12/31/2020','20-Jun-20'],columns=['Date'])
>>> df
         Date
0    1/2/2020
1  12/31/2020
2   20-Jun-20
>>>
>>> df['Date'] = pd.to_datetime(df['Date'])
>>> df
        Date
0 2020-01-02
1 2020-12-31
2 2020-06-20
>>>
>>> df['Date'] = pd.to_datetime(df['Date']).dt.strftime('%y-%m-%d')
>>>
>>> df
       Date
0  20-01-02
1  20-12-31
2  20-06-20
>>>

A: Step 0:-
Your dataframe:-
df=pd.read_csv('your file name.csv')

Step 1:-
firstly convert your 'date' column into datetime by using to_datetime() method:-
df['date']=pd.to_datetime(df['date'])

Step 2:-
And If you want to convert them in string like format Then use:-
df['date']=df['date'].astype(str)

Now if you print df or write df(if you are using jupyter notebook)
Output:-

0    2020-01-01
1    2020-12-31
2    2020-06-20


text:
Q: CMake file GLOB_RECURSE with complex globs I would like to use file(GLOB_RECURSE... as follows:
file(GLOB_RECURSE _tmp_files
     LIST_DIRECTORIES false
     "${mydir}/*.cpp|${mydir}/*.h")

This -- along with variations such as ${mydir}/*{.cpp,.h} -- yields an empty list.
However, this works as expected -- produces all the *.cpp files in the ${mydir} along with its subdirectories:
file(GLOB_RECURSE _tmp_files
     LIST_DIRECTORIES false
     "${mydir}/*.cpp")

So, does the file( feature in CMake indeed support "full" globbing? In particular, how to glob for a pattern {*.cpp,*.h} using file(?

A:
So, does the file( feature in CMake indeed support "full" globbing?

Yes.
Your expressions do not work the way you expect them to work. {..,..} is not a way to match multiple suffixes in glob, { , } are matched literally and have no special meaning in glob. "${mydir}/*.cpp|${mydir}/*.h" is not an OR in glob - | is matched literally, it has no special meaning in glob. See man 7 glob.

how to glob for a pattern {.cpp,.h} using file(?

Write it twice.
file(GLOB_RECURSE _tmp_files
     LIST_DIRECTORIES false
     ${mydir}/*.cpp
     ${mydir}/*.h
)


text:
Q: transform json content to object getSpecificData(par) {
return this.afd.list('products/products', ref => ref.orderByChild('par').equalTo(par)).valueChanges();
}

In my components, i have this:
export class Product {
  name: string;
  price: string;
  quantity: string;
}

ionViewDidLoad() {
    let aux =this.readData();
    console.log('Products', aux);
}
readData() {
    return this.firebaseService.getSpecificData(this.par).subscribe(
        items => {
            this.data = items,
            console.log('Data from Firebase ', this.data)
        }
    );
}

The "console.log('Data from Firebase ', this.data)" is printing data right, but "console.log('Products', aux);" is getting me undefined.
What i am doing wrong?
My aim is to iterate the array of data and transform each item into an object of type product.
Regards,

A: Your readData method doesn't return the actual records. Everything happens asynchronously, which is why it works within the subscribe handler (that bit only gets called when the asynchronous task has completed.
Quick timeline example:

*

*ionViewDidLoad()

*let aux = this.readData();

*readData()

*return this.firebaseService.getSpecificData(this.par).subscribe(

*);

*console.log('Products', aux); (TOO SOON!!!)

*(call to firebase getSpecificData completes)

*items => {

*this.data = items, This is the point where this.data receives the items

*console.log('Data from Firebase ', this.data)

*}

A: The explanation from Fenton is correctly.
I figure out the solution. Don't know yet if is the best solution, but it is working fine.
In my provider, i have the following code:
    export class Product {
    name: string;
    price: string;
    quantity: string;
    constructor(name: string, price: string, quantity: string) {
        this.name = name;
        this.price = name;
        this.quantity = quantity;
    }
}

    getSpecificData(par) {
    return this.afd.list('products/products', ref => ref.orderByChild('par').equalTo(par)).valueChanges().map(items => {
        let results = items.map(item => {
            return new Product(
                item.name,
                item.price,
                item.quantity
            );
        })
        return results;
    });
}

And im my component a have this:
readData() {
    this.firebaseService.getSpecificData(this.stock).map(
        data => {
            this.products = data;
        }
    ).subscribe();
}

It is working fine. I am reading the result in my html file.
<ion-col *ngFor=" let product of products" >
        {{product.name}}
</ion-col>


text:
Q: Select all single quotes in regex field I have this field in my JSON data:
"pinyin": "bei1 'ai1",
I just want to select any single quote ' like the one before ai1;
I tried this
(?<="pinyin": "\w*)\'+(?!")

but it didn't work

A: You can use
(?<="pinyin": "[\w\s]*)'(?!")

See this regex demo. Details:

*

*(?<="pinyin": "[\w\s]*) - a positive lookbehind that matches a location that is immediately preceded with "pinyin": " and then any zero or more word or whitespace chars

*' - a single quotation mark

*(?!")  - a negative lookahead that fails the match of there is a " char immediately to the right of the current location.


text:
Q: Configure proguard to exclude library jar which extends android.content.Context I'm integrating a library into a device for a project which is going to be embedded into the device OS. For this, we're integrating a library jar which overrides the Android framework Context.
Because of this, trying to enable Proguard for the app gives me the following error - "there were 220 instances of library classes depending on program classes".
All of these files are Widgets and Views. How can I fix this?
This is the content of my proguard-project.txt
-injars      bin/classes
-outjars     bin/classes-processed.jar
-libraryjars /Users/me/android-sdk-mac_86/platforms/android-15/android.jar
-libraryjars libs/library-that-overrides-context.jar

-keep public class * extends android.app.Activity
-keep public class * extends android.app.Application
-keep public class * extends android.app.Service
-keep public class * extends android.content.BroadcastReceiver
-keep public class * extends android.content.ContentProvider
-keep public class * extends android.content.Context

This is the content of my proguard-android.txt
# This is a configuration file for ProGuard.
# http://proguard.sourceforge.net/index.html#manual/usage.html

-dontusemixedcaseclassnames
-dontskipnonpubliclibraryclasses
-verbose

# Optimization is turned off by default. Dex does not like code run
# through the ProGuard optimize and preverify steps (and performs some
# of these optimizations on its own).
-dontoptimize
-dontpreverify
# Note that if you want to enable optimization, you cannot just
# include optimization flags in your own project configuration file;
# instead you will need to point to the
# "proguard-android-optimize.txt" file instead of this one from your
# project.properties file.

-keepattributes *Annotation*
-keep public class com.google.vending.licensing.ILicensingService
-keep public class com.android.vending.licensing.ILicensingService

# For native methods, see http://proguard.sourceforge.net/manual/examples.html#native
-keepclasseswithmembernames class * {
    native <methods>;
}

# keep setters in Views so that animations can still work.
# see http://proguard.sourceforge.net/manual/examples.html#beans
-keepclassmembers public class * extends android.view.View {
   void set*(***);
   *** get*();
}

# We want to keep methods in Activity that could be used in the XML attribute onClick
-keepclassmembers class * extends android.app.Activity {
   public void *(android.view.View);
}

# For enumeration classes, see http://proguard.sourceforge.net/manual/examples.html#enumerations
-keepclassmembers enum * {
    public static **[] values();
    public static ** valueOf(java.lang.String);
}

-keep class * implements android.os.Parcelable {
  public static final android.os.Parcelable$Creator *;
}

-keepclassmembers class **.R$* {
    public static <fields>;
}

# The support library contains references to newer platform versions.
# Don't warn about those in case this app is linking against an older
# platform version.  We know about them, and they are safe.
-dontwarn android.support.**

A: The Android Ant/Eclipse builds automatically specify all necessary -injars/-outjars/-libraryjars options for you. You should only specify these options if you have a custom build process. Otherwise, you'll get lots of warnings about duplicate classes and possibly other problems.
If you do need to specify -injars/-outjars/-libraryjars options, classes specified with -injars can depend on classes specified with -libraryjars, but not the other way around. Cfr. ProGuard manual > Troubleshooting > Warning: library class ... depends on program class ...

A: Even if I'd marked my library as a libraryjar, I also had to add the lines
-keep public class android.content.** { *; } to the project proguard config file to fix the issues.


text:
Q: Neo4J is it ok to use two create statements in the same query? I couldn't find documentation about it anywhere, but I need to build a query that should create a new node and 3 new relationships between that node and other existing ones.
So, I used one create statement to create two relationships, and then another beneath to create the third.
So, is it correct to use two and more create statements, or is there a better way to achieve it?
My code:
match (p1:Person{name:'David'})
match (movie:Movie{title:'Harry Potter'})
create (p1)-[:KNOWS]->(p2:Person{name:'Ronald'})-[:ACTED_IN]->(movie)
create (p2)-[:KNOWS]->(p1)
return p1, p2, movie

A: Yes, it's ok to use multiple "CREATE" statements in the same query. In the Cypher Refcard, under the "Write-only query structure" section, you can see:

(CREATE | MERGE)*

which means: zero (or more) "CREATE" or "MERGE" statements is allowed


text:
Q: Server-sent events: How do you automatically reconnect in a cross-browser way? I implement some code to query the database for any changes and to send an event.
Here's the code of my PHP script
header("Content-Type: text/event-stream");
header('Cache-Control: no-cache');

//****Some code here to query the database

echo "event: message\n";
echo "data: change_from_database \n";
echo "\n\n";
ob_flush();
flush();

I'm relying on the browser to automatically reconnect each time the connection closes, so I don't implement any loop on my server code. In addition, I learned from this thread that implementing an infinite loop has many disadvantages.
So everything works fine client-side: the browser reconnects each time the connection closes and an event is fired each time the server sends one; well except for Firefox (40.0.2) which doesn't reconnect. I know it doesn't because I wrote some JavaScript error checking code to test this:
var evtSource = new EventSource("../sse.php");
evtSource.onerror = function(event){
    var txt;
    switch( event.target.readyState ){
    case EventSource.CONNECTING:
        txt = 'Reconnecting...';
        break;
    }
    console.log(txt);
}

So after like each second, the console on chrome for example logs "Reconnecting". Firefox on the other hand reconnects once and never does so again.
How do I write code to make this work on Firefox, and perhaps other browsers which support server-sent events but don't reconnect automatically?

A: With the recent version of the Firefox browser (44.0.2), your code works perfectly. However, you can reinitialize your EventSource object in the error handler like this:
var evtSource = new EventSource("../sse.php");
var evtSourceErrorHandler = function(event){
    var txt;
    switch( event.target.readyState ){
        case EventSource.CONNECTING:
            txt = 'Reconnecting...';
            break;
        case EventSource.CLOSED:
            txt = 'Reinitializing...';
            evtSource = new EventSource("../sse.php");
            evtSource.onerror = evtSourceErrorHandler;
            break;
    }
    console.log(txt);
}

But I strongly do not recommend you to do this because your code doesn't use benefits of keeping the connection alive (as you wrote, you are aware of infinite loop) so browser does simple polling (you can see this in then network tab). I don't see any reason to use SSE over AJAX without keeping a permanent connection, which is obviously hard to maintain with PHP. So I assume using simple AJAX polling in this situation.

A: You could use a polyfill like this one  https://github.com/Yaffle/EventSource which should add the event source functionality to unsupported browsers.

A: Ran a test with your code on my site and everything works as expected with Firefox 44.0.2 and php 5.5. I did run into something interesting on the Mozilla dev network though that states you can't necessarily tell what the error message was on Firefox past v22. Perhaps your switch statement in the error checking that is what's letting you down. Here's a link to the article. Check out the error handling section.
My php code is identical to yours. Just in case I did something different, here's my html code.
<!DOCTYPE>
<html>
<head>
    <title>SSE Test</title>
    <meta charset="utf-8" />
    <script>
      var evtSource = new EventSource("sse.php");
      evtSource.onerror = function(event){
        var txt;
        switch( event.target.readyState ){
           case EventSource.CONNECTING:
               txt = 'Reconnecting...';
               break;
        }
        console.log(txt);
      };
    </script>
  </head>
  <body></body>
</html>


text:
Q: optaplnner score which contraints are not satisfied I am exploring optaplanner,i found that it gives me one best solution along with some score value like -4Hard/-3hard.
I want to get more information regarding this score like list the hard and soft constraints which was not satisfied in given solution,so that user is able to change the constraints slightly to get even better solution.
Is it possible in optaplanner and if yes, how?

A: Your hard/soft scores are depending from your implementation.
Take CloudBalancingEasyScoreCalculator (see docs) from examples in Optaplanner.
You see that scores are in fact cumulated sums.
Optaplanner has no chance to know the detail of each constraint considered within that sum.
Nowhere a set of constraints is defined. We just gather them as a global objective.
Solution 1 : In such case, solution is to track yourself unrespected constraints when computing your score.
On same example, you would insert this processing here:
        // Hard constraints

        int cpuPowerAvailable = computer.getCpuPower() - cpuPowerUsage;

        if (cpuPowerAvailable < 0) {

            hardScore += cpuPowerAvailable;

            cloudbalance.trackUnrespectedHardConstraint(...)

        }

instead of
        // Hard constraints

        int cpuPowerAvailable = computer.getCpuPower() - cpuPowerUsage;

        if (cpuPowerAvailable < 0) {

            hardScore += cpuPowerAvailable;

        }

I didn't explore Drools score configuration that may be a solution 2 for your need.
Hope this helps.
ThePolyscope.com


text:
Q: MC3635 Accelerometer SPI Interrupt Pin Question I am using MC3635 Evaluation Board(EV3635B). There is no problem about SPI connection and i can read X,Y,Z movement via SPI. But i can not use interrupt pin as output. I want that let interrupt pin of the accelerometer give me HIGH when there is a tapping or movement and let me turn this interrupt pin LOW via SPI when i read this changing. Because i am trying to wake my microcontroller by this movement. Additionally i am using PIC12LF1822 but it is not a necessary information. Could you help me to configure the registers of the accelerometer?
Best regards.


text:
Q: Caret disappears after CKEditor is hidden in Firefox Problem: If CKEditor instance is hidden, when it is exposed again, the caret is invisible.  Firefox only.
We noticed the cursor disappearing problem when switching tabs in our app.  After returning to the CKEditor tab, the cursor is gone.  Typing still inserts text.
Narrowed it down to: If you set the style of the element containing the CKEditor instance to display:none, and then display:block, the problem reproduces.

A: Here's a viable solution for posterity, better than re-creating the entire editor: set the <body> element of the editor to contenteditable="false" and then back to true, the cursor reappears.
From: http://cksource.com/forums/viewtopic.php?f=11&t=21787


text:
Q: How to add number to the unsigned dword with 31bit set to 1 in assembly so it wouldn't be treated as negative? I am trying to add 5 to 3234567890 in MASM32.
Here is the full sample code:
;--------------------------------------------------------------------------
include \masm32\include\masm32rt.inc
.data
;--------------------------------------------------------------------------
.code

start:
call main                   ; branch to the "main" procedure
exit
main proc
local pbuf: DWORD
local buffer[32]: BYTE

mov pbuf, ptr$(buffer)

mov ecx, uval("5") ; converting string to unsigned dword and storing in ecx
mov ebx, uval("3234567890") ;  converting string to unsigned dword and storing in ebx

invoke udw2str, ebx, pbuf ; converting unsigned value to string and storing results in pbuf
print pbuf, 13,10 ; everything is fine so far - 3234567890

add ecx, ebx

invoke udw2str, ebx, pbuf ; once again coverting
print pbuf, 13,10 ; negative number

ret

main endp
end start                       ; Tell MASM where the program ends

What is the right way to add something to the unsigned dword?
Right now i am getting negative number and expected result is 3234567895.
Update:
Problem was indeed somewhere in the MACRO used. I've edited sample to the bare minimum and it worked correctly.  No mystery here. :)
;--------------------------------------------------------------------------
include \masm32\include\masm32rt.inc
.data
;--------------------------------------------------------------------------
.code

start:
call main                   ; branch to the "main" procedure
exit
main proc
local pbuf: DWORD
local buffer[40]: BYTE
local nNumber: DWORD

mov pbuf, ptr$(buffer)

mov ecx, 5 ; no need to convert anything at this point
mov ebx, 3234567890 ;  no need to convert anything at this point

add ebx, ecx

invoke udw2str, ebx, pbuf ; now converting result in ebx to the string (pointed by pbuf)
print pbuf, 13, 10 ; printing pbuf, success

ret

main endp
end start                       ; Tell MASM where the program ends

Thanks everyone!

A: At this level, signed and unsigned are really the same thing, except for multiply and divide instructions, so the addition is not at fault here.
Possible problems I can think of:

*

*is the result of the addition really in ebx? There is significant confusion about which operand is the destination register, as there are two different conventions in widespread use? (even if that is part of the problem, it doesn't really explain the result, as that would give 5, not a negative number, but still...)

*this forum post talks about an implementation issue in udw2str.

*you are using pbuf as the output buffer, but that is not large enough. You are relying on the assembler placing it in memory immediately before buffer.

*does print perhaps clobber ebx?
I'd pull out my trusty debugger at this point and single-step through the code.


text:
Q: Why removing the variable from the object's class during deserialization doesn't throw an Exception? Why removing the variable from the object's class during deserialization doesn't throw an Exception? What does the "incompatible" changes mean in Serialization then?
I have also changed the field of the class from non-static to static which according to Java Specifications
is incompatible.

A:
Why removing the variable from the object's class during deserialization doesn't throw an Exception?

Because it isn't supposed to. See the Object Versioning Specification, #5.6.1:

"Deleting fields - If a field is deleted in a class, the stream written will not contain its value. When the stream is read by an earlier class, the value of the field will be set to the default value because no value is available in the stream. However, this default value may adversely impair the ability of the earlier version to fulfill its contract."

and

"Changing a nonstatic field to static or a nontransient field to transient - When relying on default serialization, this change is equivalent to deleting a field from the class. This version of the class will not write that data to the stream, so it will not be available to be read by earlier versions of the class. As when deleting a field, the field of the earlier version will be initialized to the default value, which can cause the class to fail in unexpected ways."

Nothing there about throwing exceptions.

A: *

*I got such doubt in an RPC call, and I seemed to have found the answer.

*I added two fields and changed one field type of a class in the server-side, then the client-side calls a method which returns the old version class. First, I got an exception for the unmatched filed type, so I fixed this but leave the added fields, it works well, it confused me.

*Then I came here, I haved read the specification:

*

*5.6.1 Incompatible Changes - Deleting fields

*5.6.2 Compatible Changes - Adding fields

*They talk about the same thing - the serialized byte codes do not contain the field of the deserializing object, while our codition is that the serialized byte codes contains some fileds but the deserializing object does not.

*As I understand:

*

*From the consideration of design, such deserialization feature is very useful especially in an RPC call, serialization function should contain it.

*Deep into the principle, deserialization instantiates an object of the client-side class(old version) and sets values of its fields(probabaly uses reflect to got a value of a field from the serialized byte codes), the redundant field in the serialized byte codes sits silently with no visiting.


text:
Q: AngularJS/Ionic - NG Selected based on item value Solved
I'm using a form control group, so one must set the default value via that, like so:
this.data.get('selectedSite').setValue(oldActive)

Hope this helps someone!

I'm binding an array to an ion-select component with the following code:
<ion-select formControlName="selectedSite" >
    <ion-option color="light" *ngFor="let site of sites" value="{{site.site}}" ng-selected="site.active == '1'">{{site.site}}</ion-option>
</ion-select>

Where the the site has a 1, for active, the site should be selected by default. Then array is constructed like so:
this.sql.query('SELECT site,active FROM Site_tbl ORDER BY site ASC').then((res) => {
    for (var i = 0; i < res.res.rows.length; i++) {
        this.sites.push({ site: res.res.rows.item(i).site, active: res.res.rows.item(i).active })
    }
})

And the resultant array looks like this:
Array[44]
   0: Object
       active: 0
       site: "Site 1"
   1: Object
       active: 1
       site: "Site 2"
   2: Object
       active: 0
       site: "Site 3"
   ....

So in this case, Site 2 should be selected. The list of sites is bound to the list succesfully, I can see their names in the list (the ngFor repeat works in that regard) but the ng-selected condition seems to have no effect, the box select box shows as empty by default, rather than showing the selected (active) site.
Basic problem, but I've tried everything I can think of, help would be greatly appreciated!

A: You forgot to add the double curly braces in your ng-selected expression. It should read:
<ion-select formControlName="selectedSite" >
    <ion-option color="light" *ngFor="let site of sites"
     value="{{site.site}}" ng-selected="{{site.active}}">{{site.site}}</ion-option>
</ion-select>


text:
Q: How to force 32bit app to use a 64bit COM dll in CreateObject? The following code behaves differently depending on if I use the 32 or 64 bit version of wscript:
Set oSQLServer = CreateObject("SQLDMO.SQLServer")

For Each o in oSQLServer.ListInstalledInstances
    MsgBox o
Next

In 32 bit, it will list the instances of my 32bit server (SQL Server 2000), in 64 bit I get the contents of my 64bit server (SQL Server 2008).
I need to convert this code to C++ (a 32 bit application).  But I need to show the 64bit servers.  How do I force the created object to use the 64bit dll and 64bit key in the registry?

A: A 32-bit app cannot load a 64-bit DLL, and a 64-bit app cannot load a 32-bit DLL.

A: I've decided to use ODBC's SQLBrowseConnect with the connection string
"DRIVER={SQL Server Native Client 10.0};".

SQLDMO is well and truely dead, and SQLSMO is rather short-sightedly for managed applications only.


text:
Q: LNA circuit: why is the inductor causing a voltage and current drop? I am designing the following circuit whose schematic and testbench I put below:

I performed a DC bias analysis.
Theoretically, I would expect that at DC the inductor would be a short-circuit and the capacitor would be an open-circuit, so the current on the voltage source to be equal to the current on the drain of thetransistor. What I found is that the current on the source is 30 mA while the drain current of the transistor has only a current of 29.77 mA. I would also expect the drain voltage of the transistor to be 3.3 V, verifying however that it is just 2.821 V so there is almost a 0.5 V voltage drop on the inductor.
Can someone please help me understand how I can justify this? What non-ideality is playing here? Is the inductor actually a small resistor? Where is the current leakage? Is it to the bulk terminal of the inductor?

A: Your inductor has a resistance of 16 ohms. That seems high. What simulation tool are you using? I don't have enough remaining life to spend decoding your schematic, but it looks like you're modeling some sort of FET as an inductor. I suspect that has some associated series resistance, perhaps you could figure out what's going on there.


text:
Q: Adding HTML elements in the JSON data Following is my JSON Data validated using JSONLint:
[{
"text": "Products",
"data": {},
"children": [{
    "text": "Fruit",
    "data": {
        "price": "",
        "quantity": "",
        "AddItem": "+",
        "RemoveItem": "&#215"
    },
    "children": [{
        "text": "Apple",
        "data": {
            "price": 0.1,
            "quantity": 20,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Strawberry",
        "data": {
            "price": 0.15,
            "quantity": 32,
            "AddItem": "+",
            "RemoveItem": "& #215"
        }
    }],
    "state": {
        "opened": false
    }
}, {
    "text": "Vegetables",
    "data": {
        "price": "",
        "quantity": "",
        "AddItem": "&# 43;",
        "RemoveItem": "&#215"
    },
    "children": [{
        "text": "Aubergine",
        "data": {
            "price": 0.5,
            "quantity": 8,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Cauliflower",
        "data": {
            "price": 0.45,
            "quantity": 18,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }, {
        "text": "Potato",
        "data": {
            "price": 0.2,
            "quantity": 38,
            "AddItem": "+",
            "RemoveItem": "&#215"
        }
    }]
}],
"state": {
    "opened": false
}
}]

What I am looking for is to convert the value for the keys AddItem and RemoveItem to HTML buttons.
The above JSON will be used to render nodes in a jsTree plugin.
jsFiddle link where I will be using this json data. Basically, I want to replace my + and - sign with a button for the same
Does anyone has a work-around for this ?
Edit 1: I have read at a few places that adding HTML elements directly in your JSON data is not advisable as it can be used at a  number of places in your code and each time it may have a different HTML for it. If someone has a better way to do it, that would be great.

A: I have never used the jsTree plugin and there is probably a better way to solve your problem, but this seems to do what i think your looking for.  Just add this to the end of your code.
$(document).on('click','.jstree-table-wrapper', function() {//insted of document i would used jtrees containing div
    $.each($('.jstree-table-cell span'),function(){
        if($(this).html()=='+'){
            $(this).html('<button class="addBtn">+</button>')
        }else if($(this).html()=='×'){
            $(this).html('<button class="removeBtn">x</button>')
        }
    });
});

$(document).on('click','.addBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_create(id);
     $('.jstree-table-wrapper').trigger('click');
});

$(document).on('click','.removeBtn',function(){//insted of document i would used jtrees containing div
     var id = 'j1_'+$(this).parent().parent().attr('id').split('_')[2];
     demo_delete(id);//you might need to work on your delete function
     $('.jstree-table-wrapper').trigger('click');
});


text:
Q: Why cout doesn't work with pthreads? I'm trying out a simple program to test multi-threading.  I just print a series of "x" and "O" in alternate threads. Now, if I use cout , no output is seen on screen.  If I use fputc and output to stderr , it works fine.  Why is cout (output to stdout) not working here ?
My code is given below :
#include <iostream>
#include <pthread.h>
#include <unistd.h>
#include <stdio.h>

using namespace std;

static int count;

void* print_xs(void *unused)
{
    while(1)
    {
        if (count >=100) break;
        if (count%2==0)
        {
            count++;
            cout<<"X=";  // no output here
            fputc('X',stderr); // works !
        }
        else
        {
            sleep(1);
        }
    }
    return NULL;

}

int main()
{
    pthread_t tid;
    pthread_create(&tid,NULL,&print_xs, NULL);

    while(1)
    {
        if (count >=100) break;
        if (count%2!=0)
        {
            count++;
            cout<<"O="; // no output here
            fputc('O',stderr); // works !
        }
        else
        {
            sleep(1);
        }
    }

    pthread_join(tid,NULL);
    return (0);

}

A: Since std::cout is a buffered-stream, you need to flush it in order to send the buffer to the standard output.
Just try something like:
cout<< "O=";
cout.flush();

That should work.
Additional notes

*

*As some comments have already suggest you, std::cout is not thread-safe in C++03 and before. It could be useful to protect that object with a mutex.
This could be not a problem since C++11 standard.

The FDIS says the following in §27.4.1 [iostream.objects.overview]:

Concurrent access to a synchronized (§27.5.3.4) standard iostream object's formatted and unformatted input (§27.7.2.1) and output (§27.7.3.1) functions or a standard C stream by multiple threads shall not result in a data race (§1.10). [ Note: Users must still synchronize concurrent use of these objects and streams by multiple threads if they wish to avoid interleaved characters. — end note ]

That means without mutex it's guaranteed the object will not corrupted in a data-race context. But the problem on overlapped output remains. So if you be sure each line is printed without overlap by another thread, you still need a mutex.

*C++11 has introduces a multi-thread library (often is a wrapper for pthread). Here some reference. Just take a look at, you could find it useful.


text:
Q: remotely start Python program in background I need to use fabfile to remotely start some program in remote boxes from time to time, and get the results. Since the program takes a long while to finish, I wish to make it run in background and so I dont need to wait. So I tried os.fork() to make it work. The problem is that when I ssh to the remote box, and run the program with os.fork() there, the program can work in background fine, but when I tried to use fabfile's run, sudo to start the program remotely, os.fork() cannot work, the program just die silently. So I switched to Python-daemon to daemonalize the program. For a great while, it worked perfectly. But now when I started to make my program to read some Python shelve dicts, python-daemon cannot work any longer. Seems like if you use python-daemon, the shelve dicts cannot be loaded correctly, which I dont know why. Anyone has an idea besides os.fork() and Python-daemon, what else can I try to solve my problem?

A: If I understand your question right, I think you're making this far too complicated.  os.fork() is for multiprocessing, not for running a program in the background.
Let's say for the sake of discussion that you wanted to run program.sh and collect what it sends to standard output.  To do this with fabric, create locally:
fabfile.py:
from fabric.api import run
def runmyprogram():
    run('./program.sh > output 2> /dev/null < /dev/null &')

Then, locally, run:
fab -H remotebox runmyprogram

The program will execute remotely, but fabric will not wait for it to finish.  You'll need to harvest the output files later, perhaps using scp.  The "&" makes this run in the background on the remote machine, and output redirection is necessary to avoid a hung fabric session.
If you don't need to use fabric, there are easier ways of doing this.  You can ssh individually and run
nohup ./program.sh > output &

then come back later to check output.
If this is something that you'll do on a regular basis, this might be the better option, since you can just set up a cron job to run every so often, and then collect the output whenever you want.
If you'd rather not harvest the output files later, you can use:
fabfile.py:
from fabric.api import run
def runmyprogram():
    run('./program.sh')

Then, on your local machine:
fab -H remotebox runmyprogram > output &

The jobs will run remotely, and put all their output back into the local output file.  This runs in the background on your local machine, so you can do other things.  However, if the connection between your local and remote machines might be interrupted, it's better to use the first approach so the output is always safely stored on the remote machines.

A: For those who came across this post in the future. Python-daemon can still work. It is just that be sure to load the shelve dicts within the same process. So previously the shelve dicts is loaded in parent process, when python-daemon spawns a child process, the dict handler is not passed correctly. When we fix this, everything works again.
Thanks for those suggesting valuable comments on this thread!


text: Q: Are there an infinite number of primes of the form 133...331? The first 5 primes of this form are of lengths 3, 5, 7, 95, and 161 (131, 13331, 1333331, etc.). Can it be shown there are an infinite number of primes with form 133...331? Can it be shown there are only a finite number of them?


text:
Q: Open Xen Manager and XenCenter server connection So, I've got server set up and running the Xen hypervisor version 4.1 with Debian Wheezy (7.5.0) as the host OS, along with xcp-xapi and all services running correctly. Problems arise when I try to connect to the server through Open Xen Manager or XenCenter.
Open Xen Manager gives me this error message:
[Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions

XenCenter gives me this error message:
Unable to connecto server '192.168.178.21'
The connection was refused.

Check that XenServer is configured correctly on '192.168.178.21' and try again.

And I also get a connection refused error if I use the Open Xen Manager installed locally. I'm able to connect to the server over SSH.
I'm at a loss as to what to try to solve this issue.

A: Figured out my problem. An IP conflict. :( Wonderful.


text:
Q: Does equality of (weak) gradients imply equality of functions up to a constant? This seems like a pretty basic question, but I can't figure it out.
Suppose we have two measurable functions, $u$ and $v$, whose (weak) partial derivatives are all well defined, and we have $\partial_i u = \partial_i v$ for each $i$. Can we then conclude that $u=v+C$ for some constant $C$?
Note: I'm mainly interested in the weak case but I couldn't think of a proof in the classical setting either.

A: For the classical case, suppose $\varphi \in C^\infty (U)$, where $U\subset \mathbb R^n$ is a connected open domain. If $D_i \varphi = 0$ for all $i$, then $\varphi$ must be constant. Indeed, if $x_1$, $x_2$ are two points in $\Omega$, and $\gamma \subset \Omega$ is a path connecting them, then
$$ \varphi(x_2) - \varphi(x_1) =\int_\gamma D_i \varphi.dx_i = 0.$$
For the weak case, suppose $u \in L^1_{\rm loc}(U)$, and suppose that $D_i u \in L^1_{\rm loc}(U)$ ($i \in \{1, \dots, n \}$) are its weak derivatives. I think the trick here is to reduce to the classical case, by considering mollifications of $u$, which are smooth functions. Indeed, if $\eta_\epsilon (x) = \frac C {\epsilon^n}\exp\left(\frac{1}{|x/\epsilon|^2 - 1}\right) \mathbf 1_{|x| < 1}$ is the mollifying bump function, then the convolution $u \star \eta_\epsilon $ is in $C^{\infty} (U_\epsilon)$ (where $U_\epsilon = \{ x \in U : {\rm dist}(x,\partial U) > \epsilon \}$). This is proved in Evans, C.4 Theorem 7, p.714. It is also proved on the same page of Evans that $u \star \eta_\epsilon $ tends to $u$ pointwise almost everywhere in $U$ as $\epsilon \to 0$. Also, the weak derivative of the mollification is equal to the mollification of the weak derivative, $D_i(u \star \eta_\epsilon )=(D_iu)\star \eta_\epsilon$ on $U_\epsilon$ (see Evans 5.3 Theorem 1, p.264). So if the weak derivative $D_i u$ vanishes on $U$, then $D_i(u \star \eta_\epsilon) = 0$, hence $u \star \eta_\epsilon$ is constant on $U_\epsilon$ by the classical case. Taking the limit $\epsilon \to 0$, we have that $u$ is constant almost everywhere on $U$.


text:
Q: Ubuntu 22.04 takes 2.5 minutes to login (not BOOT) I updated from Ubuntu 20.04 to 22.04 and login went up from almost instantly in Ubuntu 20 to 2.5 minutes in Ubuntu 22!!!
Booting takes longer as well (appr. 50 secs.) Normally all start-up text races by, but now the following text stays on screen for about 20 secs.
Running /scripts/local-premount

It's the user login that takes 2:15 where only my backdrop is visible.
I have a Asus P8Z77-V MB (some 10 yrs old). Processor Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz
Memory 16066MB (3188MB used)
Kernel Linux 5.15.0-37-generic (x86_64) Version #39-Ubuntu SMP Wed Jun 1 19:16:45 UTC 2022
C Library GNU C Library / (Ubuntu GLIBC 2.35-0ubuntu3) 2.35
Distribution Ubuntu 22.04 LTS
Mesa Intel(R) HD Graphics 4000 (IVB GT2) Version 3.1 Mesa 22.0.1
I wanted to check logs, but don't know which and what to look for.
No NVidia card.
Any help appreciated.
Thanks
EDIT1
During 1st upgrade from 20.04 to 22.04 the installer stopped because I didn't have enough space on my / (root) partion (30GB).
I started a Live Linux version from an USB stick and used Gparted to resize the Ext4 root partition with an extra 30 GB. This went all without problems and so did the following update to 22.04.
I have the following partitions on my 128 GB SSD:
sda1  : fat32 /boot/efi    190MB
sda2  : ext4  /boot        572MB
sda3  : ext4  /            58.59GB  (was appr. 30GB before resizing)
Furthermore 2 small data partitions:
sda4 : ext4 LUKS encrypted
sda5 : ext4 data
My home directory is on a 1TB standard harddrive (sdb)
Below I've included output from system-analyze
$ systemd-analyze
Startup finished in 2.717s (firmware) + 4.301s (loader) + 34.923s (kernel) + 6.285s (userspace) = 48.228s
graphical.target reached after 6.278s in userspace

$ systemd-analyze blame
3.579s NetworkManager-wait-online.service
1.531s snapd.service
1.163s dev-sda3.device
 998ms udisks2.service
 940ms dev-loop12.device
 939ms dev-loop13.device
 939ms dev-loop11.device
 939ms dev-loop10.device
 935ms dev-loop8.device
 935ms dev-loop9.device
 933ms dev-loop15.device
 929ms dev-loop14.device
 829ms blueman-mechanism.service
 762ms dev-loop1.device
 761ms dev-loop4.device
 760ms dev-loop5.device
 760ms dev-loop7.device
 742ms dev-loop3.device
 730ms dev-loop6.device
 710ms dev-loop2.device
 687ms dev-loop0.device
 672ms snapd.seeded.service
 626ms smartmontools.service
 574ms cups.service
 543ms user@1000.service
 502ms accounts-daemon.service
 463ms networkd-dispatcher.service
 421ms ModemManager.service
 290ms systemd-resolved.service
 260ms polkit.service
 258ms systemd-journal-flush.service
 242ms NetworkManager.service
 242ms avahi-daemon.service
 238ms systemd-timesyncd.service
 203ms nginx.service
 190ms systemd-rfkill.service
 190ms gpu-manager.service
 163ms thermald.service
 160ms apparmor.service
 159ms wpa_supplicant.service
 159ms systemd-logind.service
 156ms e2scrub_reap.service
 150ms apport.service
 149ms secureboot-db.service
 141ms systemd-udev-trigger.service
 135ms systemd-udevd.service
 133ms grub-common.service
 127ms colord.service
 121ms snapd.apparmor.service
 119ms alsa-restore.service
 108ms rsyslog.service
 107ms resolvconf-pull-resolved.service
 105ms systemd-fsck@dev-mapper-fedora\x2dhome.service
 104ms systemd-journald.service
 104ms keyboard-setup.service
 102ms lightdm.service
 100ms upower.service
  86ms lm-sensors.service
  85ms lvm2-monitor.service
  82ms lvm2-pvscan@8:18.service
  82ms systemd-modules-load.service
  73ms sys-kernel-tracing.mount
  73ms sys-kernel-debug.mount
  72ms dev-mqueue.mount
  72ms dev-hugepages.mount
  69ms modprobe@fuse.service
  67ms kmod-static-nodes.service
  65ms modprobe@drm.service
  65ms modprobe@configfs.service
  65ms snap-bare-5.mount
  64ms virtualbox.service
  62ms WiLiShare.mount
  62ms snap-chromium-2000.mount


text:
Q: goto keyword in java Why is the goto keyword in java reserved though it is not used?
EDIT : Just to rephrase the question once again to avoid the ambiguity, I understand goto functionality is not supported in java and also understand that it makes code difficult to read. But its not supported, so then why make it reserved. It can be used as variable names atleast


text:
Q: @ManyToOne retrieve objects that contain a partial key using @JoinColumnOrFormula I'm having trouble using @JoinColumnOrFormula to retrieve specific data using a part of a key.
Let's try to explain the context.
There are two tables in the database that don't have dependency each other.
Here are the definition of those tables:

    @Entity
    @Table(name = "table_A")
    @IdClass(TableAPK.class)
    public class TableA {

        @Id
        @Column(name = "tableA_key")
        private String key;

        @Id
        @Column(name = "tableA_product")
        private String product;

        @Id
        @Column(name = "tableA_territory")
        private String territory;

        @Column(name = "tableA_description")
        private String description;

        @OneToMany(fetch = FetchType.EAGER, targetEntity = TableB.class)
        private List listTableB;

        // getter/setter
    }

    @IdClass(TableAPK.class)
    public class TableAPK implements Serializable {

        private static final long serialVersionUID = -6343683597717600643L;

        private String key;

        private String product;

        private String territory;

        // getter/setter
    }

    @Entity
    @Table(name = "table_B")
    @IdClass(TableBPK.class)
    public class TableB {

        @Id
        @Column(name = "tableB_key")
        private String key;

        @Id
        @Column(name = "tableB_product")
        private String product;

        @Id
        @Column(name = "tableB_region")
        private String region;

        @Column(name = "tableB_description")
        private String description;

        @ManyToOne(targetEntity = TableA.class)
        @JoinColumnsOrFormulas(value = {
          @JoinColumnOrFormula(column = @JoinColumn(name = "tableB_key", referencedColumnName = "tableA_key", insertable = false, updatable = false, nullable = false)),
          @JoinColumnOrFormula(column = @JoinColumn(name = "tableB_product", referencedColumnName = "tableA_product", insertable = false, updatable = false, nullable = false)),
          @JoinColumnOrFormula(formula = @JoinFormula(value = "????", referencedColumnName = "????"))
        })
        private TableA tableA;

        // getter/setter
    }

    @IdClass(TableBPK.class)
    public class TableBPK implements Serializable {

        private static final long serialVersionUID = -6343683597717600643L;

        private String key;

        private String product;

        private String region;

        // getter/setter
    }

As you can see TableAPK and TableBPK the primary keys are not composed by the same attributes.

    List listElements = em.createQuery("FROM TableA WHERE key = :key ORDER BY territory", TableA.class).setParameter("key", key).getResultList();

This query should returns a list TableA objects according to the key provided. Each TableA has a list of TableB which match key, product and region that is part of the key.
The key is a string that looks like this "territory_region_product_xxxx"
How can I retrieve the list of TableB that will contain 'table_B.tableB_region' in 'table_A.tableA_key'?
For instance table_A.tableA_key has
"territoryA_regionA_productA_xxxx"
"territoryA_regionA_productA_xxxx"
"territoryA_regionB_productA_xxxx"
"territoryA_regionB_productA_xxxx"
and table_B.tableB_region has
"regionA"
In this case how can I get the two first row?
How can I implement this using @JoinFormula?
Is @JoinColumnsOrFormulas a good solution in this case?
Any advice is welcome.


text:
Q: How to code Stream.findNth()? Similar to Stream.findFirst(), is there a way to write Stream.findNth()?
I'm practicing Java 8 by rewriting some legacy code. And, I'm wondering how the below function can be written using Stream API.
static curPipeNumber = 0;

/** skipToEntry() updates 'curPipeNumber' to 'pipeNumber' and returns the first byte position of the word before the ('pipeNumber')-th pipe.
 * It does so by reading and ignoring unnecessary bytes from the buffer.
 * e.g.,
 */
static int skipToEntry(byte[] buf, int len, int nextByteToBeRead, int pipeNumber) {

    if(curPipeNumber == pipeNumber)
        return nextByteToBeRead;

    for(; nextByteToBeRead < len; nextByteToBeRead++) {
        if(buf[nextByteToBeRead] == '|') {
            ++curPipeNumber;
            if(curPipeNumber == pipeNumber) {
                return ++nextByteToBeRead;
            }
        }
    }

    return nextByteToBeRead;
}

I'm hoping it would translate to something like:
static int skipToEntry(byte[] buf, int len, int nextByteToBeRead, int pipeNumber) {
    if(curPipeNumber == pipeNumber)
        return nextByteToBeRead;

    OptionalInt pipeIndex = IntStream.range(i, len)
             .filter(n -> buf[n] == '|')
                 .findNth(pipeNumber);

            curPipeNumber = pipeNumber;
            nextByteToBeRead = pipeIndex.getAsInt() + 1;

    return nextByteToBeRead;
}

A: OptionalInt result = stream.skip(n-1).findFirst();


text:
Q: nginx websocket handshake doesnt work, wrong configuration? i have a php script which only have some function like get some content or post a file to the server.
now i am trying to open a websocket with JS. But i got everytime that the handshake wouldnt work.
new WebSocket('myDomain.com')
WebSocket connection to 'ws://mydomain.com/ws' failed: Error during WebSocket handshake: Unexpected response code: 200
I am not sure, what is going wrong.
server {
        listen 80;
        root /var/www/html;
        index index.php index.html index.htm index.nginx-debian.html;
#    listen 80 default_server;
#    listen [::]:80 default_server;
#    root /var/www/html;
    server_name  mydomain.com;

#  index index.php index.html index.htm index.nginx-debian.html;

    listen 443 ssl; # managed by Certbot

    # RSA certificate
    ssl_certificate /etc/letsencrypt/live/mydomain.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/mydomain.com/privkey.pem; # managed by Certbot

    include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
    }
    location / {
                try_files $uri $uri/ =404;
#      proxy_set_header Upgrade $http_upgrade;
#      proxy_set_header Connection $connection_upgrade;

    }

}

A: Seems like a websocket server is missing in the setup.
It should be binding to a port somewhere independent of nginx.
The relevant nginx setting should look similar to this:
    location /ws {
        proxy_pass http://localhost:8123/websocket;

        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection "upgrade";
    }

Your php script likely needs to be expanded into a php websocket server.
You can read up on it here:
How to create websockets server in PHP


text:
Q: Change HTTP response in ASP.NET WebApi I am trying to implement server for issuing web tokens using ASP.NET WebApi. I've found great tutorial on how to do this step by step, and everything is working fine, except I need to change some values in HTTP response.
This is a picture of a call where user credentials are checked and if user exists in database he gets token, if he doesn't he gets HTTP 401 Error.

Here is also closer picture of body of response, cause it is too small on previous picture:

My question is: Is there any chance to change name of access_token property inside returned JSON to auth_token. I need to use different name because, later in the project I will have one more token and it's name has to be access_token too.
My second question is: Can I changed date format for .issued and .expires properties? For example to yyyy-MM-dd?
I've used this tutorial http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/
So the code is exact same. I am trying to track creation of response with debugger, but I don't have clear vision where it could be. I guess it is inside of SimpleAuthorizationServerProvider class, but I can't find explicit setup of this properties anywhere in project, so I guess that response creates automatically.

A: While changing the name or the format of the standard token response parameters is definitely not a good idea, here's a way to do it anyway: https://stackoverflow.com/a/28683971/542757
Basically, you'll have to use the TokenEndpointResponse notification and provide your own JSON payload. Sadly, there's a bug that prevents it from working with the OAuth2 authorization server built in Katana 3. You can take a look at a fork I developed with @manfredsteyer ; it includes a fix that allows this kind of scenario: https://github.com/aspnet-contrib/AspNet.Security.OpenIdConnect.Server/tree/dev


text:
Q: Ignoring to show a number using sprintf I have a question about C function sprintf. Is it possible, to show the hex number only if some
condition is OK? Or to print some blank spaces instead?
The DLC is data length, f.e. if I have DLC = 2,
I want to pack only 2 data bytes to buffer, and other 6 bytes need to be ignored or replaced by blank spaces.
sprintf(buffer, "%02X  %02X  %02X  %02X  %02X  %02X  %02X  %02X",
    (frame.frameDLC > 0)? frame.frameData[0]:"  ", (frame.frameDLC > 1) ? frame.frameData[1] : "  ",
    (frame.frameDLC > 2) ? frame.frameData[2] : "  ", (frame.frameDLC > 3) ? frame.frameData[3] : "  ",
    (frame.frameDLC > 4) ? frame.frameData[4] : "  ", (frame.frameDLC > 5) ? frame.frameData[5] : "  ",
    (frame.frameDLC > 6) ? frame.frameData[6] : "  ", (frame.frameDLC > 7) ? frame.frameData[7] : "  ",
    );

A: For an embedded system, you really want to avoid bloat library functions like sprintf because it takes up lots of execution time and memory. It's a completely unacceptable function to use in a professional setting. Similarly, on mid- to high range systems you'll want to avoid a lot of branches like your ?: example.
Doing this conversion by hand is quite trivial and some 10 to 100 times faster than sprintf, depending on system:
#include <stdio.h>
#include <stdint.h>

typedef struct
{
  uint8_t data[8];
  uint8_t dlc;
} frame_t;

static inline char hex_nibble (uint8_t bin)
{
  return "0123456789ABCDEF"[bin];
}

int main (void)
{
  char buf [100];
  size_t length=0;

  frame_t frame = { .data={0xAA,0xBB,0x55,0x77}, .dlc=4 };
  for(uint8_t i=0; i<frame.dlc; i++)
  {
    buf[length++] = hex_nibble(frame.data[i]>>4&0xF);
    buf[length++] = hex_nibble(frame.data[i]&0xF);
  }
  buf[length]='\0';
  puts(buf);
}

If you want to add spaces after the number simply do a second loop:
for(uint8_t i=frame.dlc; i<8; i++)
{
  buf[length++] = ' ';
  buf[length++] = ' ';
}

A: Do not use sprintf. Use bounds-checking snprintf instead.

Is it possible, to show the hex number only if some condition is OK? Or to print some blank spaces instead?

Yes, use an if. Basically your code is a for loop...
char buffer[200];
size_t pos = 0;
for (size_t i = 0; i < frame.frameDLC; ++i) {
   pos += snprintf(&buffer[pos], sizeof(buffer) - pos, "%02X", frame.frameData[i]);
}
for (size_t i = frame.frameDLC; i < 8; ++i) {
   pos += snprintf(&buffer[pos], sizeof(buffer) - pos, "  ");
}

A: sprint() returns the number of characters output.  You can use this to maintain a "cursor position" in the buffer to output each element incrementally.
int bi = 0 ;
for( int di = 0; di < frame.frameDLC; di++ )
{
    bi += sprintf( &buffer[bi], "%02X", frame.frameData[di] ) ;
    if( di + 1 < frame.frameDLC)
    {
        bi += sprintf( &buffer[bi], "  ", frame.frameData[di] ) ;
    }
}

The above assumes that there are two spaces between each element and that you do not want/need trailing spaces.
If you are not concerned about trailing spaces it can be simplified to:
int bi = 0 ;
for( int di = 0; di < frame.frameDLC; di++ )
{
    bi += sprintf( &buffer[bi], "%02X  ", frame.frameData[di] ) ;
}

If the single space between the 5th and 6th in your question is deliberate, then you need perhaps:
if( di + 1 < frame.frameDLC)
{
    bi += sprintf( &buffer[bi],
                   di == 4 ? " " :"  ",
                   frame.frameData[di] ) ;
}

And if you truly need to space-pad the string to 29 characters (as the code in your question does), then a second loop starting from bi to add trailing spaces will be required.


text:
Q: Legend when plotting 2 data frames in one plot I have plotted positive values and negative values exactly as I would like them to be, legend included.  I am now putting these together in one plot to create a single plot (I do not have enough points to link to this image).  I am very pleased with this - except for the legend. The legend is sorted alphabetically which is not the my preferred order (the same order as the colour layers from top to bottom).  I have tried different ways of trying to manually set the legend but all I have found so far works when plotting a single data frame and not two as I am.
It seems that using scale_colour_manual does not affect this type of plot, is there another way of doing this?
Below is a very simple working example that also gives the same behaviour described above.
data1 = data.frame(x = seq(0,20), y =    c(1,4,-5,-9,-4,0,3,6,-4,3,-2,-5,8,2,1,6,7,-9,8,-4,0))
data2 = data.frame(x = seq(0,20), y = seq(0,20))

q = ggplot(NULL, aes(x = x, y = y))
q = q + geom_line(data = data1)
q = q + geom_line(data = data2)

Thanks,
Jane

Thanks for the reply but I am still not getting the graph that I would like. Here is a link to closest that I have come to so far positive and negative values - legend not as required. For this plot I have used two separate data frames as I am using different geom_area and geom_line positions; for the positive part of the plot I am using:
geom_area(data = prod.data, position = "identity", alpha = 0.8)
geom_line(data = prod.data, position = "identity")

and for the negative part of the plot I am using:
geom_area(data = cons.data, position = "stack", alpha = 0.8)
geom_line(data = cons.data, position = "stack")

However, as discussed in the original question I seem to have no control over the order of the legend.  I tried combining the data frames and set the order of the factor, here I used:
geom_area(position = "stack", alpha = 0.8)
geom_line(position = "stack")

and I have control over the legend order but the actual plot is not as I would like it. Here is the graph positive and negative values - graph not as required.
I'm having quantum mechanics flashbacks :-) so any further assistance is greatly appreciated.

A: Generally, ggplot works best when you combine your data into one data frame. Your provided example is a bit confusing--as written there is not a legend, and it's not clear what you'd want the legend to be. The way I'd go about it would be to combine the data frames:
data1$group <- 1
data2$group <- 2
data3 <- rbind(data1, data2)
data3$group  <- factor(data3$group)
q <- ggplot(data3, aes(x = x, y = y, group = group, color = group))
    + geom_line()

You can then use any of the standard ways to order the legend. Less automatic, but often superior to a normal legend, you could use a new data.frame and a geom_text call to manually label each line.
The legend will, by default, be sorted in the order of the factor, so to reorder the legend, you should order the factor, either manually using factor
data3$group <- reorder(data3$group, levels = c(2, 1), ordered = TRUE)

or using reorder and a function (such as sort(), or rev(sort()), if you want reverse alpha order). You could also use reorder with a function of a different column if you wanted to order the factor by mean or max y value, for example.


text:
Q: How to call D-Bus method that expects array of bytes using busctl command line tool I'm trying to do busctl call of a method that takes array of bytes as arguments (signature ay). How do I do this?
This is what I've tried so far:
# busctl call ${SERVICE_IFACE} ${THE_OBJECT} ${SERVICE_IFACE} ${METHOD} ay 0x00 0x00 0x01 0x00 0xaf
Too many parameters for signature.
# busctl call ${SERVICE_IFACE} ${THE_OBJECT} ${SERVICE_IFACE} ${METHOD} yyyyy 0x00 0x00 0x01 0x00 0xaf
Call failed: Invalid arguments 'yyyyy' to call xyz.openbmc_project.Control.Haven.SendHostCommand(), expecting 'ay'.
# busctl call ${SERVICE_IFACE} ${THE_OBJECT} ${SERVICE_IFACE} ${METHOD} a5y 0x00 0x00 0x01 0x00 0xaf
Invalid array signature: Invalid argument
# busctl call ${SERVICE_IFACE} ${THE_OBJECT} ${SERVICE_IFACE} ${METHOD} ay '0x00 0x00 0x01 0x00 0xaf'
Failed to parse '0x00 0x00 0x01 0x00 0xaf' number of array entries: Invalid argument

So, what does it want?

A: I believe you need to put the length of the array before the values. So in your example that would be:
busctl call ${SERVICE_IFACE} ${THE_OBJECT} ${SERVICE_IFACE} ${METHOD} ay 5 0x00 0x00 0x01 0x00 0xaf


text:
Q: Aggregate root and value object outside of aggregate I have an aggregate root "Car"
A car has a list of value objects "Wheels" containing "Wheel" objects.
Since a car should not exist without wheels (at least according to our business logic), in order to construct a car is this valid in proper domain driven design:
double radius = 17.0;
List<Wheel> carWheels = new List<Wheel>();
carWheels.add(new Wheel(radius));
Car aCar = new Car(carWheels);

My question is basically, is it good practice to instantiate value objects outside of an aggregate root in order to construct an aggregate root (passing value objects in constructor).
I don't want to create an aggregate root in an invalid state and would like to follow best practices. If the above code is not best practice, how should it be done?

A: IMHO it is neither a bad practice nor a good practice. All depends on the actual domain which you are trying to model. It might make sense to create those VOs outside the aggregate in some cases and in others it will just open up your domain for malicious usage. DDD forces you to forget a bit about technical problems and bad/good practices in order to focus on the actual domain:

*

*Would it make sense in any scenario to create a car with 26 wheels? Your example model allows that

*Whould it make sense in any scenario to create a car with 4 wheels, each having different radius? Your example model allows that

*Whould it make sense to create a wheel with radius 17.3284546? Again, your model allows that to happen

Therefore, in my opinion for the example which you've shown, it might be better to handle those invariants inside the aggregate itself because you can nicely constrain the number of things than can be done to car and wheels when both are created. However, that comes from a closer look at the domain itself rather than relying on widely known good or bad practices. Just to reiterate, there will be cases in which you'll be better off by creating VOs outside the aggregate. All depends on the domain.

A: I like this approach. In test cases, we could inject stub/mock Wheels to Car.
I would introduce a CarFactory if there are complex business constraints in the construction of wheels or car.

A: In this concrete example, I would give radius to Car's constructor and let it build wheels by itself. That way you would hide instantiation details from your client's code (less knowledge outside of your aggregate) and your client would not be affected by internal changes of Car aggregate.
You should prefer building aggregates in only one step/operation/action. If it's not just one step, your aggregate is inevitably showing some details of it's internal structure.


text:
Q: Ajax function is not being called on document change I am using a date-range-picker.You may have a look at this https://jsfiddle.net/soongsta/r369crfv/. I am providing code of this daterangepicker as well.
HTML code of DateRangePicker

  Date range button:

    <button type="button" class="btn btn-default" id="daterange-btn" style='width:230px'>

          defaut date

    </button>
    <button id='btnDec' type="button" class="btn btn-danger btn-flat" title='Decrement month'></button>
    <button id='btnInc' type="button" class="btn btn-info btn-flat" title='Increment month'></button>

Javascript + Jquery()
var start = moment().startOf('month');
var end = moment().endOf('month');
var label = '';

    $('#daterange-btn').daterangepicker({
            locale: {
            format: 'DD MMM YYYY'
        },
        startDate: moment(start),
        endDate: moment(end),
        ranges: {
           'Today': [moment(), moment()],
           'Yesterday': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
           'Last 7 Days': [moment().subtract(6, 'days'), moment()],
           'Last 30 Days': [moment().subtract(29, 'days'), moment()],
           'This Month': [moment().startOf('month'), moment().endOf('month')],
           'Last Month': [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
        }
    },
    function(start, end, label) {
      if(isDate(start)){
        $('#daterange-btn span').html(start.format('DD MMM YYYY') + ' - ' + end.format('DD MMM YYYY'));
      }
    });

    $('#btnInc').click ( function(e) {
        IncDecMonth('Inc')
    })

    $('#btnDec').click ( function(e) {
        IncDecMonth('Dec')
    })

function isDate(val) {
    //var d = new Date(val);
    //return !isNaN(d.valueOf());
    var d = Date.parse(val);
    console.log(d);
    return Date.parse(val);
}

    function IncDecMonth(Action) {
      if(!isDate(start)){
        start = moment().startOf('month');
      }
        if(Action == 'Inc'){
        start = moment(start).add(1, 'month').startOf('month');
        end =  moment(start).endOf('month')
      }
      else
      {
        start = moment(start).subtract(1, 'month').startOf('month');
        end =  moment(start).endOf('month')
      }
      if(isDate(start)){
        $('#daterange-btn span').html(start.format('DD MMM YYYY') + ' - ' + end.format('DD MMM YYYY'));
      }
            console.log('start='+start)
      console.log('end='+end)
    }

    IncDecMonth();

I want that when a person will select date range then a request should hit my server with date range as data.
For this i have written this code:-

But i cannot see any POST request on my server.Moreover pop up of 'hi' is also not shown which ultimately means that document.on('change') has not been called.
Could you tell me where i am doing the mistake?

A: Make sure to wrap all your ajax calls in
$(function(){

})

to make sure dom has loaded before using jquery
Update
Sorry I did'nt read the entire question and only saw the last script tag. After reading the question i opened the docs for daterangepicker and fixed the issue.
Here is the working script

You were missing to call apply event after updating the values and also listen to apply event instead of span change event


text:
Q: PHP exec() Not writing output file on IIS I am trying to run a script that results in different files being created via PHP exec command.  After writing the script I get no out put file.  So I wrote basic test code listed below.  I get the hostname to display in browser but no name.txt file.  This is running on IIS, I was thinking it was a permissions problems but I already added IIS guest account IUSR_hostname with write access to the folder in question, but still no txt file.  Any help would be greatly appreciated.
<?php

    error_reporting(E_ALL);
    exec("hostname > name.txt");
    echo exec("hostname");

?>

A: Check if the user that PHP runs under have "X" permission on every directory of the file path. It will need it to access the file
If your file is: /path/to/test-in.txt You should have X permission on:
/path
/path/to

and read permission on /path/to/test-in.txt or through CPanel/ftp provide the write access to the file


text:
Q: Class has a friend function. The function is defined inside of a namesapce in a different header file. It cannot access private members? This is a simplified version of a much larger program that I am working on. However the same issue is present and I cannot seem to find a solution anywhere.
I have a class named User that contains one private data member as a string that holds a user's username. It has one constructor that accepts a string argument and a friend function for displaying the object's userName data member. I am defining the friend function inside of a namespace that is in a different header file. However, it cannot access the private data memebers of the object and I cannot figure out why...
// User.h
#ifndef USER_H
#define USER_H

#include <string>

class User
{
private:
    std::string userName;

public:
    User(std::string name)
    {
        userName = name;
    }

    friend void displayUsername(const User& temp);
};

#endif /* USER_H */

// Operations.h
#ifndef OPERATIONS_H
#define OPERATIONS_H

#include <iostream>
class User;

namespace Operations
{
    void displayUsername(const User& temp)
    {
        std::cout << temp.userName << std::endl; // ERROR??
    }
};

#endif /* OPERATIONS_H */

//main.cpp
#include <iostream>
#include "User.h"
#include "Operations.h"

int main()
{
    User me("World");
    Operations::displayUsername(me);

    return 0;
}

A: Your friend function is declared into the namespace enclosing the class User. It is essentially ::displayUsername, and is different from Operations::displayUsername. If you want that one to be a friend you better declare it by a fully qualified name
class User;
namespace Operations{
   void displayUsername(const User& temp);
}

class User
{
private:
    std::string userName;

public:
    User(std::string name)
    {
        userName = name;
    }

    friend void Operations::displayUsername(const User& temp);
};

A: For a friend of a class to make use of that friendship - and to access members of the class - the compiler needs to see the class definition when compiling the friend function.
This means you need to do a few things.
Firstly, in User.h, the compiler needs to see a declaration of the friend function.
#ifndef USER_H
#define USER_H

#include <string>

class User;

namespace Operations
{
    void displayUsername(const User& temp);    // a definition of User is not needed here, since User is passed by reference
};

class User
{
   private:
      std::string userName;

   public:
      User(std::string name)
      {
          userName = name;
      };

     friend void displayUsername(const User& temp);
};

#endif /* USER_H */

Then, in your Operations.h, the compiler needs to see a definition (NOT just a forward declaration) of class User
#ifndef OPERATIONS_H
#define OPERATIONS_H

#include <iostream>

#include "User.h"    // a forward declaration of User is insufficient

namespace Operations
{
    void displayUsername(const User& temp)
    {
        std::cout << temp.userName << std::endl;
          // this statement accesses User's members, so the compiler
          //  needs to see a complete class definition
    }
};
#endif /* OPERATIONS_H */

It would probably be advisable to move the definition of Operations::displayUserName() into a source (.cpp) file, rather than having it in a header file.   In your project, you only have one compilation unit, so that is unnecessary - something to consider as your project gets larger and has multiple distinct source files.


text:
Q: Firebase+GTM SDK - tracking exceptions and crashes in Google Analytics Google Analytics allows collection of a basic contextual information and crash and exception in app. This has been done using GA library. I am currently upgrading the implementation to use Google Tag Manager by utilising latest version Firebase+Tag Manager SDK.
I wonder how can I make sure crashes from my app are registered within GA? Firebase crashlitycs is a different tool. I really need those crashes and exceptions in Google Analytics as exceptions/crashes rather than just events.
Please advice. Thank you

A: You can create a tag in GTM (exception type) and use the event 'app_exception' (in firebase) as a trigger, sending that information to GA.


text:
Q: Get correct language code in Django from HTML header I am trying to get language choices from HTML head ACCEPT-LANGUAGE header. I have used parse_accept_lang_header() module for this. But its returning me all the language code in small character. like this [('pt-pt', 1.0), ('pt-br', 0.8), ('en-us', 0.5), ('en', 0.3)]
But I want to get like first one in small character, second part in uppercase corrector. Like this [('pt-PT', 1.0), ('pt-BR', 0.8), ('en-US', 0.5), ('en', 0.3)]. So how can I do so?
My code is as following:
from django.utils.translation.trans_real import parse_accept_lang_header
header_locales =parse_accept_lang_header(
                                  request.META.get('HTTP_ACCEPT_LANGUAGE', None))

the header_locales return me the locale name in small charector.

A: It would appear that django lower cases the language codes for you (thx dgel). Is there a reason you need the uppercasized version? You could always split up the code and uppercase it yourself I guess. Or you could duplicate the functionality of the parse_accept_lang_header code without the lowercase bit. I'm not exactly sure what the use case is though.
If you need to query your database, you could always use something like the following (from here and the original documenation):
MyClass.objects.filter(name__iexact=my_parameter)


text:
Q: JQuery Hide after append I am running a script that will append an element upon selecting it from a dropdown list, that bit all works fine and appends the item. The item appended includes a button that will hide the appended item when clicked. What I can't seem to get to work is the hide function. The code seems to work fine if I put the element in manually into the HTML and click the hide button but for some reason when appending it it doesn't work?
$('#addteammember').click(function() {
 var usernamevalue = $("#teammemberselected").val();
 var teammemberfullname = $('#teammemberselected option:selected').text();
  $('#teammemberlist').append("
<input class='removeteam' type='button' value="+usernamevalue+" />"+teammemberfullname+"
");
});

$('.removeteam').click(function () {
  $(this).hide();
});

A: It happens because you append the button dynamically but bind your click handler for already existing elements only. You can use this code instead:
$("#teammemberlist").on("click", ".removeteam", function () {
    $(this).hide();
});

A: Try live function.
$(".removeteam").live("click", function() {
$(this).hide();
});


text:
Q: Calling Mixpanel Alias and Identify events in WordPress I am trying to call the Mixpanel alias and identify events into hooks for user_registration and wp_login but am getting undefined function errors on the alias function on registration and identify function on login.
I have included the Mixpanel javascript in my header and below are my two hooks that I am using in my functions.php file.
Any help on what I may be doing wrong here would be greatly appreciated!

// MIXPANEL REGISTRATION SCRIPT
function mixpanelRegistration($user_id) {
    mixpanel.alias($user_id);
}
add_action('user_register', 'mixpanelRegistration');

// MIXPANEL LOGIN SCRIPT
function mixpanelLogin($user) {
    mixpanel.identify($user->ID);
}
add_action('wp_login', 'mixpanelLogin');

A: This issue was being caused by trying to call the mixpanel javascript library within my WordPress functions (PHP). Ended up needing to call in the mixpanel php library.


text:
Q: configure php using pear on linux I have lampp installed on my linux box. I am trying to use proc_open as below.
    $spec = array(
            array("pty"),
            array("pty"),
            array("pty")
    );

    $this->process = proc_open($command, $spec, $this->pipes);

But i am getting Warning: proc_open() [function.proc-open]: pty pseudo terminal is not support on this system in...
I found that i need to enable pty in php like ./configure --enable-pty. But the php is installed as part of lampp. I could not configure php.
How can I enable pty using pear. Please help.

A: You have to recompile PHP, which is nothing PEAR can help you with.


text:
Q: Solving equations of motion with a background ansatz Consider the effective 4d gravitational bulk action article, dual to $QFT_3$ on $\mathbb{R}^{2,1}$,
$ S_{QFT_3}=S_{CFT_3}+S_r +S_i=\frac{1}{2\kappa^2}\int dx^4\sqrt{-\gamma}(R+6-\frac{1}{2}(\nabla\phi)^2+\phi^2-\frac{1}{2}(\nabla\chi)^2-2\chi^2-g\phi^2\chi^2)$,
where we split the action into a conformal part, it deformation by a relevant operator and a sector involving an irrelevant operator, along with its mixing with a relevant operator under the renormalization group flow, specified by a constant $g$.
The thermal states of the $QFT_3$ are dual to the black brane solutions with a translationary invariant horizons
$ ds^2_4 =\frac{\alpha^2a(x)^2}{(2x-x^2)^{2/3}}(-(1-x)^2dt^2+(dx_1^2+dx_2^2))+g_{xx}dx^2$, $ \phi=\phi(x) $, $ \chi=\chi(x) $,
where the radial coordinate $ x\in(0,1) $. The constant $\alpha$ is an arbitrary scale parameter and the metric warp factor $ g_{xx} $ is determined algebraically from $ a,\phi,\chi $. Solving the equations of motion with the background ansatz we find
$ a=1-\frac{1}{40}p_1^2x^{2/3}-\frac{1}{18}p_1p_2x+\mathcal{O}(x^{4/3}) $
$ \phi=p_1x^{1/3}+p_2x^{2/3}+\frac{3}{20}p_1^3x+\mathcal{O}(x^{4/3}) $
$ \chi=\chi_4 (x^{4/3}+(\frac{1}{7}g-\frac{3}{70})p_1^2x^2+\mathcal{O}(x^{7/3}))$,
near the $ AdS_4 $ boundary $ x\rightarrow 0_+ $ and
$ a=a_0^h+a_1^hy^2+\mathcal{O}(y^4) $
$ \phi=p_0^h+\mathcal{O}(y^2) $
$ \chi=c_0^h+\mathcal{O}(y^2) $
near the black brane horizon $ y=1-x\rightarrow 0_+ $. Apart from the overall scaling factor $\alpha$, a black brane solution is specified with the three UV coefficients $ \{p_1,p_2,\chi_4\} $ and four IR coefficients $ \{a_0^h,a_1^h,p_0^h,c_0^h\} $.
Could someone explain what exactly does it mean "solving the equaitons of motion with a background ansatz" and how are equations for coefficients generally obtained? Does there exist any useful reference?


text:
Q: Invalid syntax in python 2 creating a simple Naive Bayes classifie The final step for creating a simple Naive Bayes classifier consists in writing a class Classifier, which will use our classes NBclass and Feature.
class Classifier:

    def __init__(self, *nbclasses):
        self.nbclasses = nbclasses

    def prob(self, *d, best_only=True):

        nbclasses = self.nbclasses
        probability_list = []
        for nbclass in nbclasses:
            ftrs = nbclass.features
            prob = 1
            for i in range(len(ftrs)):
                prob *= nbclass.probability_value_given_feature(d[i], ftrs[i])

            probability_list.append( (prob, nbclass.name) )
        prob_values = [f[0] for f in probability_list]
        prob_sum = sum(prob_values)
        if prob_sum==0:
            number_classes = len(self.nbclasses)
            pl = []
            for prob_element in probability_list:
                pl.append( ((1 / number_classes), prob_element[1]))
            probability_list = pl
        else:
            probability_list = [ (p[0] / prob_sum, p[1])  for p in probability_list]
        if best_only:
            return max(probability_list)
        else:
            return probability_list

// File "", line 7
     def prob(self, *d, best_only=True):
                                ^
SyntaxError: invalid syntax

A: flip *d and best_only=True and it'll work fine. Python3 allows you to specify keyword-only arguments. Python2 does not, so *d expects to accumulate all the rest. Specifying best_only=True after that makes no sense to the Python2 syntax.
class Classifier:

    def __init__(self, *nbclasses):
        self.nbclasses = nbclasses

    def prob(self, best_only=True, *d):

        nbclasses = self.nbclasses
        probability_list = []
        for nbclass in nbclasses:
            ftrs = nbclass.features
            prob = 1
            for i in range(len(ftrs)):
                prob *= nbclass.probability_value_given_feature(d[i], ftrs[i])

            probability_list.append( (prob, nbclass.name) )
        prob_values = [f[0] for f in probability_list]
        prob_sum = sum(prob_values)
        if prob_sum==0:
            number_classes = len(self.nbclasses)
            pl = []
            for prob_element in probability_list:
                pl.append( ((1 / number_classes), prob_element[1]))
            probability_list = pl
        else:
            probability_list = [ (p[0] / prob_sum, p[1])  for p in probability_list]
        if best_only:
            return max(probability_list)
        else:
            return probability_list


text:
Q: how to edit state based on country using php and ajax How can I fetch state from selected country in edit time?
This is for country:

    <select class="select2 form-control custom-select " style="width: 100%; height:36px;" name="country" onChange="getState(this.value);" id="country">
    <option>Select Country</option>
    <?php foreach($countries as $coun) {
            foreach($ed as $edit) /*edit mode*/
            {

                if($edit->country_id==$coun->id)
                {
        ?>

                    <option value="<?php  echo $coun->id;  ?>" selected="selected"> <?php echo $coun->name; ?> </option>
        <?php
            }}

                ?>
                    <option value="<?php  echo $coun->id;  ?>"> <?php echo $coun->name; ?> </option>
                <?php

    } ?>
    </select>

This is for state:

    <select class="select2 form-control custom-select" style="width: 100%; height:36px;" name="state" id="state-list" onChange="getCity(this.value);">
    <option>Select State</option>

    </select>

function getState(val) {
    $.ajax({
        type: "POST",
        url: "getState.php",
        data:'country_id='+val,
        success: function(data){
            $("#state-list").html(data);
            //getCity();
        }
    });
}

A: Try the code below:
function getState(val) {
    $.ajax({
        type: "POST",
        url: "getState.php",
        data:{country_id:val},
        success: function(data){
            $("#state-list").html(data);
            //getCity();
        }
    });
}