text:
Q: ValueError: Cannot use median strategy with non-numeric data The image shows that the column work class is converted to numerical value using dummy however when I print that column it still shows dtype as object1
I am new to Data Science and learning on handling the missing values in Python version 3.8.
I came across this issue which I am not able to understand what went wrong.
The issue is that I created dummies for the column named 'work class' one of the values in this column is 'state-gov'. I created dummies for this column and the code worked fine till then. However, when I started imputing the missing values with median I received the following error.
ValueError: Cannot use median strategy with non-numeric data:
could not convert string to float: 'State-gov'
Please find the code from where I created dummies attached with this Question.
Thank You in advance for help!
todummy_list = ['workclass', 'education', 'marital-status', 'occupation', 'relationship', 'race', 'sex', 'native-country']
def dummy_list(data_frame_features, todummy_list):
for x in todummy_list:
    dummies = pd.get_dummies(df[x], prefix=x, dummy_na=False)
    data_frame_features = data_frame_features.drop(x, 1)
    data_frame_features = pd.concat([df, dummies], axis=1)
return data_frame_features
 # filling the missing values with median
imp = SimpleImputer(missing_values='NAN', strategy='median', fill_value=None)
imp.fit(data_frame_features)
data_frame_features = pd.DataFrame(data=imp.transform(data_frame_features), columns=data_frame_features.columns)
print(f'\nRecalculated')
print(data_frame_features.isnull().sum().sort_values(ascending=False))

A: This error is being thrown because your workclass column contains "state-gov" (and potentially other string-type values) you cannot impute using the mean because mean imputation only works with numeric data. It looks like one imputation strategy which scikitlearn supports for string values is "most_frequent". If this is your desired behavior you can use that:
imp = SimpleImputer(missing_values='NAN', strategy='median', fill_value=None)
Your other option would be to fill all those NAN values with a constant value, in this case "work-from-home" for example:
imp = SimpleImputer(missing_values='NAN', strategy='constant', fill_value="work-from-home")


text:
Q: Content hiding above div's I have an adept knowledge in HTML/CSS but I'm having a problem that has more than stooped me. In order to test my skills, I build websites on TV Shows etc, and while designing one, I've ran into a problem. As seen in the screenshot, although I've declared the div after the previous one, it seems to be hiding.
As you can see. I've tried both paragraph tags and divs, nothing seems to be working, I've included the HTML and CSS.

body {
 padding:0;
 margin: 0;
 font-family: 'Raleway';

}

.nav {
 background-color: black;
 text-decoration: none;
 color: silver;
 margin: 0;
 list-style: none;
 text-align: center;
}

.nav > li {
 display: block;
}

/* .nav > li:before {
 content: "*";
} */

.nav > li > a {
 text-decoration: none;
 color: silver;
 font-size:24px;
 text-transform: uppercase;
 font-weight: bolder;
 letter-spacing: 4px;
}

.nav-btn {
 display:block;
 font-size: 30px;
 background-color: black;
 color: silver;
 text-align: center;
 cursor: pointer;
}

.image {
 background-image:url('download1.jpg');
 width:100%;
    max-height:400px;
    background-position: left center absolute;
    background-size: 100%;
    background-repeat: no-repeat;
    position: absolute;
}

.title {
 display: inline-block;
 color: white;
 position:relative;
 margin: 15%;
 text-transform: uppercase;
}

.image {
 text-align: center;
 position:absolute;
}

.image > h2 {
 padding-top: 50%;
 line-height: 50%;

}

@media screen and (max-width: 411px) {
 .title > h2 {
  font-size: 15px;
 }

 .image {
  max-height:280px;
 }
}

.submitbox {
 color: yellow;
 background-color: darkblue;
 z-index: 1 !important;
}
<!DOCTYPE html>

<title>Welcome to France!</title>
<link rel="stylesheet" href="Reign.css" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>

 Menu

Home

About

News

Contact

"Today, I am king!"
Mary, Queen of Scots.

Sign up for our Newsletter!

hello

Some of that code isn't relevant to what I'm asking. Also, I have a menu but it's open when the page loads, and idea how I can get this to be closed on page load? Also running the code snippet doesn't illustrate what I'm saying as the image is missing.
EDIT: important was used to try and bring the H2 to the front of the image, which cannot be seen when running the code snippet. I used position abolute so when anything is adjusted it will not affect said styles, sorry If I'm doing that wrong. Also changed the images.
EDIT2: I just realised why I used position absolute, it was to stop the image getting white bars above and below the image when the window is scaled down
White bars?

A: For your menu issue, just set display:none; to your .nav and it will start not visible. For your other issue, I believe having your position set to absolute is what is causing the issue. By changing it to position:relative (and making the background green so you can see it), the div shows up and doesn't block the newsletter text. Absolute div's don't care what else is around it. It will be position relative to its nearest ancestor if set to absolute, which in the case of your HTML, is the
Also, you label id="submitbox" but reference it in css with .submitbox instead of #submitbox

body {
 padding:0;
 margin: 0;
 font-family: 'Raleway';

}

.nav {
    display:none;
 background-color: black;
 text-decoration: none;
 color: silver;
 margin: 0;
 list-style: none;
 text-align: center;
}

.nav > li {
 display: block;
}

/* .nav > li:before {
 content: "*";
} */

.nav > li > a {
 text-decoration: none;
 color: silver;
 font-size:24px;
 text-transform: uppercase;
 font-weight: bolder;
 letter-spacing: 4px;
}

.nav-btn {
 display:block;
 font-size: 30px;
 background-color: black;
 color: silver;
 text-align: center;
 cursor: pointer;
}

.image {
 background-image:url('download1.jpg');
 width:100%;
    max-height:400px;
    background-position: left center absolute;
    background-size: 100%;
    background-repeat: no-repeat;
    position: absolute;
}

.title {
 display: inline-block;
 color: white;
 position:relative;
 margin: 15%;
 text-transform: uppercase;
}

.image {
 text-align: center;
 position:relative;
  background-color:green;
}

.image > h2 {
 padding-top: 50%;
 line-height: 50%;
}

@media screen and (max-width: 411px) {
 .title > h2 {
  font-size: 15px;
 }

 .image {
  max-height:280px;
 }
}

.submitbox {
 color: yellow;
 background-color: darkblue;
 z-index: 1 !important;
}
<!DOCTYPE html>

<title>Welcome to France!</title>
<link rel="stylesheet" href="Reign.css" type="text/css">
<link href='https://fonts.googleapis.com/css?family=Raleway' rel='stylesheet' type='text/css'>

 Menu

Home

About

News

Contact

"Today, I am king!"
Mary, Queen of Scots.

Sign up for our Newsletter!

hello

redpajama_set_name: RedPajamaStackExchange


text:
Q: cant get resource string from adapter of recycler view When i reffer to resource string value in on bind view holder of my adapter i get following error:
2021-03-01 14:56:14.390 28009-28009/ E/AndroidRuntime: FATAL EXCEPTION: main
    Process:, PID: 28009
    java.lang.IllegalAccessError: Field 'com.example.ui.screens.history.PaymentHistoryVH.itemView' is inaccessible to class 'com.example.ui.screens.history.PaymentHistoryAdapter' (declaration of 'com.example.ui.screens.history./base.apk!classes2.dex)
        at com.example.ui.screens.history.PaymentHistoryAdapter.onBindViewHolder(PaymentHistoryAdapter.kt:40)
        at com.example.ui.screens.history.PaymentHistoryAdapter.onBindViewHolder(PaymentHistoryAdapter.kt:15)
        at androidx.recyclerview.widget.RecyclerView$Adapter.onBindViewHolder(RecyclerView.java:7065)
        at androidx.recyclerview.widget.RecyclerView$Adapter.bindViewHolder(RecyclerView.java:7107)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryBindViewHolderByDeadline(RecyclerView.java:6012)
        at androidx.recyclerview.widget.RecyclerView$Recycler.tryGetViewHolderForPositionByDeadline(RecyclerView.java:6279)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6118)
        at androidx.recyclerview.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:6114)
        at

My adapter :
class PaymentHistoryAdapter (private val onSelected: Consumer<ChargeModel>) : RecyclerView.Adapter<PaymentHistoryVH>() {

    private val items = mutableListOf<ChargeModel>()

    override fun getItemCount() = items.size

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
        LayoutInflater.from(parent.context).inflate(R.layout.item_history, parent, false)
                .let { PaymentHistoryVH(it) }
                .also {
                    handleClick(it)
                }

    private fun handleClick (holder : PaymentHistoryVH) {
        holder.root.setOnClickListener {
            val pos = holder.adapterPosition
            if (pos != RecyclerView.NO_POSITION) {
                onSelected.accept (items[pos])
            }
        }
    }

    override fun onBindViewHolder(holder: PaymentHistoryVH, position: Int) {
        holder.type.text = convertChargeType(items[position].type)
        holder.date.text = getDate(items[position].date, "dd/MM/yyyy")
        holder.price.text = holder.itemView.resources.getString(R.string.item_mb_price, formatPrice(items[position].total))
        holder.qoute.text = items[position].bytes?.let { formatQuoteMb(it) }
    }

    fun setData(data: List<ChargeModel>) {
        items.clear()
        items.addAll(data)
        notifyDataSetChanged()
    }
}

my resorce file :
<string name="item_mb_price">%1$s\u20ac</string>

But in my other adapters i can access the same resource string without problem, can anybody help me?


text:
Q: IE6 - body shrink on hover / z-index change I'm debugging a site to make it work for IE6 (god, please, let this be the last time). I've gotten pretty far with getting the the layout look right. There's just one more thing bugging me.

*

*Some elements like links, when they get hovered, the body of the site shrinks.

*I have built a dropdown with javascript. When it should show, the body of the site shrinks.

*There is a slideshow, made with javascript, which changes the z-index of the images, everytime it changes the z-index, the body shrinks.

Now I found some information that IE6 creates this specific shrinking behaviour when using a fixed position element. But this is not the case. Someone here have some ideas for solving this? Thanks!

A: I use situations like these as an argument to convince the users to finally switch from this monstrosity of a browser.

A: I hate to ask the question.... but are you using?:
<!--[if IE 6]>
Enter "special" styles for IE 6
<![endif]-->

It will get you out of a jam.
Regarding dropping IE6 support for sites, I have found that complaining to clients about it doesn't work very often.  But what does work is showing them in their Google Analytics that only 5% of their site visitors use it, and its ok if it doesn't match exactly, as long as the content is accessible.  That niche 5% costs a lot of extra development time and money to cater too.  But your screwed if it says 11% :-)


text:
Q: RestTemplate Bad Request a number of requests I am having a problem with rest template exchange method. I use it to send requests to google's GCM server. Everytime the same request, only recipient differs (a field in a JSON). When I send more than 200 requests at the same time, at 207th I get the 400 Bad Request response, after that I can wait some time but still get the same response for each outgoing request from my server. It seems like my code blocks access to the networking resources. When I restart server the resources are available again.
RestTemplate configuration:
<bean id="restTemplate"                 class="org.springframework.web.client.RestTemplate">
    <constructor-arg ref="httpRequestFactory"> </constructor-arg>
</bean>

<bean id="httpRequestFactory"           class="org.springframework.http.client.HttpComponentsClientHttpRequestFactory">
    <constructor-arg ref="httpClient"> </constructor-arg>
    <property name="connectTimeout" value="1000" />
</bean>

<bean id="httpConnectionManager"        class="org.apache.http.impl.conn.PoolingClientConnectionManager">
     <property name="defaultMaxPerRoute" value="50" />
        <property name="maxTotal" value="100" />
</bean>

<bean id="httpClient" class="org.apache.http.impl.client.DefaultHttpClient" >
     <constructor-arg ref="httpConnectionManager" />
</bean>

request:
ResponseEntity<String> response = restTemplate.exchange(
            "myaddress",
            HttpMethod.POST, request, String.class);

logs:
DEBUG [org.springframework.web.client.RestTemplate] (gcmjmsContainer-1) Created POST request for "https://gcm-http.googleapis.com/gcm/send"
DEBUG [org.springframework.web.client.RestTemplate] (gcmjmsContainer-1) Setting request Accept header to [text/plain, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, application/*+json, */*]

DEBUG [org.springframework.web.client.RestTemplate] (gcmjmsContainer-1) Writing [{
  "to" : "1",
  "notification" : {
    "text" : "mytext",
    "click_action" : "SHOW"
  },
  "data" : {
    "orderid" : 1,
    "status" : "paid"
  }
}] as "application/json" using [org.springframework.http.converter.json.MappingJackson2HttpMessageConverter@1d92cbc8]

DEBUG [org.apache.http.impl.conn.PoolingClientConnectionManager] (gcmjmsContainer-1) Connection request: [route: {s}->https://gcm-http.googleapis.com:443][total kept alive: 2; route allocated: 1 of 50; total allocated: 2 of 100]

DEBUG [org.apache.http.impl.conn.PoolingClientConnectionManager] (gcmjmsContainer-1) Connection leased: [id: 1][route: {s}->https://gcm-http.googleapis.com:443][total kept alive: 1; route allocated: 1 of 50; total allocated: 2 of 100]

DEBUG [org.apache.http.impl.client.DefaultHttpClient] (gcmjmsContainer-1) Stale connection check

DEBUG [org.apache.http.impl.client.DefaultHttpClient] (gcmjmsContainer-1) Attempt 1 to execute request

DEBUG [org.apache.http.impl.conn.DefaultClientConnection] (gcmjmsContainer-1) Sending request: POST /gcm/send HTTP/1.1

DEBUG [org.apache.http.impl.conn.DefaultClientConnection] (gcmjmsContainer-1) Receiving response: HTTP/1.1 400 Bad Request

DEBUG [org.apache.http.impl.client.DefaultHttpClient] (gcmjmsContainer-1) Connection can be kept alive indefinitely

WARN  [org.springframework.web.client.RestTemplate] (gcmjmsContainer-1) POST request for "https://gcm-http.googleapis.com/gcm/send" resulted in 400 (Bad Request); invoking error handlerng error handler

A: Actually I have found the solution the very second I posted the question. It came to my mind that there is to many entries "application/json" in the Accept header. My bug in the code was:
    restTemplate.getMessageConverters().add(
                new MappingJackson2HttpMessageConverter());
executing everytime I was sending a request using a singleton restTemplate.


text:
Q: Classpath variable 'JRE_LIB' in project is deprecated: Use the JRE System Library instead Attempting to Maven Clean the automation project displays the message "Could not find the main class. Program will exit"
After displaying the warnings of the project "Classpath variable 'JRE_LIB' in project 'ercard' is deprecated: Use the JRE System Library instead"
I'm starting in Java, and I don't know how to solve it.


text:
Q: In FitNesse - is there a way to see programmatically if a test failed/passed In my CI server, I'm implementing some logging/audit functionality - after every Fit test runs, in the TearDown page I'm logging some stuff to DB - Test Name, TimeStamp, some variables; I would also like to log if the test failed or passed - don't seem to find any global variable readily available in FitNess that would help. Could anyone give me some ideas how to do that?
thanks!
O.

A: TearDown doesn't know if a test passed or failed.  That is only known by FitNesse after the test is complete. What you can do is run fetch the last execution as XML and then parse that. Here is a snipped from ANT that will do something like that.
<!--Then run the page history responder to get the latest run of fitnesse in xml format-->
        <java classpath="${toString:compile.classpath};build\classes" fork="true" jar="javalib/fitnesse.jar" maxmemory="256m" output="${fitnesse.output.file}.temp">
            <arg value="-c" />
            <arg value="${fitnesseSuite}?pageHistory&resultDate=latest&format=xml" />
            <arg value="-p" />
            <arg value="${fitnesse_port}" />
        </java>

The one catch is that after you fetch it, you have to strip the http headers from the temp file that is created.  But once you do that, you can use the test result data for your database.  You can also create junit style results.  Check out this example on transforming to junit: http://whotestedthis.squarespace.com/journal/2012/1/26/transforming-fitnesse-results-to-junit.html (shameless self promotion).


text:
Q: Xcode can distribute iOS app but altool doesn't work I've made and distribute an iOS application from Xcode and have pushed it into Testflight.
Next, I try to do the same from the command-line.
xcodebuild -scheme QA -archivePath <path1> archive
xcodebuild -exportArchive -archivePath <path1> -exportPath <path2> -exportOptionsPlist ExportOptions.plist
xcrun altool --upload-app -f <path2> -u ... -p ...

After this, I've had the error
2020-12-18 15:33:55.164 altool[78702:6031914] *** Error: Error uploading '<path2>'.
2020-12-18 15:33:55.166 altool[78702:6031914] *** Error: code -21017 (Unable to validate your application. Could not determine the package's bundle id. The package is missing an Info.plist or the CFBundlePackageType is not 'APPL' or 'FMWK'.)

info.plist contains
    <key>CFBundlePackageType</key>
    <string>APPL</string>

What have I do?
PS: ExportOptions.plist:
...
    <key>method</key>
    <string>app-store</string>
...


text:
Q: Error is Cannot find module '@angular/fire'.ts(2307) how to resolve cant find @angular/fire
when import
it said that cant find module @angular/fire
how to resolve cant find @angular/fire
it said that cant find module @angular/fire
npm i firebase @angular/fire --save

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { AngularFireModule } from '@angular/fire';
import { AngularFirestoreModule } from '@angular/fire/firestore';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    AngularFireModule,
    AngularFirestoreModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }


text:
Q: Drawing a rectangle inside a rectangle I feel a little silly asking this but i'm not able to figure it out.. I am trying to draw a rectangle inside another rectangle and the math i'm using must be off. the inside rectangle is always one pixel to short.
b.fillRect( rectangleX+rectangleOutlineSize, rectangleY+rectangleOutlineSize, rectangleWidth-rectangleOutlineSize*2, rectangleHeight);

Its probably simple but I have been stuck on it for a hour and I have had trouble with it in the past.

A: In programming the coordinate system is a bit
weird, not exactly as (the usual one) in math.
*---------------------------------------> X +
|
|
|
|
|
|
|
v
Y +
I guess you're having a problem with that.
The * is the (0,0) which is usually the upper left
corner of your drawing area (e.g. of your screen).
Try something along these lines.
b.fillRect( x, y, width, height );

b.fillRect( x + (width-w)/2.0, y + (height-h)/2.0, w, h );

width - the width of the big rectangle
height - the height of the big rectangle
x,y - upper left corner of the big rectangle
w,h - width, height of the small rectangle


text:
Q: cvCaptureFromCAM causes program to hang I have a multiple camera setup and an OpenCV application that has been working using two cameras. One camera is a Logitech C310, and the other has been my built-in camera on my MacBook Pro. On initialization I call cvCaptureFromCAM(), once for each camera. However, hooking up a second Logitech C310 (total of 3 cameras) causes the call to cvCaptureFromCAM() to hang for my MacBook pro camera.
Both Logitech cameras work together just fine. Once I call cvQueryFrame() for my MacBook camera it hangs, but eventually after maybe 2-3 minutes it returns what appears to be a valid pointer (i.e. not NULL), but that camera is not initialized. I receive no frames from that camera, and the light that is typically green when the camera is in use is not lit.
Here is a snippet of my code:
for( size_t i = 0; i < NUM_CAMERAS; i++ ) // Works fine when NUM_CAMERAS is 2, but hangs when it is 3
{
    capture[i] = cvCaptureFromCAM( i );

    if( capture[i] != NULL )
    {
        // Start a thread for each camera
    }
}

// Threads manage calling cvQueryFrame() for each camera.

I am certain this is not an issue with multiple threads, because cvQueryFrame() always hangs, even if I do not start any new threads.
Thanks for any help - I'm having trouble finding anyone else with a similar issue.
OpenCV 2.4.5
OSX 10.8.4
gcc 4.2
Qt 5.0.2
Boost version 105300
2.4GHz Intel Core i7, retina Mac, 8BG RAM
2 x Logitech C310, 1 x MacBook Pro Camera
1 x Frustrated Dude

A: Turns out this is a limitation with my MacBook Pro. Running 2 USB cameras as well as the built-in iSight (which I believe is also USB internally), initialization of the 3rd device hangs. I can't provide a technical reason, but it seems it is a USB bandwidth issue.
I resolved this by using a Thunderbolt dock (http://www.belkin.com/us/p/P-F4U055) which has additional USB ports. Now my application works fine and initializes all cameras as it should. Also verified an Apple Thunderbolt display (which has a built in USB hub) also works.
Cheers!


text:
Q: Storing multiple images and displaying them within large bodies of text We currently have a million academic documents that need to be stored in a database. These documents contain text and figures (images) that are used to illustrate some concept within a specific section.
We have managed to separate the text and store it in our choice of Database which is ElasticSearch. However, we are unsure of how to proceed with storing the images available per document, retrieving them and displaying them most importantly in between the correct paragraphs.
Therefore I am looking for advice on the best approach for storing many images that should be embedded in bodies of text. What approach is high performance? Looking forward to hear from your experiences

A: HTML does this rather well... Kind of designed for it...  No need to reinvent anything here.  Dump them to a folder per-document, put  tags in with URLs in the text to reference them.  Static web sites scale rather well :-)


text:
Q: Install `mysql` gem for use in `chef-client`? I am trying to deploy a rails application using chef, for the mysql cookbook to create a database, it needs the mysql gem. The mysql gem is installed system-wide by using an Ubuntu package, but this is not usable by chef-client which runs from /opt/chef/embedded.
I have tried adding this:
chef_gem 'mysql' do
    action :nothing
end.run_action(:install)

But this requires the libmysqlclient-dev Ubuntu package to be installed. Therefore I have also added this before the previous:
package 'libmysqlclient-dev' do
    action :nothing
end.run_action(:install)

But this is done before the apt recipe updates the apt repositories, and therefore the install of libmysqlclient-dev fails.
These 'hacks' look ugly and I am unable to find a way to run the apt-get update at the right time.
Could someone please help me to find the right (the most chef-like) way to solve my problem (the actual problem is to create the database using the application cookbook)?
Update
I have been able to fix the problem with this recipe as an ugly hack... I'm still searching for a better solution:
execute "apt-get update" do
  ignore_failure true
  action :nothing
end.run_action(:run)

node.set['build_essential']['compiletime'] = true
include_recipe "build-essential"

%w{build-essential mysql-client libmysqlclient-dev}.each do |p|
  package p do
    action :nothing
  end.run_action(:install)
end

chef_gem 'mysql' do
  action :nothing
end.run_action(:install)

A: The mysql::ruby recipe allow to install packages via node["mysql"]["client"]["packages"]:
Therefore include it in your run list:
run_list(
  #...
  "recipe[mysql::ruby]",
  #...
)

and specify your dependencies in the attributes:
# this is needed for debian based systems
node["mysql"]["client"]["packages"] = ["build-essential","mysql-client","libmysqlclient-dev"]

A: There isn't really a link between the Debian package management system and gem so the answer is probably this:
package "libmysqlclient-dev" do
  action :install
end

gem_package "mysql" do
  action :install
end

(The chef_gem resource does install a gem, but it's only for installing gems to use inside a Chef recipe.  See all the gory details at the Chef Resources page).
For keeping apt under control, I recommend using the apt Opscode community cookbook and add recipe[apt] to the beginning of the run list for all nodes.


text:
Q: CSS: nested list - how to highlight entire line? I have a nested list like this :

Animals

Birds

Eagle

Mammals

Elephant

Cats

Lion

Tiger

Reptiles

Snake

Turtle

I'd like to style this so each level is indented, but I also wish to have each entire line highlighted when hovered. When I put a hover on DIV , the highlighting only starts from the left-position of the containing UL:
  ul.tree, ul.tree ul {
    list-style-type: none;
  }

  ul.tree li div:hover {
    background-color: red;
  }

Is there some way to achieve the effect I want, without defining multiple rules for li li, li li li, etc. ?
There could be an infinite number of levels of nesting, so I find it quite ugly to define all these different rules.
Or is there a way to calculate the level of nesting dynamically (in CSS?), so I could remove the padding of UL and instead put the right amount of padding inside each DIV ?
UPDATE:
added a fiddle that shows what I want:  http://jsfiddle.net/za3db/
You can see it's only indented on the second level, because I did not define the rule for the third, or fourth...

A: I know this answer is a tad late, however I was working on a tree recently and had the exact same thought and found a solution by studying the way several products tackle it. The below snippet illustrates a possible solution by placing a fill div for each item in the tree which has a large negative margin which allows it to cover the whole line. It's a very simple CSS only solution.
Hopefully it will help you and others who come across this question + answer.

.fill {
  display: none;
  margin-left: -10000px;
  position: absolute;
  top: 0px;
  right: 0px;
  bottom: 0px;
  left: 0px;
  z-index: -1;
}

.title {
  position: relative;
}

.title:hover .fill {
  display: block;
  background-color: #eee;
}

      Animals

          Birds

              Eagle

          Mammals

              Elephant

              Cats

                  Lion

                  Tiger

          Reptiles

              Snake

              Turtle

A: I haven't been able to do it with CSS, but it can be done with a little bit of javascript (jQuery).
$(".tree div").each(function()
{
    var padding = $(this).parents("ol, ul").length * 20 + "px";

    $(this).css("padding-left", padding);
});

See this jsFiddle

A: This kinda does was you want: http://jsfiddle.net/za3db/4/
It is placing an absolute positioned (left:0; right:0) pseudo-element under (z-index:-1) each of your divs. But this construct has 2 downsides:

*

*It only works when you know the height of the div (in my example always 1.3em = line-height)

*It wont highlight when you hover over the indent, because the div still doesnt start at the left.

So the best solution might still be javascript or just writing down all those li li, li li li, ... rules.

Edit: I played a little more with it and came up with a new version using hidden floated counter()-pseudo-elements for the indent: http://jsfiddle.net/za3db/5/.


text:
Q: How would I match a string that may or may not span multiple lines? I have a document that when converted to text splits the phone number onto multiple lines like this:
(xxx)-xxx-
xxxx

For a variety of reasons related to my project I can't simply join the lines.
If I know the phonenumber="(555)-555-5555" how can I compile a regex so that if I run it over
(555)-555-
5555
it will match?
**EDIT
To help clarify my question here it is in a more abstract form.
test_string = "xxxx xx x xxxx"
text = """xxxx xx
x
xxxx"""

I need the test string to be found in the text.  Newlines can be anywhere in the text and characters that need to be escaped should be taken into consideration.

A: You can search for a possible \n existing in the string:
import re
nums = ["(555)-555-\n5555", "(555)-555-5555"]
new_nums = [i for i in nums if re.findall('\([\d\n]+\)[\n-][\d\n]+-[\d\n]+', i)]

Output:
['(555)-555-\n5555', '(555)-555-5555']

A: A simple workaround would be to replace all the \n characters in the document text before you search it:
pat = re.compile(r'\(\d{3}\)-\d{3}\d{4}')
numbers = pat.findall(text.replace('\n',''))

# ['(555)-555-5555']

If this cannot be done for any reasons, the obvious answer, though unsightly, would be to handle a newline character between each search character:
pat = re.compile(r'\(\n*5\n*5\n*5\n*\)\n*-\n*5\n*5\n*5\n*-\n*5\n*5\n*5\n*5')

If you needed to handle any format, you can pad the format like so:
phonenumber = '(555)-555-5555'
pat = re.compile('\n*'.join(['\\'+i if not i.isalnum() else i for i in phonenumber]))

# pat
# re.compile(r'\(\n*5\n*5\n*5\n*\)\n*\-\n*5\n*5\n*5\n*\-\n*5\n*5\n*5\n*5', re.UNICODE)

Test case:
import random
def rndinsert(s):
    i = random.randrange(len(s)-1)
    return s[:i] + '\n' + s[i:]

for i in range(10):
    print(pat.findall(rndinsert('abc (555)-555-5555 def')))

# ['(555)-555-5555']
# ['(555)-5\n55-5555']
# ['(555)-5\n55-5555']
# ['(555)-555-5555']
# ['(555\n)-555-5555']
# ['(5\n55)-555-5555']
# ['(555)\n-555-5555']
# ['(555)-\n555-5555']
# ['(\n555)-555-5555']
# ['(555)-555-555\n5']

A: data = ["(555)-555-\n5555", "(55\n5)-555-\n55\n55", "(555\n)-555-\n5555", "(555)-555-5555"]

input = '(555)-555-5555'
#add new lines to input string
input = re.sub(r'(?!^|$)', r'\\n*', input)
#escape brackets ()
input = re.sub(r'(?=[()])', r'\\',input)

r = re.compile(input)

match = filter(r.match, data)

Code demo


text:
Q: Objective-C memory model I am attempting to wrap my head around one part of the Objective-C memory model (specifically on the iPhone, so no GC).  My background is C/C++/Java, and I am having an issue with the following bit of code (also wondering if I am doing this in an "Objective-C way" or not):
- (NSSet *) retrieve
{
    NSMutableSet *set;

    set = [NSMutableSet new];
    // would normally fill the set in here with some data

    return ([set autorelease]);
}

- (void) test
{
    NSSet *setA;
    NSSet *setB;

    setA = [self retrieve];
    setB = [[self retrieve] retain];

    [setA release];
    [setB release];
}

start EDIT
Based on comments below, the updated retrieve method:
- (NSSet *) retrieve
{
    NSMutableSet *set;

    set = [[[NSMutableSet alloc] initWithCapacity:100] autorelease];
    // would normally fill the set in here with some data

    return (set);
}

end EDIT
The above code gives a warning for [setA release] "Incorrect decrement of the reference count of an object is not owned at this point by the caller".
I though that the "new" set the reference count to 1.  Then the "retain" call would add 1, and the "release" call would drop it by 1.  Given that wouldn't setA have a reference count of 0 at the end and setB have a reference count of 1 at the end?
From what I have figured out by trial and error, setB is correct, and there is no memory leak, but I'd like to understand why that is the case (what is wrong with my understanding of "new", "autorelease", "retain", and "release").

A:
I though that the "new" set the reference count to 1. Then the "retain" call would add 1, and the "release" call would drop it by 1. Given that wouldn't setA have a reference count of 0 at the end and setB have a reference count of 1 at the end?

You're leaving out the autorelease. When -(void)test gets a set, its retain count is 0. You don't retain setA, so it already has a retain count of 0 when you try to release it, hence the error message.
The fundamental rule for memory management is quite simple: calls to alloc, new and copy* must be balanced by calls to release/autorelease. The former take ownership, the latter relinquish ownership.
The only tricky part is when dealing with shared objects, where you don't take ownership of an object, so it might be discarded in between the time you get a reference to it and when you use it. This has a simple solution: if in doubt, retain it.
You can make things even simpler by using properties in many situations.

A: Don't think in terms of absolute numbers. That can be very deceptive. Think of retains and releases as deltas if you must have a number — in this case, the autorelease has already balanced the new (a +1 delta and a -1 delta), so that method manages its memory correctly and the receiver doesn't need to do anything unless it wants to keep the object around longer.
Definitely read the memory management docs. It really is as simple as following the rules described there. It's a very simple contract of ownership where you claim ownership when you want an object to stick around and relinquish ownership when you don't care anymore. In the case above, you relinquish ownership in the retrieve method, so trying to relinquish ownership when you don't have it is obviously a bug.

A: As the profiler message hints, you should be thinking in terms of ownership. As noted in the memory management rules, whenever you have an object that you have created with +alloc, +new, -copy, or -mutableCopy, you own it and are responsible for releasing it eventually. (In fact, +new is just shorthand for [[MyClass alloc] init].)
-retain takes an object that you didn't initially own and makes you own it.
-release takes an object that you own and releases ownership of it.
-autorelease takes an object that you own and releases ownership of it, but also guarantees that the object will exist for at least a little bit longer.
Your -retrieve method does not transfer ownership of the object it returns. This is good—it follows the memory management rules (the method isn't +alloc, +new, -copy, or -mutableCopy). Therefore, using -release on it without using -retain is an error. It would be equally valid to not retain or release the result from -retrieve, as long as the object will have a temporary lifetime—your -autorelease guarantees temporary existence of the object.

A: http://www.macresearch.org/difference-between-alloc-init-and-new
You probably want
NSMutableSet *set = [[NSMutableSet alloc] initWithCapacity: someNumber];

or
NSMutableSet *set = [NSMutableSet setWithCapacity: someNumber];


text:
Q: Hazelcast with openjdk-15 How I can run hazelcast with java15 ? I am using usercodedeployment so I need to install my own classes in java 15. Now I got error:
{"@timestamp":"2021-04-08T23:34:43.129+02:00","@version":"1","message":"Hazelcast nepripojen","logger_name":"org.my.data.HazelcastInstanceWrapper","thread_name":"main","level":"ERROR","level_value":40000,"stack_trace":"com.hazelcast.client.UndefinedErrorCodeException: Class name: java.lang.UnsupportedClassVersionError, Message: org/my/data/MyData has been compiled by a more recent version of the Java Runtime (class file version 59.0), this version of the Java Runtime only recognizes class file versions up to 55.0\n\tat java.lang.ClassLoader.defineClass1(Native Method)\n\tat java.lang.ClassLoader.defineClass(ClassLoader.java:1017)\n\tat java.lang.ClassLoader.defineClass(ClassLoader.java:878)\n\tat com.hazelcast.internal.usercodedeployment.impl.ClassSource.define(ClassSource.java:52)\n\tat com.hazelcast.internal.usercodedeployment.impl.ClassLocator.defineClassFromClient(ClassLocator.java:135)\n\tat com.hazelcast.internal.usercodedeployment.impl.ClassLocator.defineClassesFromClient(ClassLocator.java:107)\n\tat com.hazelcast.internal.usercodedeployment.UserCodeDeploymentService.defineClasses(UserCodeDeploymentService.java:74)\n\tat com.hazelcast.internal.usercodedeployment.impl.operation.DeployClassesOperation.run(DeployClassesOperation.java:49)\n\tat com.hazelcast.spi.impl.operationservice.Operation.call(Operation.java:184)\n\tat com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.call(OperationRunnerImpl.java:256)\n\tat com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:237)\n\tat com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:452)\n\tat com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:166)\n\tat com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.process(OperationThread.java:136)\n\tat com.hazelcast.spi.impl.operationexecutor.impl.OperationThread.executeRun(OperationThread.java:123)\n\tat com.hazelcast.internal.util.executor.HazelcastManagedThread.run(HazelcastManagedThread.java:102)\n","SERVERNAME":"rob-cache-8448d476d6-l9k2j"}

I check that hazelcast support this version and when I check official dockerfile there is java11. Is there also version with java 15 or I need to create my own dockerfile with java 15 ?

A: As you mention, the official Docker image uses Java 11. Note that your link points to the Enterprise version, the OSS version is here.
Because your code has been compiled with Java 15, it's not possible for the Java 11 runtime on the server-side to execute it.
Creating your own Dockerfile with a Java runtime 15+ will solve this issue.


text:
Q: How to apply custom styling to NSTableHeaderView? So I am going for a custom looking NSTableView. I've already successfully subclassed NSTableRowView and NSTextFieldCell to achieve the look I'm going for, however I'm struggling of getting rid of the default styling for the header. I seem to be able to tweak its frame, however I'm not sure where the rest of the default styling is coming from.
As you see on the screenshot the red area is the increased frame of the headerView. I'm using its CALayer to set the colour, however how to change the contents inside is beyond me...

Here's what I'm doing in the viewDidLoad of my ViewController
override func viewDidLoad() {
    super.viewDidLoad()
    tableView.delegate = self
    tableView.dataSource = self
    tableView.wantsLayer = true
    tableView.headerView?.frame = NSMakeRect(0, 0, (tableView.headerView?.frame.width)!, 32.00)
    tableView.headerView?.wantsLayer = true
    tableView.headerView?.layer?.backgroundColor = NSColor.red.cgColor
}

I've also tried subclassing NSTableHeaderView, however this class seems to be extremely limited in terms of the customizations I can make...
Any help would be appreciated?

A: The table view is view based but the header isn't and the header cells still are class NSTableHeaderCell. Use NSTableColumn's property headerCell. You can set the cell's properties like attributedStringValue and backgroundColor or replace the cells by instances of a subclass of NSTableHeaderCell and override one of the draw methods.

A: Play around with this to get inside the header.
 Remember to except the answer if it works for you.
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
    //Color for the  header.
    let topColor = UIColor(red: (70/255.0), green: 000/255.0, blue: 000/255.0, alpha: 255)

    //Location of label.
    let locationOfLabel = self.view.frame.width

    let headerView:UIView = UIView()

    //Locating the text in the label
    let title = UILabel(frame: CGRect(x: 0, y: 30, width: locationOfLabel, height: 21))
    title.textAlignment = .center

    //Changing the title in the label per the default.
    let defaults:UserDefaults = UserDefaults.standard
    defaults.synchronize()

    let cardSelector  = defaults.object(forKey: "selectorKeyID") as! Int
    switch (cardSelector) {
    case 0: title.text = "Personal"
    break
    case 1: title.text = "Saved"
    break
    case 2: title.text = "Favorite"
    break
    case 3: title.text = "Grouped"
    break
    default:
        break
    }
    //Coloring the text in the label
    //Add the label
    title.textColor = UIColor.gray

    headerView.addSubview(title)

    //Adding a button to the header.
    let closeBttn = UIButton(type: UIButtonType.system) as UIButton
    closeBttn.frame = CGRect(x: 0, y: 30, width: 90, height: 27)
    closeBttn.setTitle("Close", for: UIControlState())
    closeBttn.setTitleColor(buttonColor, for: UIControlState())
    closeBttn.titleLabel?.font = UIFont.systemFont(ofSize: 19, weight: UIFontWeightMedium)
    closeBttn.addTarget(self, action: #selector(MainTableViewController.close), for: UIControlEvents.touchUpInside)
    headerView.addSubview(closeBttn)

    let menuButton = UIButton(type: UIButtonType.system) as UIButton
    menuButton.frame = CGRect(x: locationOfLabel-53, y: 30, width: 27, height: 27)
    menuButton.setBackgroundImage(UIImage(named: "VBC Menu4.png"), for: UIControlState())
    menuButton.addTarget(self, action: #selector(MainTableViewController.menuButton), for: UIControlEvents.touchUpInside)
    headerView.addSubview(menuButton)

    //Coloring the header
    headerView.backgroundColor = topColor

    //Rounding the corners.
    headerView.layer.cornerRadius = 10
    headerView.clipsToBounds = true

    return headerView

}

 func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 70.0
}


text:
Q: Display Results By Date  $sql = mysqli_query($conn, "SELECT * FROM stock WHERE Date = '$date'");
$result = $conn->query($sql);

if ($result->num_rows > 0)
    {
    $d="D-";
         // output data of each row
        echo "

ID	Date	Product Code	Description	Delivery Order	Cartons	Items	Quantity	Sent_To
";

       while($row = $result->fetch_assoc())
       {
           echo "
" . $row["id"]. "	" . $row["Date"]. "	" . $row["Product_Code"]. "	" . $row["Description"]. "	".$d. $row["DEO"]. "	" . $row["Cartons"]. "	" . $row["Items"]. "	" . $row["Quantity"]. "	" . $row["Sent_To"]. "
";
       }
       echo "
";

Hello Guys When i echo $date it prints the date correctly but when i run this query i get an error

Warning: mysqli::query() expects parameter 1 to be string, object
  given in C:\xampp\htdocs\rmt\displaydate.php on line 9
Notice: Trying to get property of non-object in
  C:\xampp\htdocs\rmt\displaydate.php on line 11

Please help me to fix this error. Thanks in advance.

A: You're calling mysqli_query followed by $conn->query on the result from the first query. You only need to call one of them, for example;
$sql = "SELECT * FROM stock WHERE Date = '$date'";
$result = $conn->query($sql);


text:
Q: EnableCors without creation of Controller Instance I have next controller:
[EnableCors(origins: "*", headers: "*", methods: "*",
     SupportsCredentials = true)]
public class ResourceController {
    public ResourceController (ResourceRepository repository) {
    }
}

Where ResourceRepository is defined as
[PrincipalPermission(SecurityAction.Demand, Authenticated = true)]
public class ResourceRepository {

}

But when the browser issues OPTIONS request it turned out that .AttributeBasedPolicyProviderFactory tries to create an instance of ResourceController just to look for its attributes. As a result instanciation is failed with SecurityException "Request for principal permission failed."
Is it possible configure CORS for ASP.NET API so that it will not instanciate the controller?

A: You can host your Web API with OWIN and enable CORS for OWIN pipeline (see Microsoft.Owin.Cors NuGet package). You should register CORS middleware before Web API middleware. So as your CORS middleware goes first it will be executed before request even reaches Web API infrastructure.


text:
Q: Nginx 413 error does not get to the browser I think my situation is very similar to Why might a 413 not be flushed to the client immediately? , what is indented is where my situation is different
I have my local development server returning status 413 for oversized file uploads and the client is receiving these immediately - as I require. Both my error and access log show this, but it takes around 6 seconds, so I wonder if my browser is waiting to send the image? and then receive it the 413 error?
My remote server is the same version of Nginx and more-or-less the same configuration, but the 413 never reaches the browser.
An error indicating the data is oversized appears in the error log straight away and nothing appears in the access log. The browser continues to send the data and after 30 seconds the 413 status appears in the access log (and again in the error log) and the browser times out with an internal 'connection reset' error. Here is where my situation is different from this problem. I still get the (client intended to send too large body:) in error.log and (POST /path/to/my/imageupload HTTP/1.1 413) in access.log right away, but I also get a respond with no Status (in Chrome the status is failed or 0) right away
When I curl the same request I do get the 413 error respond. Which matches mgorven responded in that post.
I see mgorven said that the browser waits to send everything before receiving anything from server.
Is that why it doesn't accept the 413? Any idea how to fix it? If i set keepalive_requests to 0  would it break anything? like uploading big images (smaller than 5mb)?
So how do people handle nginx  413 errors without showing the nginx 413 error page?
Also along the same topic, the above happens when I try to upload through javascript. Part of my app has a Rails uploader, and when it uploads a large file, it just drops the connection. But my local box shows the nginx 413 error page. Any ideas how to get around this and just send a Json respond?

A: Setting keepalive_requests to 0 won't break anything, but it will disable persistent connections (which may result in a reduction in performance).
You can configure nginx to send a JSON response, but note that you'll still need the client to behave correctly and check for a response before finishing sending the request body.
/var/www/errors/413.json:
{"message": "Request Entity Too Large"}

/etc/nginx.conf:
location /errors {
    types {
        application/json    json;
        text/html   html;
        text/html   htm;
    }
}

error_page 413 /errors/413.json;


text:
Q: Policy Gradient: Why would shuffling data cause performance dropping down?
The above is the average scores every 100 episodes when the agent runs on a gym environment LunarLanderContinuous-v2. the orange and blue lines are the results when agents feed transitions sequentially to the policy gradient algorithm (e.g., ppo), while the red line is the result when agents shuffle collected transitions before feeding them to the algorithm. I don't understand why simply shuffling data would make such a difference. To my best knowledge, neural networks assume input data is IID, so algorithms such as DQN shuffles the data(or random sample from the replay buffer) to break the correlation. But here shuffling data seems to make things worse, why would this happen?
Here's my project https://github.com/xlnwel/Distributed-Model-Free-RL/tree/master/dppo.
Each worker samples transitions until a certain amount of transitions are collected, and then computes gradients, sending gradients to the learner for updating weights, then repeat the above process. The code corresponding to shuffling data is at line 143 to line 150 in worker.py.

A: I would say the difference is between an on-policy (Policy-gradient) and off-policy method (DQN for e.g.). You cannot shuffle the collected data because after fitting each episode, the policy itself changes. When you collect new samples, they are on new policy. Whereas, in case of DQN, you update the q-value function of given state-action pair whereby you can still use random samples together and update them.


text:
Q: Any way to remedy EF slow startup? I'm using a legacy ObjectContext for my EF 5 project.  The project has grown significantly since inception, as projects do, and now we are sitting at around 400 tables, plus a handful of views that are also included in the edmx model.  It all works fine... but the startup time from cold is getting to be a real problem, both for programmers who are trying to debug stuff and have to wait upwards of a minute before the web site is ready to run, and for testers and users of QA and production builds, who likewise have to wait a long time before each new deployment is ready for use.
We also have a development road map that is going to add ever more tables to our DB.  So this problem is only going to get worse.
Is there something we can do to speed up our startup times?  Would switching to DbContext help?  And if so, how disruptive would that be for existing code that is using the ObjectContext?

A: To answer your question, yes there are a lot of things you can do to speed up your start times such as using Pre-Generated Views (only doable with DbContext), using Foreign Key associations to reduce view generation cost and moving your model to a separate assembly.
e.g.
"When your model is included directly in your application's project and you generate views through a pre-build event or a T4 template, view generation and validation will take place whenever the project is rebuilt, even if the model wasn't changed. If you move the model to a separate assembly and reference it from your application's project, you can make other changes to your application without needing to rebuild the project containing the model."
Read this lengthy MSDN Performance Considerations for EF4, EF5, EF6 article.
DBContext is just a wrapper around ObjectContext. You can still get a reference to ObjectContext through DBContext. So I doubt that will speed up anything, if anything it will probably slow things down.


text:
Q: Inconsistent behavior when removing minimize button from Windows Terminal I am using the Windows API to disable the minimize button from the current console window (Windows Terminal).
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <windows.h>

bool disableMinimize ( HWND hwnd )
{
    // use styles
    DWORD style = GetWindowLong( hwnd, GWL_STYLE );
    DWORD exStyle = GetWindowLong( hwnd, GWL_EXSTYLE );
    // set the window styles
    style &= ~WS_MINIMIZEBOX;
    exStyle &= ~WS_EX_APPWINDOW;
    // set the window styles
    SetWindowLong( hwnd, GWL_STYLE, style );
    SetWindowLong( hwnd, GWL_EXSTYLE, exStyle );
    // return
    return true;
}

int main() {
    disableMinimize( GetConsoleWindow() );
}

What is expected is that the minimize (-) button on the window is greyed out or inaccessible, but this doesn't seem to be working when I am running on Windows Terminal.
The theory I have is that Windows Terminal is forcing WS_MINIMIZEBOX to be true, otherwise I am stumped.
What am I missing?

A: The Terminal draws its own minimize button (in XAML), and doesn't rely on the win32 styling at all for this. If you'd like to remove the minimize button from the Terminal, you should probably file a feature request on the Terminal repo.
<here be dragons>
Theoretically, you can get the win32 titlebar back by disabling showTabsInTitlebar. Know, however, that GetConsoleWindow isn't going to get you the handle of the actual Terminal HWND - it will only get you a hidden HWND associated with that tab. I cannot stress this highly enough - don't mess with GetConsoleWindow. It's a bad API, and it really does NOT play nice with the Terminal.
</>


text:
Q: Wordpress ACF: Querying Relationship, keeping paragraph breaks I'm using the Wordpress plugin Advanced Custom Fields to tie data together into a single post.
Here is my query for one of the relationships:
<?php $notes = get_field('episode_notes'); ?>
<?php if(!empty($notes)): ?>
    <?php foreach($notes as $note): ?>

<?php echo $note->post_content); ?>

    <?php endforeach; ?>
<?php endif; ?>

The post_content is being returned without any paragraph/line breaks (though italics, bold, etc. seem okay). I've tried this without across-the-board success:
<?php echo str_replace('\r','
', $note->post_content); ?>

What do I need to do differently?

A: Have you tried wpautop?
<?php echo wpautop( $note->post_content, true ); ?>


text:
Q: Import django doesn't work? Pythonpath? I'm running Windows with Python 2.7 and (I believe) Django 1.0. I installed Django using the Bitnami Djangostack. The strange thing is, when I typed "import django" in python, I got this error:
Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
ImportError: No module named django

I searched online for an answer, but all of the answers I found were "django needs to be in your PYTHONPATH." I'm new to Python, so I don't know what this means. Can someone please explain this to me?

A: It means that you need to install Django under Python 2.7 as well.

A: if you type the following at the command line what does it say?
python --version

My guess is that bitnami installed into one python version and you are using another, or when they installed it they didn't put it in the pythonpath. I don't know much about the bitnami stack but have you looked at these instructions?
https://docs.djangoproject.com/en/1.3/topics/install/


text:
Q: overusing ".present?" in rails controllers I have a question about process if i could be doing this a better way. I'm working on a rails app and i run into page errors when certian elements are not present. For example here is my show action
def show
    @article = Article.friendly.find(params[:article_slug])
    @section_slug = Section.find_by_id(@article.section_id).slug if @article.section_id.present?
    @issue_slug = Issue.find_by_id(@article.issue_id).slug if @article.issue_id.present?
    @next_article = @article.next_article if @article.next_article.present?
    @prev_article = @article.prev_article if @article.prev_article.present?
    @article_author = Author.find_by_id(@article.author_id)

    render :layout => 'magazine'
    session[:return_to] = request.referer
    #if request.path != article_path(@article)
     #return redirect_to @article, :status => :moved_permanently
    #end
  end

Should i be using .present? as much as i am? is there something better that will make pages not fail so completely if an element is not present? Just trying to learn rails in a way that will lead to better code.

A: First, why are you not using relations? If Article already has section_id then you should be getting to the Section using @article.section. belongs_to :section should be in your Article model.
The above is true for Issue and Author as well.
In answer to your question: No, you should not be using .present? as much as you are.
Here how I would code this action:
def show
  @article = Article.friendly.find(params[:article_slug])
  @section_slug = @article.section.try(:slug)
  @issue_slug   = @article.issue.try(:slug)
  @next_article = @article.next_article
  @prev_article = @article.prev_article
  @author       = @article.author

  render :layout => 'magazine'
  session[:return_to] = request.referer
end

There is no reason for @prev_article = @article.prev_article if @article.prev_article.present?. If your views depend on @prev_article they will see a nil value with or without the if @article.prev_article.present?. Your view is going to have to do .present? or similar anyways.
I might actually do away with all but @article here and have my views ask the article for its author,  next_article, etc.

A: I think so you need to do only:
@next_article = @article.next_article
@prev_article = @article.prev_article

If next_article is not present then it will be nil so with present condition and without present condition the value of @next_article and @prev_article will be nil

A: welcome to RoR
if @article.prev_article.present?

is the same as
if @article.prev_article

and
@article_author = Author.find_by_id(@article.author_id)

looks like you are missing out on a belongs_to relationship. If in your model you define as follows:
class Author < ActiveRecord::Base
   has_many :articles
end
class Article < ActiveRecord::Base
 belongs_to :author
end

Then you can simply call
@article.author

to retrive the author object. Please do the same for section and issue.
When you want to query a database using ids, ActiveRecord allows you to do this:
@user = User.find(1)

It looks like you are trying to paginate articles. Give the Kaminari Gem (https://github.com/amatsuda/kaminari) and Will_Paginate Gem(https://github.com/mislav/will_paginate) a go, they come quite well built and maintained.
@issue_slug = Issue.find_by_id(@article.issue_id).slug if @article.issue_id.present?

In order to not error out when calling a method, the try method is apt.
@article.section.try(:slug)


text:
Q: Haskell - create instance of class (how to do it right?) I read the chapter about that topic in "learn you a haskell" and tried to find some hints on different websites - but are still unable to solve the following task.
Im a haskell newbie (6 weeks of "experience") and its the first time I have to work with instances.
So here is the task, my code has to pass the HUnit tests and the end. I tried to implement the instances but it seems like I´ve missed something there. Hope you can help me! THX
module SemiGroup where

{-

A type class 'SemiGroup' is given. It has exactly one method: a binary operation
called '(<>)'. Also a data type 'Tree' a newtype 'Sum' and a newtype 'Max' are
given. Make them instances of the 'SemiGroup' class.
The 'Tree' instance should build a 'Branch' of the given left and right side.
The 'Sum' instance should take the sum of its given left and right side. You need
a 'Num' constraint for that.
The 'Max' instance should take the maximum of its given left and right side. You
also need a constraint for that but you have to figure out yourself which one.
This module is not going to compile until you add the missing instances.

-}

import Test.HUnit (runTestTT,Test(TestLabel,TestList),(~?=))

-- | A semigroup has a binary operation.
class SemiGroup a where
    (<>) :: a -> a -> a

-- Leaf = Blatt, Branch = Ast
-- | A binary tree data type.
data Tree a = Leaf a
            | Branch (Tree a) (Tree a)
                deriving (Eq,Show)

-- | A newtype for taking the sum.
newtype Sum a = Sum {unSum :: a}

-- | A newtype for taking the maximum.
newtype Max a = Max {unMax :: a}

instance SemiGroup Tree where
    (<>) x y = ((x) (y))

instance SemiGroup (Num Sum) where
    (<>) x y = x+y

instance SemiGroup (Eq Max) where
    (<>) x y = if x>y then x else y

-- | Tests the implementation of the 'SemiGroup' instances.
main :: IO ()
main = do
    testresults <- runTestTT tests
    print testresults

-- | List of tests for the 'SemiGroup' instances.
tests :: Test
tests = TestLabel "SemiGroupTests" (TestList [
    Leaf "Hello" <> Leaf "Friend" ~?= Branch (Leaf "Hello") (Leaf "Friend"),
    unSum (Sum 4 <> Sum 8) ~?= 12,
    unMax (Max 8 <> Max 4) ~?= 8])

I tried something like:
class SemiGroup a where
    (<>) :: a -> a -> a

-- Leaf = Blatt, Branch = Ast
-- | A binary tree data type.
data Tree a = Leaf a
            | Branch (Tree a) (Tree a)
                deriving (Eq,Show)

-- | A newtype for taking the sum.
newtype Sum a = Sum {unSum :: a}

-- | A newtype for taking the maximum.
newtype Max a = Max {unMax :: a}

instance SemiGroup Tree where
    x <> y = Branch x y

instance Num a => SemiGroup (Sum a) where
    x <> y = x+y

instance Eq a => SemiGroup (Max a) where
    x <> y = if x>y then x else y

But there a still some failures left! At least the wrap/unwrap thing that "chi" mentioned. But I have no idea. maybe another hint ? :/

A: I fail to see how to turn Tree a into a semigroup (unless it has to be considered up-to something).
For the Sum a newtype, you need to require that a is of class Num. Then, you need to wrap/unwrap the Sum constructor around values so that: 1) you take two Sum a, 2) you convert them into two a, which is a proper type over which + is defined, 3) you sum them, 4) you turn the result back into a Sum a.
You can try to code the above yourself starting from
instance Num a => Semigroup (Sum a) where
   x <> y = ...   -- Here both x and y have type (Sum a)

The Max a instance will require a similar wrap/unwrap code.

A further hint: to unwrap a Sum a  into an a you can use the function
unSum :: Sum a -> a

to wrap an a into a Sum a you can use instead
Sum :: a -> Sum a

Note that both functions Sum, unSum are already implicitly defined by your newtype declaration, so you do not have to define them (you already did).
Alternatively, you can use pattern matching to unwrap your values. Instead of defining
x <> y = ... -- x,y have type Sum a (they are wrapped)

you can write
Sum x <> Sum y = ...   -- x,y have type a (they are unwrapped)

A: Pay attention to the types.  Either manually, or with some help from GHCi, figure out the type of the functions you are writing -- you'll find they don't match the types that the typeclass instance needs.  You'll use wrapping and unwrapping to adjust the types until they work.


text:
Q: How can I translate SVG group element to the center of the root SVG? Question: How can I translate the center of a SVG group element to the center of the root SVG. I tried to use transform="translate(x,y)" on the <g> element, but this transformation will only translate with respect to the top left corner of the group element.
Example case and goal: In the following SVG, the two rectangles <rect> are grouped together with <g>. Assume we don't know the position, size, and which types are elements are inside the group. We only know the width/height of the parent SVG. Goal is to translate the center of the group (bounding box of the two rectangles) to the center of the root SVG. The issue is that we don't know the height/width of the "bounding box" which is the group itself, thus when using transform="translate(x,y)" alone won't get us to the center of the root SVG.
<svg width="500px" height="300px" preserveAspectRatio="none" viewBox="0,0,5.0,3.0">
    <g transform="translate(0,0)">
        <rect x="1" y="0.25" width="0.5" height="0.5" fill="green" />
        <rect x="1.25" y="1" width="0.5" height="0.5" fill="red" />
    </g>
</svg>

Requirements:

*

*The solution can only use pure SVG. CSS or external libraries can NOT be used.

*Using Python to do basic calculation is okay. However, remember we don't what elements are inside the <g>.

*The coordinate system for the root SVG (viewBox, width, height) must not be change because in example use case, these coordinate system are used for conversion of real world spatial units (ex: millimeters) to pixels for the end application.

A: You need some way to do calculations. I'm using Javascript:

const SVG_NS = 'http://www.w3.org/2000/svg';
const svg = document.querySelector("svg");
// the viewBox of the svg element splited
let svgVB = svg.getAttribute("viewBox").split(/[ ,]+/);

let o = test.getBBox();
let oCenter = {};//the center of the g#test element
oCenter.x = o.x + o.width/2;
oCenter.y = o.y + o.height/2;

// the valuefor the transform attribute
let tr = `
translate(${-oCenter.x},${-oCenter.y})
translate(${svgVB[2]/2},${svgVB[3]/2})`;

test.setAttributeNS(null, "transform",tr);

// for debugging I'm drawing the bounding box
bbox.setAttributeNS(null, "transform",tr);

function drawRect(o, parent) {
  let rect = document.createElementNS(SVG_NS, 'rect');
  for (let name in o) {
      rect.setAttributeNS(null, name, o[name]);
  }
  parent.appendChild(rect);
  return rect;
}

drawRect(o, bbox);
svg{border:1px solid;}
<svg width="500px" height="300px" preserveAspectRatio="none" viewBox="0,0,5.0,3.0">
  <g id="bbox"></g>
    <g id="test" transform="translate(0 0)">
        <rect x="1" y="0.25" width="0.5" height="0.5" fill="green" />
        <rect x="1.95" y="1" width="0.5" height="0.5" fill="red" />
    </g>
</svg>

I hope it helps


text:
Q: area of n-gon of prime points Using prime points (2,3), (5,7) (11,13)....to a last prime point to form an irregular n-gon by connecting each consecutive point with a line and connecting the first point to the last point with NO previous line being intersected by this longest line, do you
think there is some n-gon of maximum area?  After this, all increasing last points will have a connecting line from (2,3) to this last point that will always intersect  some previous line.
As an example. I want to go from (2,3) to (59,61) without having this line intersect any of the previous lines connecting successive prime points.  It can be  done to give an n-gon with an area of 127.  Clarity  for this question would result if you drew a graph for the first 20 prime points to observe what the curve is doing.
A variation of this question arises when prime points are redefined as (2,3), (3,5), (5,7)...and one connects (2,3) to a final point of this form to give an n-gon having no intersections of the connecting line with any of the lines connecting the previous points.  Example of this is going from (2,3) to (41,43)
to give an area of 200; from (2,3) to (71,73) the area of 381.  In either case of how prime points are defined, do you think there is a maximum n-gon for each in which the connecting line does not intersect any previous connecting lines between successive points?


text:
Q: How to avoid double insert in Oracle with multithreading In my application, while I make INSERT into Oracle I got a lot of exception about the double insert.
My test code looks like that
class SomeClass{
EntityManager em;
Dao dao;

@Override
void insert(String a, String b){
    MyObject object =new MyObject(a,b);
    dao.insertObject(object);
    }
}

class OtherClass{
    private final ExecutorService completableFutureExecutor =
            new ThreadPoolExecutor(10, 11, 30L, TimeUnit.SECONDS, new SynchronousQueue<>());

    public void method() {

        Runnable task1 = () -> dao.insert("a","b");
        for (int i = 0; i < 5; i++) {
            completableFutureExecutor.submit(task1);
        }
    }
}

In openJpa log I see something like that

240981  JpaPersistenceUnit  TRACE  [pool-25-thread-3] openjpa.jdbc.SQL - <t 1427395137, conn 1023570122> executing prepstmnt 743213969 SELECT t0.COLUMN1, t0.COLUMN2  FROM TABLE t0 WHERE t0.COLUMN2 = ? AND t0.COLUMN1 = ? [params=(String) a, (String) b]
240983  JpaPersistenceUnit  TRACE  [pool-25-thread-9] openjpa.jdbc.SQL - <t 1116539025, conn 246735198> executing prepstmnt 468904024 SELECT t0.COLUMN1, t0.COLUMN2  FROM TABLE t0 WHERE t0.COLUMN2 = ? AND t0.COLUMN1 = ? [params=(String) a, (String) b]
240986  JpaPersistenceUnit  TRACE  [pool-25-thread-5] openjpa.jdbc.SQL - <t 2107513837, conn 1168031715> executing prepstmnt 1872262728 SELECT t0.COLUMN1, t0.COLUMN2  FROM TABLE t0 WHERE t0.COLUMN2 = ? AND t0.COLUMN1 = ? [params=(String) a, (String) b]
240986  JpaPersistenceUnit  TRACE  [pool-25-thread-1] openjpa.jdbc.SQL - <t 1881630463, conn 2024928498> executing prepstmnt 1258578230 SELECT t0.COLUMN1, t0.COLUMN2  FROM TABLE t0 WHERE t0.COLUMN2 = ? AND t0.COLUMN1 = ? [params=(String) a, (String) b]
240986  JpaPersistenceUnit  TRACE  [pool-25-thread-7] openjpa.jdbc.SQL - <t 1202968848, conn 1876787130> executing prepstmnt 1733696457 SELECT t0.COLUMN1, t0.COLUMN2  FROM TABLE t0 WHERE t0.COLUMN2 = ? AND t0.COLUMN1 = ? [params=(String) a, (String) b]

240998  JpaPersistenceUnit  TRACE  [pool-25-thread-9] openjpa.jdbc.SQL - <t 1116539025, conn 246735198> executing prepstmnt 752805342 INSERT INTO TABLE (  COLUMN1, COLUMN2  ) VALUES (?, ?)  [params= (String) a,   (String) b]
240999  JpaPersistenceUnit  TRACE  [pool-25-thread-3] openjpa.jdbc.SQL - <t 1427395137, conn 1023570122> executing prepstmnt 1035550395 INSERT INTO TABLE (  COLUMN1, COLUMN2  ) VALUES (?, ?)  [params= (String) a,   (String) b]
240999  JpaPersistenceUnit  TRACE  [pool-25-thread-5] openjpa.jdbc.SQL - <t 2107513837, conn 1168031715> executing prepstmnt 1439514282 INSERT INTO TABLE (  COLUMN1, COLUMN2  ) VALUES (?, ?)  [params=  (String) a,   (String) b]
241000  JpaPersistenceUnit  TRACE  [pool-25-thread-1] openjpa.jdbc.SQL - <t 1881630463, conn 2024928498> executing prepstmnt 1158780577 INSERT INTO TABLE (  COLUMN1, COLUMN2  ) VALUES (?, ?)  [params=  (String) a,   (String) b]
241000  JpaPersistenceUnit  TRACE  [pool-25-thread-7] openjpa.jdbc.SQL - <t 1202968848, conn 1876787130> executing prepstmnt 1082517334 INSERT INTO TABLE (  COLUMN1, COLUMN2  ) VALUES (?, ?)  [params=  (String) a,   (String) b]

41018  JpaPersistenceUnit  TRACE  [pool-25-thread-4] openjpa.Runtime - An exception occurred while ending the transaction.  This exception will be re-thrown.<openjpa-2.4.0-r422266:1674604 fatal store error> org.apache.openjpa.util.StoreException: The transaction has been rolled back.  See the nested exceptions for details on the errors that occurred.
FailedObject: com.test.SomeClass@19df04ab
 at org.apache.openjpa.kernel.BrokerImpl.newFlushException(BrokerImpl.java:2368)
 at org.apache.openjpa.kernel.BrokerImpl.flush(BrokerImpl.java:2205)
 at org.apache.openjpa.kernel.BrokerImpl.flushSafe(BrokerImpl.java:2103)
 at org.apache.openjpa.kernel.BrokerImpl.beforeCompletion(BrokerImpl.java:2021)
 at org.apache.openjpa.kernel.LocalManagedRuntime.commit(LocalManagedRuntime.java:81)
 at org.apache.openjpa.kernel.BrokerImpl.commit(BrokerImpl.java:1526)
 at org.apache.openjpa.kernel.DelegatingBroker.commit(DelegatingBroker.java:932)
 at org.apache.openjpa.persistence.EntityManagerImpl.commit(EntityManagerImpl.java:569)
 at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:514)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:755)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:724)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:475)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:270)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:633)
 at com.test.Dao$$EnhancerBySpringCGLIB$$c4aa5f08.insertObject(<generated>)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
 at java.lang.reflect.Method.invoke(Method.java:498)
 at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
 at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.doInvoke(ServiceInvoker.java:58)
 at org.springframework.osgi.service.importer.support.internal.aop.ServiceInvoker.invoke(ServiceInvoker.java:62)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:132)
 at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:120)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invokeUnprivileged(ServiceTCCLInterceptor.java:56)
 at org.springframework.osgi.service.util.internal.aop.ServiceTCCLInterceptor.invoke(ServiceTCCLInterceptor.java:39)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.osgi.service.importer.support.LocalBundleContextAdvice.invoke(LocalBundleContextAdvice.java:59)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.support.DelegatingIntroductionInterceptor.doProceed(DelegatingIntroductionInterceptor.java:132)
 at org.springframework.aop.support.DelegatingIntroductionInterceptor.invoke(DelegatingIntroductionInterceptor.java:120)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
 at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:204)
 at com.sun.proxy.$Proxy255.insertObject(Unknown Source)
 at com.test.OtherClass.lambda$method$5(OtherClass.java:146)
 at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
 at java.util.concurrent.FutureTask.run(FutureTask.java:266)
 at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
 at java.lang.Thread.run(Thread.java:748)
Caused by: <openjpa-2.4.0-r422266:1674604 fatal store error> org.apache.openjpa.util.ObjectExistsException: ORA-00001: unique constraint (TABLE_PK) violated
 {prepstmnt 1119780936 INSERT INTO TABLE (COLUMN1, COLUMN2) VALUES (?, ?) [params=(String) a, (String) b]} [code=1, state=23000]
FailedObject: com.test.entities.Table@19df04ab
 at org.apache.openjpa.jdbc.sql.DBDictionary.narrow(DBDictionary.java:4986)
 at org.apache.openjpa.jdbc.sql.DBDictionary.newStoreException(DBDictionary.java:4961)
 at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:133)
 at org.apache.openjpa.jdbc.sql.SQLExceptions.getStore(SQLExceptions.java:75)
 at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushBatch(BatchingPreparedStatementManagerImpl.java:225)
 at org.apache.openjpa.jdbc.kernel.BatchingConstraintUpdateManager.flush(BatchingConstraintUpdateManager.java:63)
 at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:104)
 at org.apache.openjpa.jdbc.kernel.AbstractUpdateManager.flush(AbstractUpdateManager.java:77)
 at org.apache.openjpa.jdbc.kernel.JDBCStoreManager.flush(JDBCStoreManager.java:731)
 at org.apache.openjpa.kernel.DelegatingStoreManager.flush(DelegatingStoreManager.java:131)
 ... 43 more
Caused by: org.apache.openjpa.lib.jdbc.ReportingSQLException: ORA-00001: unique constraint (TABLE_PK) violated
 {prepstmnt 1119780936 INSERT INTO TABLE (COLUMN1, COLUMN2) VALUES (?, ?) [params=(String) a, (String) b]} [code=1, state=23000]
 at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:218)
 at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.wrap(LoggingConnectionDecorator.java:194)
 at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator.access$1000(LoggingConnectionDecorator.java:58)
 at org.apache.openjpa.lib.jdbc.LoggingConnectionDecorator$LoggingConnection$LoggingPreparedStatement.executeUpdate(LoggingConnectionDecorator.java:1133)
 at org.apache.openjpa.lib.jdbc.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:275)
 at org.apache.openjpa.jdbc.kernel.JDBCStoreManager$CancelPreparedStatement.executeUpdate(JDBCStoreManager.java:1791)
 at org.apache.openjpa.jdbc.kernel.PreparedStatementManagerImpl.executeUpdate(PreparedStatementManagerImpl.java:268)
 at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushSingleRow(BatchingPreparedStatementManagerImpl.java:254)
 at org.apache.openjpa.jdbc.kernel.BatchingPreparedStatementManagerImpl.flushBatch(BatchingPreparedStatementManagerImpl.java:157)
 ... 48 more

How I can avoid that? Because A lot of errors like that I have in production.
UPD added new log into snippet.
My application locates on both servers (nodes). Each server connected to DB. So, my test we can multiply by 2.

A: You could possibly synchronize your doa object, meaning it can only be run by one thread at a time.
  @Override
  void insert(String a, String b) {
    MyObject object = new MyObject(a, b);
    synchronized (dao) {
      dao.insertObject(object);
    }
  }

Something like the above

The main advantage of synchronized keyword is we can resolve data
  inconsistency problems. But the main disadvantage of synchronized
  keyword is it increases waiting time of thread and effects performance
  of the system. Hence, if there is no specific requirement it is never
  recommended to use synchronized keyword.

A: Using a single EntityManager from concurrent threads is most likely a bad idea, as you may have seen from the logs: Best case is that an exception in one thread rolls back the single transaction of the EM which all other threads try to use too. Worst case is all kinds of concurrency problems, race conditions and whatnot.

I want it INSERT just once and if It already in DB, select it. But I
  have about 5 methods in different classes which can call that INSERT
  in time, because of that, that exception should be handled

In that case you will probaly have no other choice than to synchronize your DAO calls via some other means; could be done by locking on some existing record in the DB, or in any other way. You may also want to try EntityManager.merge(), but I don't think that would solve your problem of two seperate machines writing concurrently.

A: I use now memcache, but it is not final solution
 private int expire = 2;

 public <T> void insert(Supplier<T> supplier, String... keyLine) throws InterruptedException, MemcachedException, TimeoutException {
        String key = ParseUtils.collectToKeyWithDot(keyLine);
        T value = getCache(key);
        if (value == null) {
            value = supplier.get();
            setCache(key, value);
        }
    }

 private <T> Boolean setCache(String key, T value) throws InterruptedException, MemcachedException, TimeoutException {
        return memcacheClient.set(key, expire, value);
    }

    private <T> T getCache(String key) throws InterruptedException, MemcachedException, TimeoutException {
        return memcacheClient.get(key);
    }

Here, I store my first INSERT into DB and also into the cache for 2 seconds. In that 2 seconds, if any Thread tries to insert the same values into DB and wouldn't happen. First of all, it would be checked in the cache. For me, 2 seconds enough to avoid exceptions.
P.S.  I'm still looking for a more elegant solution.

A: You might want to consider a delayed write from the data access object, something like this -
class SomeClass {
    private EntityManager em;
    private Dao dao;
    private Set<MyObject> writableObjects = new HashSet<>();

    @Override
    public void insert(String a, String b) {
        MyObject object = new MyObject(a, b);
        writableObjects.add(object);
    }

    @override
    public void commit() {
        writableObjects.forEach(object -> dao.insertObject(object));
    }
}

class OtherClass {
    private final ExecutorService completableFutureExecutor = new ThreadPoolExecutor(10, 11, 30L, TimeUnit.SECONDS,
            new SynchronousQueue<>());

    public void method() {

        Runnable task1 = () -> dao.insert("a", "b");
        for (int i = 0; i < 5; i++) {
            completableFutureExecutor.submit(task1);
        }

        dao.commit();
    }
}


text:
Q: Multidimensional FourierCoefficient, how to do / how to get as discrete deltas I'm trying to turn a pretty nasty differential equation into a spectral form. And while I have done most of the work by hand, I want to check my work with Mathematica.
One step I need is the fourier series of a external potential. If I have something simple like
FourierCoefficient[Cos[x]*Cos[y],{x,y},{n,m}]

It gives me 0
What I'd expect to get is
1/4 (m==-1 || m==+1) && (n==-1 || n==+1)

I get the correct answer when I do
FourierCoefficient[Cos[y]*FourierCoefficient[Cos[x],x,n],y,m]

But that is cumbersome since I need to manually split the terms. It does not scale when I have a long and complicated expression. Has anybody had this problem before? Do you know how I can fix it?
Lastly, It would be much more convenient if I can turn
1/4 (m==-1 || m==+1) && (n==-1 || n==+1)

Into something like
1/4 (DiscreteDelta[m-1] + DiscreteDelta[m+1]) * (DiscreteDelta[n-1] + DiscreteDelta[n+1])

or more preferebly
1/4 (KroneckerDelta[m,1] + KroneckerDelta[m,-1]) * (KroneckerDelta[n,1] + KroneckerDelta[n,-1])

Does anyone know of any functions or shortcuts I can use to turn the AND and OR outputs into a more suitable format?
Thank You!
Edit: Thanks for your feedback, it seems like this is a bug in Mathematica and I submitted a bug report. Also, I did not submit the whole output for the second expression, technically it was this.
FourierCoefficient[Cos[y]*FourierCoefficient[Cos[x],x,n],y,m]

\begin{cases}  \frac{1}{4} & (m=-1 || m=1) \&\& (n=-1||n=1) \\  0
& \text{True} \end{cases}


text:
Q: Selenium Python: How to web scrape the element text I am trying to webscrap data from roulette game.
While trying to
find element by class name (roulette_round_result-position__text)

I am getting this output:
<selenium.webdriver.remote.webelement.WebElement (session="d4f20fd17bf4037ed8cf50b00e844a7f", element="f12cf837-6c77-4c90-9da2-7b5fb9da9e5d")>

Any idea how to scrap this value? (In this case number 2)
My code:
number_1=0
    while number_1 == 0:
        try:
            number_1 = self.driver.find_element_by_class_name('roulette-round-result-position__text')
        except:
            pass

Screen shot from DevTools:

A: You are printing the WebElement. Hence you see the output as:
<selenium.webdriver.remote.webelement.WebElement (session="d4f20fd17bf4037ed8cf50b00e844a7f", element="f12cf837-6c77-4c90-9da2-7b5fb9da9e5d")>

Instead you may like to print the text within the element as:
number_1 = self.driver.find_element_by_class_name('roulette-round-result-position__text')
print(number_1.text)

or
print(self.driver.find_element_by_class_name('roulette-round-result-position__text').text)


text:
Q: Send file via Jersey and x-www-form-urlencoded I'm trying to invoke REST service with the following client code with the idea to send some String message details as well as the attachment file:
ClientConfig config = new DefaultClientConfig();
config.getClasses().add(FormProvider.class);
Client client = Client.create(config);
WebResource webResource = client.resource("http://some.url/path1/path2");

File attachment = new File("./file.zip");

FormDataBodyPart fdp = new FormDataBodyPart(
            "content",
            new ByteArrayInputStream(Base64.encode(FileUtils.readFileToByteArray(attachedLogs))),
            MediaType.APPLICATION_OCTET_STREAM_TYPE);
form.bodyPart(fdp);

ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, form);

The server I'm targeting accepts Base64 encoded content, so that is why the additional transferring from File to ByteArray.
Also, I have found that class com.sun.jersey.core.impl.provider.entity.FormProvider is noted with both for production and consuming of "x-www-form-urlencoded" requests.
@Produces({"application/x-www-form-urlencoded", "*/*"})
@Consumes({"application/x-www-form-urlencoded", "*/*"})

But still I end-up with the following stacktrace:
com.sun.jersey.api.client.ClientHandlerException: com.sun.jersey.api.client.ClientHandlerException: A message body writer for Java type, class com.sun.jersey.multipart.FormDataMultiPart, and MIME media type, application/x-www-form-urlencoded, was not found at com.sun.jersey.client.urlconnection.URLConnectionClientHandler.handle(URLConnectionClientHandler.java:149) ~[jersey-client-1.9.1.jar:1.9.1]
at com.sun.jersey.api.client.Client.handle(Client.java:648) ~[jersey-client-1.9.1.jar:1.9.1]
at com.sun.jersey.api.client.WebResource.handle(WebResource.java:670) ~[jersey-client-1.9.1.jar:1.9.1]
at com.sun.jersey.api.client.WebResource.access$200(WebResource.java:74) ~[jersey-client-1.9.1.jar:1.9.1]
at com.sun.jersey.api.client.WebResource$Builder.post(WebResource.java:563) ~[jersey-client-1.9.1.jar:1.9.1]

Any help on this one?

A: I managed to get the thing working on the client side. The problem was that I was forcing sending of file as separate message body part, while x-www-form-urlencoded is actually packing all of the data as parameters in the query that is the entire body.
So the working client code if you want to send attachment via Jersey post method would be:
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource("http://some.url/path1/path2");

MultivaluedMapImpl values = new MultivaluedMapImpl();
values.add("filename", "report.zip");
values.add("text", "Test message");
values.add("content", new String(Base64.encode(FileUtils.readFileToByteArray(attachedLogs))));
ClientResponse response = webResource.type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class, values);

The Apache Commons' Base64 encoder was required in my case to transform file into encoded byte array, not sure if this is general requirement.

A: try using Multipart/form-data instead of application/x-www-form-urlencoded. This tutorial might help.


text:
Q: displaying errors in jsf fragment with  tag I was just wondering if I could display errors on a separate jsp fragment.
I have a requirement where I have to display hyperlink errors (i.e clicking any error would focus to respective input field)
For example, if I have a form and there are 20 fields, then I am suppose to use 20 times <t:message> tag. I know I can use single <t:messages> tag for all errors, but I have a requirement to focus individual field and I am not sure How we implement this using <t:messages>. However onclick event from <t:message> tag solves my issue but using 20 tags leave a big space under heading and page does not look nice.
So I was thinking if I could put all the errors tag on separate jsf fragment and later do jsp include on the main page.
I tried, but error messages are not being displayed.
Does any body have any idea, how do I accomplish this?

A: I take it that t:message is the Tomahawk control.

Perhaps a custom JSF control would fit the bill - sometimes you can't manipulate the existing tags to get the exact output you want.
You can get the messages from the FacesContext. The control's renderer writes the HTML to the page:
package custom;    /*imports omitted*/

public class CustomErrorRenderer extends Renderer {

  @Override @SuppressWarnings("unchecked")
  public void encodeEnd(FacesContext context,
      UIComponent component) throws IOException {
    ResponseWriter writer = context.getResponseWriter();
    writer.startElement("div", component);
    writer.writeAttribute("id", component.getClientId(context), "id");
    writer.writeAttribute("style", "color: red", null);
    writer.startElement("ul", null);
    Iterator<String> clientIds = context.getClientIdsWithMessages();
    while (clientIds.hasNext()) {
      String clientId = clientIds.next();
      Iterator<FacesMessage> messages = context.getMessages(clientId);
      if (!messages.hasNext()) { continue; }
      String javaScript = "var field = document.getElementById('"
          + clientId + "');" + "if(field == null) return false;"
          + "field.focus(); return false;";
      writer.startElement("li", null);
      writer.startElement("a", null);
      writer.writeAttribute("onclick", javaScript, null);
      writer.writeAttribute("href", "#", null);
      while (messages.hasNext()) {
        writer.writeText(messages.next().getSummary(), null);
      }
      writer.endElement("a");
      writer.endElement("li");
    }
    writer.endElement("ul");
    writer.endElement("div");
  }
}

This renderer is defined in faces-config.xml:
  <render-kit>
    <description>add to base HTML_BASIC renderkit</description>
    <display-name>HTML_BASIC</display-name>
    <render-kit-id>HTML_BASIC</render-kit-id>
    <renderer>
      <display-name>CustomErrorRenderer</display-name>
      <component-family>javax.faces.Output</component-family>
      <renderer-type>custom.CustomErrorRenderer</renderer-type>
      <renderer-class>custom.CustomErrorRenderer</renderer-class>
    </renderer>
  </render-kit>

Since the sample component doesn't require any special attributes or logic, it can be defined using the existing UIOutput component:
  <component>
    <display-name>CustomErrorMessages</display-name>
    <component-type>custom.Errors</component-type>
    <component-class>javax.faces.component.UIOutput</component-class>
  </component>

To integrate the control with JSPs, you also need to provide a tag class:
package custom;

import javax.faces.webapp.UIComponentELTag;

public class CustomErrorTag extends UIComponentELTag {

  @Override
  public String getComponentType() {
    return "custom.Errors";
  }

  @Override
  public String getRendererType() {
    return "custom.CustomErrorRenderer";
  }

}

This is defined in a TLD file:
<?xml version="1.0" encoding="UTF-8"?>
<taglib xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd"
  version="2.1">
  <tlib-version>1.0</tlib-version>
  <short-name>custom</short-name>
  <uri>http://custom</uri>
  <tag>
    <name>errors</name>
    <tag-class>custom.CustomErrorTag</tag-class>
    <body-content>empty</body-content>
  </tag>
</taglib>

If you wish to include this via a separate page, this sample JSP holds the control:
<%@ taglib prefix="custom" uri="http://custom"%>
<custom:errors />

This JSP includes it:
<%@taglib uri="http://java.sun.com/jsf/html" prefix="h"%><%@taglib
  uri="http://java.sun.com/jsf/core" prefix="f"%>
<html>
<body>
<f:view>
  <h:form>
    <h:inputText>
      <f:validateLength minimum="6" maximum="10" />
    </h:inputText>
    <h:inputText>
      <f:validateLength minimum="4" maximum="6" />
    </h:inputText>
    <h:commandButton />
  </h:form>
  <f:subview id="errs">
    <jsp:include page="customerrors2_inc.jsp" />
  </f:subview>
</f:view>
</body>
</html>

Yep, it all seems too complicated, but at least you could use this to create a JAR with a reusable custom control that can be dropped into any JSF application.
You could probably achieve similar results using a managed bean and a repeating control, but then you have to start worrying about delaying the list creation until after the validation phase (which will probably involve a phase listener).