text:
Q: Bootstrap collapse show and hide immediately I'm trying to make my bootstrap button that opens a div work as here :  http://getbootstrap.com/javascript/#collapse. The problem is that when I click on my buttons they show the div content but this content is hidden immediatelly.
My HTML code :

{{ 'current.user.data'|trans }}

<button type="button" data-toggle="collapse" class="pull-right" data-target="#main-data" aria-expanded="false" aria-controls="collapseExample"></button>

{{ 'person.firstName'|trans }} : {{ user.firstName }}

{{ 'person.lastName'|trans }} : {{ user.lastName }}

{{ 'person.email'|trans }} : {{ user.email }}

{{ 'person.birthDate'|trans }}: {{ user.bornOn ? user.bornOn|date('d-m-Y') }}

{{ 'person.familySituation'|trans }}: {{ user.familySituation }}

{{ 'person.profession'|trans }} : {{ user.profession }}

{{ 'person.createdAt'|trans }} {{ user.createdAt ? user.createdAt|date('d-m-Y') }}

{{ 'person.addresses'|trans }}

<button type="button" data-toggle="collapse" class="pull-right" data-target="#addresses">+</button>

            {% for address in user.addresses %}

{{ 'address'|trans }} N°{{ loop.index }}

{{ 'person.addresses.street1'|trans }} : {{ address.street1 }}

{{ 'person.addresses.street2'|trans }} : {{ address.street2 }}

{{ 'person.addresses.number'|trans }} : {{ address.number }}

{{ 'person.addresses.box'|trans }} : {{ address.box }}

{{ 'person.addresses.locality'|trans }} : {{ address.locality }}

{{ 'person.addresses.type'|trans }} : {{ address.addressType }}

            {% endfor %}

{{ 'person.medias'|trans }}

<button type="button" data-toggle="collapse" class="pull-right" data-target="#medias"></button>

            {% for media in user.medias %}

{{ '__media__label__'|trans }} N°{{ loop.index }}

{{ 'type'|trans }} : {{ media.typeMedia }}

{{ 'detail'|trans }} : {{ media.detail }}

            {% endfor %}

Then at the end before  tag I have this :

First it wan not working (and I dont know how to add the collapse functionality) and then I've found a JS filehere : https://getbootstrap.com/2.0.4/javascript.html#collapse and nos I have the problematic effect.
So how to make it work ? Where can I find the right collapse plugin ?
PS: I'm working on google chrome.

A: the best approach to execute your functionality would be via Angularjs or jquery/javascript. Not too sure about the plugin, though please try adding collapse.in class to the div you wish to show


text:
Q: Sending POST requests to Google Action/API.AI or sending responses which take more than 5s My fulfillment needs to do a lot of processing after receiving a certain request from Google Action/API.AI and the default response timeout is 5s.
https://developers.google.com/actions/components/fulfillment#nodejs
Is there any way I could send a delayed response or send a POST request after the results are ready?

A: The short answer is no - you must respond within 5 seconds, and there is no way to send a notification back through the Assistant at this time.
The slightly longer answer is that we know notifications are coming - but we don't know if there will be an API for them. There have been rumors about other ways that may be coming that allow us to work around the 5 second limit.
The even longer answer is that, if you are using Action Transactions (ie - allowing the user to purchase or reserve something) you can send updates after the fact. However, Transactions are still in developer preview and don't work on all surfaces (they don't work on Google Home at all, for example).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Define a function that extract a float and do operation I have a column with the following type of values:

I have to define a function that convert column Diameter in float and manage that kind of exception. In particular:

*

*when is 42x54 then make the operation: sqrt(42^2+54^2)

*when is Steel then return a NaN value

A: You can use str.extract with a regex to get the numbers, then square them with pow, sum the columns, and get the square root with numpy.sqrt:
import numpy as np

df['Diameter2'] = np.sqrt(df['Diameter']
                          .str.extract('(\d+)(?:\s*x\s*(\d+))?')
                          .astype(float).pow(2)
                          .sum(axis=1, min_count=1)
                          )

output:
  Diameter  Diameter2
0       44  44.000000
1  42 x 54  68.410526
2    Steel        NaN

regex demo
(\d+)              # capture a number
(?:\s*x\s*(\d+))?  # capture a number (optionally) if preceded by x with optional spaces


text:
Q: how to delete all data from SQLite table in android java I want to delete all data from SQLite table when I click the button then It create pdf file and then delete the data from the table I have created pdf file but not able to delete to the complete record it show error
//Dbhandler code
  public void deleteAll()
{
    SQLiteDatabase db = this.getWritableDatabase();
    db.execSQL("delete from "+ TABLE_Users);
    db.close();
}
//main activity code
 document.close();

if (myPath.exists())
    myPath.delete();

openPdf(path);
// here I want to call the delete all user
dbHandler.deleteAll();

 logs
 2021-04-08 08:22:00.213 13776-13803/com.j.usamaelectronics E/EGL_adreno:
 CreateContext rcMajorVersion:3, minorVersion:0
 2021-04-08 08:22:00.288 13776-13803/com.j.usamaelectronics E/EGL_adreno: tid
 13803: eglSurfaceAttrib(1582): error 0x3009 (EGL_BAD_MATCH)
   2021-04-08 08:22:09.227 13776-13803/com.j.usamaelectronics E/EGL_adreno:
  tid 13803: eglSurfaceAttrib(1582): error 0x3009 (EGL_BAD_MATCH)
  2021-04-08 08:45:31.035 13776-13776/com.j.usamaelectronics
  E/AndroidRuntime: FATAL EXCEPTION: main
 Process: com.j.usamaelectronics, PID: 13776
 java.lang.NullPointerException: Attempt to invoke virtual method 'void

com.j.usamaelectronics.DbHandler.deleteAll()' on a null object reference
at
com.j.usamaelectronics.ShowallsaleitemActivity.createPdf(ShowallsaleitemActivity.java:197)
at
com.j.usamaelectronics.ShowallsaleitemActivity.takeScreenShot(ShowallsaleitemActivity.java:163)
at com.j.usamaelectronics.ShowallsaleitemActivity.access$000(ShowallsaleitemActivity.java:46)
at com.j.usamaelectronics.ShowallsaleitemActivity$1.onClick(ShowallsaleitemActivity.java:107)
at android.view.View.performClick(View.java:5637)


text:
Q: KFold Cross Validation does not fix overfitting I am separating the features in X and y then I preprocess my train test data after splitting it with k fold cross validation. After that i fit the train data to my Random Forest Regressor model and calculate the confidence score. Why do i preprocess after splitting? because people tell me that it's more correct to do it that way and i'm keeping that principle since that for the sake of my model performance.
This is my first time using KFold Cross Validation because my model score overifts and i thought i could fix it with cross validation. I'm still confused of how to use this, i have read the documentation and some articles but i do not really catch how do i really imply it to my model but i tried anyway and my model still overfits. Using train test split or cross validation resulting my model score is still 0.999, I do not know what is my mistake since i'm very new using this method but i think maybe i did it wrong so it does not fix the overfitting. Please tell me what's wrong with my code and how to fix this
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
from sklearn.impute import SimpleImputer
from sklearn.model_selection import train_test_split
from sklearn.model_selection import KFold
from sklearn.preprocessing import LabelEncoder
from sklearn.ensemble import RandomForestRegressor
import scipy.stats as ss
avo_sales = pd.read_csv('avocados.csv')

avo_sales.rename(columns = {'4046':'small PLU sold',
                            '4225':'large PLU sold',
                            '4770':'xlarge PLU sold'},
                 inplace= True)

avo_sales.columns = avo_sales.columns.str.replace(' ','')
x = np.array(avo_sales.drop(['TotalBags','Unnamed:0','year','region','Date'],1))
y = np.array(avo_sales.TotalBags)

# X_train, X_test, y_train, y_test = train_test_split(x, y, test_size=0.2)

kf = KFold(n_splits=10)

for train_index, test_index in kf.split(x):
    X_train, X_test, y_train, y_test = x[train_index], x[test_index], y[train_index], y[test_index]

impC = SimpleImputer(strategy='most_frequent')
X_train[:,8] = impC.fit_transform(X_train[:,8].reshape(-1,1)).ravel()
X_test[:,8] = impC.transform(X_test[:,8].reshape(-1,1)).ravel()

imp = SimpleImputer(strategy='median')
X_train[:,1:8] = imp.fit_transform(X_train[:,1:8])
X_test[:,1:8] = imp.transform(X_test[:,1:8])

le = LabelEncoder()
X_train[:,8] = le.fit_transform(X_train[:,8])
X_test[:,8] = le.transform(X_test[:,8])

rfr = RandomForestRegressor()
rfr.fit(X_train, y_train)
confidence = rfr.score(X_test, y_test)
print(confidence)

A: The reason you're overfitting is because a non-regularized tree-based model will adjust to the data until all training samples are correctly classified. See for example this image:

As you can see, this does not generalize well. If you don't specify arguments that regularize the trees, the model will fit the test data poorly because it will basically just learn the noise in the training data. There are many ways to regularize trees in sklearn, you can find them here. For instance:

*

*max_features

*min_samples_leaf

*max_depth

With proper regularization, you can get a model that generalizes well to the test data. Look at a regularized model for instance:

To regularize your model, instantiate the RandomForestRegressor() module like this:
rfr = RandomForestRegressor(max_features=0.5, min_samples_leaf=4, max_depth=6)

These argument values are arbitrary, it's up to you to find the ones that fit your data best. You can use domain-specific knowledge to choose these values, or a hyperparameter tuning search like GridSearchCV or RandomizedSearchCV.
Other than that, imputing the mean and median might bring a lot of noise in your data. I would advise against it unless you had no other choice.

A: While @NicolasGervais answer gets to the bottom of why your specific model is overfitting, I think there is a conceptual misunderstanding with regards to cross-validation in the original question; you seem to think that:

Cross-validation is a method that improves the performance of a machine learning model.

But this is not the case.
Cross validation is a method that is used to estimate the performance of a given model on unseen data. By itself, it cannot improve the accuracy.
In other words, the respective scores can tell you if your model is overfitting the training data, but simply applying cross-validation does not make your model better.
Example:
Let's look at a dataset with 10 points, and fit a line through it:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression

X = np.random.randint(0,10,10)
Y = np.random.randint(0,10,10)

fig = plt.figure(figsize=(1,10))

def line(x, slope, intercept):
    return slope * x + intercept

for i in range(5):

    # note that this is not technically 5-fold cross-validation
    # because I allow the same datapoint to go into the test set
    # several times. For illustrative purposes it is fine imho.
    test_indices = np.random.choice(np.arange(10),2)
    train_indices = list(set(range(10))-set(test_indices))

    # get train and test sets
    X_train, Y_train = X[train_indices], Y[train_indices]
    X_test, Y_test = X[test_indices], Y[test_indices]
    # training set has one feature and multiple entries
    # so, reshape(-1,1)
    X_train, Y_train, X_test, Y_test = X_train.reshape(-1,1), Y_train.reshape(-1,1), X_test.reshape(-1,1), Y_test.reshape(-1,1)

    # fit and evaluate linear regression
    reg = LinearRegression().fit(X_train, Y_train)
    score_train = reg.score(X_train, Y_train)
    score_test = reg.score(X_test, Y_test)

    # extract coefficients from model:
    slope, intercept = reg.coef_[0], reg.intercept_[0]

    print(score_test)
    # show train and test sets
    plt.subplot(5,1,i+1)
    plt.scatter(X_train, Y_train, c='k')
    plt.scatter(X_test, Y_test, c='r')

    # draw regression line
    plt.plot(np.arange(10), line(np.arange(10), slope, intercept))
    plt.ylim(0,10)
    plt.xlim(0,10)

    plt.title('train: {:.2f} test: {:.2f}'.format(score_train, score_test))

You can see that the scores on training and test set are vastly different. You can also see that the estimated parameters vary a lot with the change of train and test set.
That does not make your linear model any better at all.
But now you know exactly how bad it is :)


text:
Q: Check my own servers for vulnerabilities We are a small early stage startup with not so much money to spend.
We have less than 3 servers that we want to monitor for security issues.
Our website is essentially on one server having:

*

*Ubuntu

*A Single-Page-App (full javascript)

*An API (Play/Scala/Netty) with MongoDB and ElasticSearch behind and an Apache reverse proxy

As you can understand, I'm more interested by server monitoring rather than application monitoring (not really looking for SQL injections, XSS or other things like that, I guess no tool is able to test that automatically on a JS app + API stack)
Is there any offering available, or open source product to monitor such things and alert us on security issues?
We are looking for a free or cheap tool, easy to use. Preferable a cheap SaaS offering, or a tool that can be run on a developer's computer (and not something that targets a 10000 computer network and should be run as image on vShpere or KVM, like some offers i've seen)
I have seen products like Nessus, Qualys, BeyondSecurity with SaaS offerings but it's extremely difficult to understand if these offers are affordable as it seems we always have to contact a sale to obtain any price, or the minimum number of ips to scan is > 250, or the price is > 3000$
Our cloud provider has made our server vulnerable temporarily (a shame: the firewall stopped working, opening very sensitive and easy to exploit ports to the outside world). At least we would like to be alerted for such things, and possibly a little more than a simple port scan.
Have you come up with any solution for this kind of task? Are there open-source tools reliable, easy to use for a regular developer and up to date?

A: Product or service recommendations are off-topic for this site.
Having said that, I would like to speak to your paragraph:
Our cloud provider has made our server vulnerable temporarily (a shame: the firewall stopped working, opening very sensitive and easy to exploit ports to the outside world). At least we would like to be alerted for such things, and possibly a little more than a simple port scan.
You should be layering your security. Your host-based firewall, iptables, should be blocking these "sensitive" and "easy to exploit" ports as a backup to your hosting provider's firewall. There's no "hard" costs involved and it's pretty simple to configured.
I also question that you're running "easy to exploit" services on an OS instance that is running Internet-exposed services. Even if you firewall off those exploitable services a vulnerability that allows for remote code execution on the machine might still be used to attack those services. (Given the recent Shellshock vulnerabilities I don't think this is an unreasonable concern.) If they're not able to be hardened then I'd look at architectural changes that isolated those services to machines with a smaller attack surface exposed to the Internet.


text:
Q: Inherit dependencies among projects Due to an architecture requirement, I would have to have all the 3rd party dependencies centralized in a single project. Then, the remaining projects in the solution would have this project referenced as a dependency to inheriting all of these dependencies in order to avoid having them duplicated along the solution.
I'm wondering if that's possible even if I have to make some tricky adjustments to make it work.
Any suggestion will be much appreciated.
Thanks in advance!

A: If you reference a project, you are not necessarily referencing it's dependencies.
So, say I have Project A that references 3rdPartyLib.dll.  when I reference ProjectA.dll, I'm not referencing 3rdPartyLib.dll.
One way to do it would be to write all of the logic that uses 3rdPartylib.dll in Project A, and essentially use it as an abstraction layer.  Then reference projectA.dll and call that logic, and the calling assembly would have no knowledge of 3rdPartyLib.dll


text:
Q: Wizard like layout in android I want to create a Wizard like layout which should look like described:
 * at the top should be some kind of title of the current dialog
 * at the bottom should be a navigation bar containg buttons for next/previous and various operations. THis bar should always(!) be at the very bottom of the screen.
 * at the center should be a list (should use all the space left, except the title bar and the navigation bar described above)
My first attempt is posted below. I used framelayout however I was told this is a bad idea. The problem I ran into is that last row of my list is below the bar with the buttons at the bottom of the screen. Do you have any suggestions on how I could solve my Problem?
Thanks
Here's my not working draft:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">

<LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="vertical" >

    <LinearLayout android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:orientation="horizontal" style="@android:style/ButtonBar">

        <ImageView android:src="@drawable/person"
            android:layout_width="wrap_content" android:layout_height="wrap_content" />

        <TextView android:text="@string/personstring"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:textStyle="bold" android:textAppearance="?android:attr/textAppearanceLarge" />

    </LinearLayout>

    <ListView android:visibility="visible" android:id="@android:id/list"
        android:layout_width="fill_parent" android:layout_height="fill_parent" />

</LinearLayout>
<LinearLayout android:id="@+id/footer"
        android:layout_width="fill_parent" android:layout_height="wrap_content"
        android:orientation="horizontal" android:layout_gravity="bottom|center"
        android:layout_alignParentBottom="true" style="@android:style/ButtonBar">

        <ImageButton android:id="@+id/loacreation.previousButton"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_weight="1" android:src="@drawable/buttonarrowleft" />

        <ImageButton android:id="@+id/loacreation.nextButton"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_weight="1" android:src="@drawable/buttonarrowright" />
    </LinearLayout>

</FrameLayout>

A: Use a RelativeLayout as your outermost container, and the LinearLayout that contains your buttons can have android:layout_alignParentBottom="true".


text:
Q: Android permissions categories and DELETE_PACKAGES and INSTALL_PACKAGES permissions I have an application that requires the DELETE_PACKAGES and INSTALL_PACKAGES permissions. The app is NOT being distributed through the market and requires "unknown sources" to be enabled. When I install this application the install page presents the user with a list of permission categories that include the categories:

*

*Your location

*Network communication

*Storage

*Services that cost you money

*Phone Calls

Are the permissions DELETE_PACKAGES and INSTALL_PACKAGES included in one of these categories? If so, which? If not, is the user not warned about this permission request?
For some background see List of android application categories and permissions

A:
I have an application that requires the DELETE_PACKAGES and INSTALL_PACKAGES permissions.

SDK applications cannot hold these permissions, unless they are part of the firmware.

Are the permissions DELETE_PACKAGES and INSTALL_PACKAGES included in one of these categories?

Probably not, but the user isn't installing your application, as it will be part of the firmware, so the point is presumably moot.


text:
Q: Google Map for Android doesn't show in production version of App - API key is unrestricted Maps worked properly for debug version and also for first four release versions (Alpha testing).
Now debug version works okay, but maps don't show in new release version. I also added SH1 from my Google Play Console of course, but still nothing. Now I generated new API key and also this key is unrestricted, so it should be always work, but still maps is "white" with Google logo in left down corner

A: It was my stupid silly mistake. I had one google_maps_api.xml with API key which I added manually at the beginning with my first map fragment. Later I added another map fragment automatically via Android studio. This added two google_maps_api.xml more. So finally I had google_maps_api.xml in

*

*src/main/res/value

*src/release/res/value

*src/debug/res/value
In the src/release/res/value/google_maps_api.xml I had "YOUR_KEY_HERE" instead of API key.
Bottom question:
I deleted both release and debug files and I have only one in main. If I want to have only one API key for debug and release, is there any other reason to have two google_maps_api.xml files in release and debug folders instead of only one file in main?


text:
Q: NHibernate and repositories design pattern I've been working with NHibernate for quite a while and have come to realize that my architecture might be a bit...dated. This is for an NHibernate library that is living behind several apps that are related to each other.
First off, I have a DomainEntity base class with an ID and an EntityID (which is a guid that I use when I expose an item to the web or through an API, instead of the internal integer id - I think I had a reason for it at one point, but I'm not sure it's really valid now). I have a Repository base class where T inherits from DomainEntity that provides a set of generalized search methods. The inheritors of DomainEntity may also implement several interfaces that track things like created date, created by, etc., that are largely a log for the most recent changes to the object. I'm not fond of using a repository pattern for this, but it wraps the logic of setting those values when an object is saved (provided that object is saved through the repository and not saved as part of saving something else).
I would like to rid myself of the repositories. They don't make me happy and really seem like clutter these days, especially now that I'm not querying with hql and now that I can use extension methods on the Session object. But how do I hook up this sort of functionality cleanly? Let's assume for the purposes of discussion that I have something like structuremap set up and capable of returning an object that exposes context information (current user and the like), what would be a good flexible way of providing this functionality outside of the repository structure? Bonus points if this can be hooked up along with a convention-based mapping setup (I'm looking into replacing the XML files as well).

A: If you dislike the fact that repositories can become bloated over time then you may want to use something like Query Objects.
The basic idea is that you break down a single query into an individual object that you can then apply it to the database.
Some example implementation links here.


text:
Q: How to append text string information from CAD annotation to polygon feature class attribute by location? I have a CAD file with polygons. They are signed with an annotation.
Is it possible to assign text values from the annotations to polygon feature class attribute.
As I understand only the location connection between the text and the polygon.


text:
Q: How to read sharePoint List item value (current Item) using javascript I have to read Title and Location from a picture library and display using CEWP.
Can someone suggest how to read SharePoint list item values using Javascript.

A: In SharePoint 2010 there are three different types of Client Object Model extension you can use. They are Managed Client Object Model, ECMAScript and silverlight extension.
This link more close to your requirement How to: Retrieve Lists Using JavaScript
and  How do you get the current list item in JavaScript?
SP.ListOperation.Selection Methods
var value = SP.ListOperation.Selection.getSelectedItems();

Check following links for more information:
SharePoint 2010: Use ECMAScript to manipulate (Add/Delete/Update/Get) List Items
Accessing List Data using the JavaScript Client OM
Using the SP2010 Client Object Model to update a list item
How to – SharePoint 2010 – JS client object model and UI advancements

A: You can use jQuery to access the list items via SharePoint Web Services. Refer for example here - SharePoint Web Services with jQuery

A: You can use the JavaScript Client Object Model. Assuming the window's _spPageContextInfo object is set with the webServerRelativeUrl, pageListId, and pageItemId properties initialized:
var context = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
var list = context.get_web().get_lists().getById(_spPageContextInfo.pageListId);
var item = list.getItemById(_spPageContextInfo.pageItemId);

Then you can load the fields you need:
context.load(item, "Title", "Location");
context.executeQueryAsync(Function.createDelegate(this, this.mySuccessFunction), Function.createDelegate(this, this.myErrorFunction));

item will now be populated with the fields you requested, and you can retrieve them like so:
var itemTitle = item.get_item("Title");
var itemLocation = item.get_item("Location");

Note that you should use the display, not internal, names of the fields you want to load.

A: if _spPageContextInfo.pageItemId is undefined.
Use this function
function getUrlVars() {
var vars = [],
    hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for (var i = 0; i < hashes.length; i++) {
    hash = hashes[i].split('=');
    vars.push(hash[0]);
    vars[hash[0]] = hash[1];
}
return vars;
}
//THEN DO THIS
var id = getUrlVars()["ID"];
//THEN DO YOUR MAGIC
var context = new SP.ClientContext(_spPageContextInfo.webServerRelativeUrl);
var list = context.get_web().get_lists().getById(_spPageContextInfo.pageListId);
var item = list.getItemById(id);

A: In SP2010 there is new client APIs that allow you to interact with SharePoint sites from JavaScript
SharePoint 2010 Client Object Model
JavaScript Class Library


text:
Q: How to upload video with Title & description to Firebase using flutter?  Future uploadtoServer () async{
print(videoFile);
StorageReference storageReference = FirebaseStorage.instance
    .ref()
    .child('video.mp4');
StorageUploadTask uploadTask = storageReference.putFile(videoFile, StorageMetadata(contentType: 'video.mp4'));
StorageTaskSnapshot taskSnapshot=await uploadTask.onComplete;
Uri downloadUrl = (await uploadTask.onComplete).uploadSessionUri;
final String Url = downloadUrl.toString();
print(Url);

setState(() {
  print(taskSnapshot);

});

return print(_uploadedFileURL);

}

A: You can only save your videoLink, description, and title to the Firestore database after uploading the video to the Firebase storage.
https://pub.dev/packages/cloud_firestore


text:
Q: sum array of objects inside an array of objects I have an array of objects and inside the array there is another array of objects, I would like to sum the values. So the sum is based on the same picker_id. Then sum current_capacity, process_time_in_minutes, and picked_qty inside products which is array of objects.
Here is my data:
var arr = [
  {
    current_capacity: 6000,
    picker_id: "icQrHPuE2fMZslceSG6liwuRar92",
    process_time_in_minutes: 10,
    products: [
      {
        product_id: 1,
        picked_qty: 2
      },
      {
        product_id: 2,
        picked_qty: 3
      }
    ]
  },

  {
    current_capacity: 2500,
    picker_id: "icQrHPuE2fMZslceSG6liwuRar92",
    process_time_in_minutes: 20,
    products: [
      {
        product_id: 1,
        picked_qty: 10
      }
    ]
  },

  {
    current_capacity: 36000,
    picker_id: "WIRzfIZALeftRk3DRGvh4nBdxQV2",
    process_time_in_minutes: 15,
    products: [
      {
        product_id: 1,
        picked_qty: 2
      },
      {
        product_id: 2,
        picked_qty: 3
      }
    ]
  }
];

Here is my code:
  var res = arr.reduce((acc, obj) => {
  var existObj = acc.find((item) => item.picker_id === obj.picker_id);
  if (existObj) {
    let total_picked = obj.products.reduce((acc2, curr) => acc2 + curr);

    // console.log("total_picked", total_picked);
    existObj.current_capacity =
      existObj.current_capacity + obj.current_capacity;
    existObj.process_time_in_minutes =
      existObj.process_time_in_minutes + obj.process_time_in_minutes;

    existObj.total = existObj.total ? existObj.total : 0 + total_picked;
    return acc;
  }
  acc.push(obj);
  return acc;
}, []);

const formatted = res.map((el) => {
  return {
    picker_id: el.picker_id,
    total_volume: el.current_capacity,
    total_time: el.process_time_in_minutes,
    total_products: el.total
  };
});

The result is as below:
[
 {
   picker_id: "icQrHPuE2fMZslceSG6liwuRar92"
   total_volume: 8500
   total_time: 30
   total_products: "0[object Object]"
 },
 {
   picker_id: "WIRzfIZALeftRk3DRGvh4nBdxQV2"
   total_volume: 36000
   total_time: 15
   total_products: undefined
  }
]

Expected like below:
[
 {
   picker_id: "icQrHPuE2fMZslceSG6liwuRar92"
   total_volume: 8500
   total_time: 30
   total_products: 15
 },
 {
   picker_id: "WIRzfIZALeftRk3DRGvh4nBdxQV2"
   total_volume: 36000
   total_time: 15
   total_products: 5
  }
]

A: Issue with your implementation was if the existObj doesn't exit in your acc, you were directly pushing the obj instead you need to process the total first from the inner array of products.
I have updated your code to look cleaner and maintainable.
Approach:

*

*build a dict for each picker_id which hold the computed data

*convert dict to list
var result = arr.reduce((acc, obj) => {
  if (!acc[obj.picker_id]) {
    acc[obj.picker_id] = {
      total_volume: 0,
      total_time: 0,
      total_products: 0
    };
  }

  const selectedPicker = acc[obj.picker_id];
  const total_picked = obj.products.reduce((acc2, item) => acc2 + item.picked_qty, 0);

  selectedPicker.total_volume = selectedPicker.total_volume + obj.current_capacity;
  selectedPicker.total_time =
    selectedPicker.total_time + obj.process_time_in_minutes;
  selectedPicker.total_products = selectedPicker.total_products + total_picked;

  return acc;
}, {});

const formatted = Object.keys(result).reduce((acc, picker_id) => {
    acc.push({
    picker_id,
    ...result[picker_id]
  })
    return acc;
}, [])

console.log("formmated", formatted);

A: You can also achieve your output by this

    function getProductQty(arr){
      let total = 0;
      arr.forEach(prd => {
        total += prd.picked_qty
      })
      return total;
    }
    const result = arr.reduce((acc,product) => {
       if(!acc.hasOwnProperty(product.picker_id)){
          acc[product.picker_id] = {
            picker_id: product.picker_id,
            total_volume: product.current_capacity,
            total_time: product.process_time_in_minutes
       }

      acc[product.picker_id].total_products = getProductQty(product.products);
      }else{
         acc[product.picker_id].total_volume = acc[product.picker_id].total_volume + product.current_capacity
         acc[product.picker_id].total_time = acc[product.picker_id].total_time + product.process_time_in_minutes
         acc[product.picker_id].total_products = acc[product.picker_id].total_products + getProductQty(product.products);
      }

         return acc
       },{})

console.log(Object.values(result),'result');

A: Using a little parameter destructuring, I think you can do a little further clean-up after you fix the problems others have described.  My version might look like this:

const extract = (xs) => Object .values (xs .reduce (
  (acc, {current_capacity, picker_id, process_time_in_minutes, products}) => {
    const curr = acc [picker_id] || (acc [picker_id] = {
      picker_id, total_volume: 0, total_time: 0, total_products: 0
    })
    curr .total_volume += current_capacity
    curr .total_time += process_time_in_minutes
    curr .total_products += products .reduce ((t, p) => t + p .picked_qty, 0)
    return acc
  },
  {}
))

const arr = [{current_capacity: 6e3, picker_id: "icQrHPuE2fMZslceSG6liwuRar92", process_time_in_minutes: 10, products: [{product_id: 1, picked_qty: 2}, {product_id: 2, picked_qty: 3}]}, {current_capacity: 2500, picker_id: "icQrHPuE2fMZslceSG6liwuRar92", process_time_in_minutes: 20, products: [{product_id: 1, picked_qty: 10}]}, {current_capacity: 36e3, picker_id: "WIRzfIZALeftRk3DRGvh4nBdxQV2", process_time_in_minutes: 15, products: [{product_id: 1, picked_qty: 2}, {product_id: 2, picked_qty: 3}]}]

console .log (extract (arr))
.as-console-wrapper {max-height: 100% !important; top: 0}


text:
Q: Symfony - Accessing Service from Custom Class I am trying to log information with Monolog library from a Custom Class that I have created that is called Common.
I have included logger as an argument in service.yml for that class
parameters:
services:
   appbundle.helper.common:
   class: AppBundle\Helpers\Common
   arguments: ['@doctrine','@logger']

I have also initialized the Logger Interface for that class.
    private $dataEntityManager;
    private $suppEntityManager;
    private $curation;
    private $innerDoctrine;
    private $logger;

    /**
     * Common constructor.
     * @param ManagerRegistry $doctrine
     */
    public function __construct(ManagerRegistry $doctrine, LoggerInterface $logger)
    {
        $this->dataEntityManager = $doctrine->getManager();
        $this->suppEntityManager = $doctrine->getManager('gtsupp');
        $this->curation = new Curation($doctrine);
        $this->innerDoctrine = $doctrine;
        $this->logger = $logger;
    }
    public function detail($a, $b, $c, $d, $e, $f = "", $g = true, $h = true)
    {

       $this->logger->error('Type not supplied in Common detail ' . __LINE__ . " for descriptor: " . $b);

     }

The problem is that each time I want to use class::Common I have to provide the logger in Class's constructor.
    class DefaultController extends Controller
    {
        /**
         * @Route("/", name="homepage")
         */
        public function indexAction(Request $request)
        {
            $common = new Common($this->getDoctrine(), $this->get('logger'));
            $common->detail('a', 'b', 'c', 'd', 'e');

            return $this->render('default/index.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir') . '/..') . DIRECTORY_SEPARATOR,
            ]);
        }
    }

P.S.
Same problem occurs with doctrine. I have to pass it every time I call Common class as you can see above.

A: Change this:
$common = new Common($this->getDoctrine(), $this->get('logger'));

to this:
$common = this->get('appbundle.helper.common');

In your way your are not using dependency injection, in the good way you don't need to pass all parameters to instantiate your service
https://symfony.com/doc/current/components/dependency_injection.html


text:
Q: Edit and reopen - shows reopen popup but doesn't let me edit I've just seen a question in the new Reopen queue that needed editting - the user had added code, but it was missing linebreaks.
I clicked on Edit and Reopen. I got the 'Nominate this question for reopening' popup; clicked on OK; and my vote was then counted without me getting the Edit box.


text:
Q: what does dim=-1 or -2 mean in torch.sum()? let me take a 2D matrix as example:
mat = torch.arange(9).view(3, -1)

tensor([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])

torch.sum(mat, dim=-2)

tensor([ 9, 12, 15])

I find the result of torch.sum(mat, dim=-2) is equal to torch.sum(mat, dim=0) and dim=-1 equal to dim=1. My question is how to understand the negative dimension here. What if the input matrix has 3 or more dimensions?

A: A tensor has multiple dimensions, ordered as in the following figure.
There is a forward and backward indexing. Forward indexing uses positive integers, backward indexing uses negative integers.
Example:
-1 will be the last one, in our case it will be dim=2
-2 will be dim=1
-3 will be dim=0

A: The minus essentially means you go backwards through the dimensions. Let A be a n-dimensional matrix. Then dim=n-1=-1, dim=n-2=-2, ..., dim=1=-(n-1), dim=0=-n. See the numpy doc for more information, as pytorch is heavily based on numpy.


text:
Q: Searching for the files which have search terms in python Trying to find search word in a bunch of text document in a folder using that approach:
dirname = '/Users/user/Documents/dat/'
search_terms = ['kek']

for f in os.listdir(dirname):

    text = open(os.path.join(dirname,f)).readlines()

    if any(term in text for term in search_terms):

        print (f)

For some reason, don't know why, it gives me the name of first file in directory no matter consists it this search term or not. What should be done differently to proper do this task?
Thanks!

A: If I understood you correctly you need.
dirname = '/Users/user/Documents/dat/'
search_terms = ['kek']

for f in os.listdir(dirname):
    with open(os.path.join(dirname,f), "r") as infile:
        text =  infile.read()

    if any(term in text for term in search_terms):
        print (f)

A: Because when you find the right term in the file, you aren't printing the term, you're printing the file name, f.
Try:
    for line in text:
        if any(term in line for term in search_terms):
            print(line)

Also, don't forget to either close your file when you're done with it, or use with


text:
Q: Best approach for RESTful Web Api with multiple Update/Put actions? When making RESTful services, I find myself confused on how to handle different types of updates in a resource. With MVC we could have different actions with different models working smoothly, but as we move to Web API and try to implement a REST approach I get myself tied to two options: PUT and POST.
And that's not enough.
If I have a very big and complex resource, like a User's profile in a social website with lots of properties and possible bounds with other resources, just trying to make any possible change go through the same "PUT" isn't going to work, it would create a massive Spaghetti Updater Monster.
I've found different solutions to this problem though:

*

*Use overloads (with different models as param). Still not good as this type of bifurcation can make it hard to maintain and/or troubleshooting.

*Use PATCH verb. Though this would still require me to overload it many times for each update possibility and WEB API doesn't have native support for it.

*Create more Controllers: Personally I've used this approach in an MVC/Command way: I can consider the "bound" a resource and make a Controller like: FriendsController, FavouritesController, LikesController, MainPhotoController, ans so... which are "user features/properties/possible bounds with other resources". It works for me and makes things simpler and smoother.

*Looks like there's another similar way but instead of creating Controllers for everything, creating "paths", so I could have "UserController/favourites/", "UserController/Likes", etc.
I know that in SW architecture there's never an absolute right way and it all depends on your requirements, but even so there are patterns and best practices so, which one of those looks like a best practice to you? Or does none of those look like a good approach?
Many Thanks.


text:
Q: H2 in memory is empty when I run my unitary tests but it´s populated when I run the application itself I am somewhat new to Spring Boot and for learning purposes, I wrote a simple REST API using an in-memory database (H2).
Everything works fine when I actually run the application: the database is loaded into memory and populated using an import.sql file I provided, my endpoints
do what they are supposed to do. Now I´m trying to write a controller test that is supposed to call a "find stuff by id" endpoint. Here lies the problem:
when I run this test, it doesn't find any entry in the database and fails, i.e., it seems my database has not been populated on startup. I don´t know what´s happening
because, as I said, when I actually run the application and test it using Postman, everything is on memory and works as intended.
What should I do in order to get my database properly populated in a testing scenario?
Just for reference, I´ve read this article (very useful btw) and there, although he uses an alternative approach to populate his database, he doesn't do anything special regarding his testing needs. Everything runs fine both using Postman and when testing. This is what I try to accomplish.
Any help would be truly appreciated. I´ve done a lot of research, tried a lot of things, but to no avail.
These are the files I assume are relevant:
** my application.properties under /scr/main/resources
server.port=8888
spring.h2.console.enabled=true
spring.h2.console.path=/h2
spring.datasource.url=jdbc:h2:file:~/test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=
spring.datasource.driver-class-name=org.h2.Driver
spring.jpa.hibernate.ddl-auto=create-drop

** my controller class and the find method I want to test.
@RestController
@RequestMapping(value="/email", produces=APPLICATION_JSON_VALUE)
public class EmailController {

    private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private EmailService emailService;

    @GetMapping(value="/{id}")
    public ResponseEntity<Email> consultar(@PathVariable Long id) {
        Email emailEncontrado = emailService.buscar(id);
        if (emailEncontrado == null) {
            LOGGER.info("No email has been found with this id... :(");
            return new ResponseEntity<Email>(HttpStatus.NOT_FOUND);
        }

        return new ResponseEntity<Email>(emailService.buscar(id), HttpStatus.OK);
    }
}

** my controller test class and the find method:
@RunWith(SpringRunner.class)
//@WebMvcTest(EmailController.class)
@SpringBootTest
@AutoConfigureMockMvc
public class EmailControllerTest {

    @Autowired
    private MockMvc mvc;

    @MockBean
    private EmailService service;

    @Test
    public void deveBuscarEmailPorIdComSucesso() throws Exception {
        mvc.perform(get("/email/1"))
        .andExpect(jsonPath("$.id").value(1))
        .andDo(print());
    }
}

** my Email model
@Entity
@Table(name="t_email")
public class Email {

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

    private String emailTo;

    @Column(length=12000)
    private String message;

    private String subject;

    ** constructors, getters and setters
}

** The Spring Boot initialization log when I actually run the test (note the line at 2017-07-05 09:11:48.354)
09:11:28.619 [main] DEBUG org.springframework.test.context.junit4.SpringJUnit4ClassRunner - SpringJUnit4ClassRunner constructor called with [class com.email.controller.EmailControllerTest]
09:11:28.660 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating CacheAwareContextLoaderDelegate from class [org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate]
09:11:28.786 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating BootstrapContext using constructor [public org.springframework.test.context.support.DefaultBootstrapContext(java.lang.Class,org.springframework.test.context.CacheAwareContextLoaderDelegate)]
09:11:29.089 [main] DEBUG org.springframework.test.context.BootstrapUtils - Instantiating TestContextBootstrapper for test class [com.email.controller.EmailControllerTest] from class [org.springframework.boot.test.context.SpringBootTestContextBootstrapper]
09:11:29.198 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [com.email.controller.EmailControllerTest], using SpringBootContextLoader
09:11:29.229 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.email.controller.EmailControllerTest]: class path resource [com/aws/email/controller/EmailControllerTest-context.xml] does not exist
09:11:29.229 [main] DEBUG org.springframework.test.context.support.AbstractContextLoader - Did not detect default resource location for test class [com.email.controller.EmailControllerTest]: class path resource [com/aws/email/controller/EmailControllerTestContext.groovy] does not exist
09:11:29.229 [main] INFO org.springframework.test.context.support.AbstractContextLoader - Could not detect default resource locations for test class [com.email.controller.EmailControllerTest]: no resource found for suffixes {-context.xml, Context.groovy}.
09:11:29.229 [main] INFO org.springframework.test.context.support.AnnotationConfigContextLoaderUtils - Could not detect default configuration classes for test class [com.email.controller.EmailControllerTest]: EmailControllerTest does not declare any static, non-private, non-final, nested classes annotated with @Configuration.
09:11:29.572 [main] DEBUG org.springframework.test.context.support.ActiveProfilesUtils - Could not find an 'annotation declaring class' for annotation type [org.springframework.test.context.ActiveProfiles] and class [com.email.controller.EmailControllerTest]
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
09:11:29.650 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
09:11:29.697 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/aws/email/controller/] to resources [URL [file:/C:/Users/john.doe/workspace/project/bin/com/aws/email/controller/]]
09:11:29.710 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller]
09:11:29.710 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller] for files matching pattern [C:/Users/john.doe/workspace/project/bin/com/aws/email/controller/*.class]
09:11:29.712 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/aws/email/controller/*.class] to resources [file [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller\EmailController.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\controller\EmailControllerTest.class]]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved classpath location [com/aws/email/] to resources [URL [file:/C:/Users/john.doe/workspace/project/bin/com/aws/email/]]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Looking for matching resources in directory tree [C:\Users\john.doe\workspace\project\bin\com\aws\email]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Searching directory [C:\Users\john.doe\workspace\project\bin\com\aws\email] for files matching pattern [C:/Users/john.doe/workspace/project/bin/com/aws/email/*.class]
09:11:29.870 [main] DEBUG org.springframework.core.io.support.PathMatchingResourcePatternResolver - Resolved location pattern [classpath*:com/aws/email/*.class] to resources [file [C:\Users\john.doe\workspace\project\bin\com\aws\email\Application.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\ApplicationTests.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\GlobalExceptionHandler.class], file [C:\Users\john.doe\workspace\project\bin\com\aws\email\TestBaseClass.class]]
09:11:30.009 [main] DEBUG org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider - Identified candidate component class: file [C:\Users\john.doe\workspace\project\bin\com\aws\email\Application.class]
09:11:30.025 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Found @SpringBootConfiguration com.email.Application for test class com.email.controller.EmailControllerTest
09:11:30.041 [main] DEBUG org.springframework.boot.test.context.SpringBootTestContextBootstrapper - @TestExecutionListeners is not present for class [com.email.controller.EmailControllerTest]: using defaults.
09:11:30.041 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener, org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
09:11:30.169 [main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Using TestExecutionListeners: [org.springframework.test.context.web.ServletTestExecutionListener@40996815, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@17805bd5, org.springframework.boot.test.autoconfigure.SpringBootDependencyInjectionTestExecutionListener@6c0d0900, org.springframework.test.context.support.DirtiesContextTestExecutionListener@4bca166b, org.springframework.test.context.transaction.TransactionalTestExecutionListener@4085f1ac, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@19bd744c, org.springframework.boot.test.autoconfigure.web.client.MockRestServiceServerResetTestExecutionListener@651e36c7, org.springframework.boot.test.mock.mockito.MockitoTestExecutionListener@229e76ae, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcPrintOnlyOnFailureTestExecutionListener@5181ab43, org.springframework.boot.test.autoconfigure.restdocs.RestDocsTestExecutionListener@1812e583, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverTestExecutionListener@9a07ce, org.springframework.boot.test.mock.mockito.ResetMocksTestExecutionListener@7665b1]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.184 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.215 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.231 [main] DEBUG org.springframework.test.context.support.AbstractDirtiesContextTestExecutionListener - Before test class: context [DefaultTestContext@75152f9 testClass = EmailControllerTest, testInstance = [null], testMethod = [null], testException = [null], mergedContextConfiguration = [WebMergedContextConfiguration@6c1e5d2f testClass = EmailControllerTest, locations = '{}', classes = '{class com.email.Application}', contextInitializerClasses = '[]', activeProfiles = '{}', propertySourceLocations = '{}', propertySourceProperties = '{org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true}', contextCustomizers = set[[ImportsContextCustomizer@3d77f01d key = [Package Import com.email.controller, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcSecurityAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebClientAutoConfiguration, org.springframework.boot.test.autoconfigure.web.servlet.MockMvcWebDriverAutoConfiguration]], org.springframework.boot.test.context.SpringBootTestContextCustomizer@66edadfa, org.springframework.boot.test.context.filter.ExcludeFilterContextCustomizer@795eac8b, org.springframework.boot.test.json.DuplicateJsonObjectContextCustomizerFactory$DuplicateJsonObjectContextCustomizer@72dbf050, org.springframework.boot.test.mock.mockito.MockitoContextCustomizer@169a567f, org.springframework.boot.test.autoconfigure.properties.PropertyMappingContextCustomizer@e7e8512, org.springframework.boot.test.autoconfigure.web.servlet.WebDriverContextCustomizerFactory$Customizer@67b3f915], resourceBasePath = 'src/main/webapp', contextLoader = 'org.springframework.boot.test.context.SpringBootContextLoader', parent = [null]]], class annotated with @DirtiesContext [false] with mode [null].
09:11:30.231 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved @ProfileValueSourceConfiguration [null] for test class [com.email.controller.EmailControllerTest]
09:11:30.231 [main] DEBUG org.springframework.test.annotation.ProfileValueUtils - Retrieved ProfileValueSource type [class org.springframework.test.annotation.SystemProfileValueSource] for class [com.email.controller.EmailControllerTest]
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemProperties] PropertySource with lowest search precedence
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [systemEnvironment] PropertySource with lowest search precedence
09:11:30.525 [main] DEBUG org.springframework.core.env.StandardEnvironment - Initialized StandardEnvironment with PropertySources [systemProperties,systemEnvironment]
09:11:30.525 [main] DEBUG org.springframework.core.env.MutablePropertySources - Adding [inline] PropertySource with highest search precedence
09:11:30.559 [main] DEBUG org.springframework.test.context.support.TestPropertySourceUtils - Adding inlined properties to environment: {spring.jmx.enabled=false, org.springframework.boot.test.context.SpringBootTestContextBootstrapper=true, server.port=-1}
09:11:30.559 [main] DEBUG org.springframework.core.env.StandardEnvironment - Adding [Inlined Test Properties] PropertySource with highest search precedence

  .   ____          _            __ _ _
 /\\ / ___'_ __ _ _(_)_ __  __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
 \\/  ___)| |_)| | | | | || (_| |  ) ) ) )
  '  |____| .__|_| |_|_| |_\__, | / / / /
 =========|_|==============|___/=/_/_/_/
 :: Spring Boot ::        (v1.5.4.RELEASE)

2017-07-05 09:11:31.932  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : Starting EmailControllerTest on INOTE79 with PID 11268 (started by john.doe in C:\Users\john.doe\workspace\project)
2017-07-05 09:11:31.932  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : No active profile set, falling back to default profiles: default
2017-07-05 09:11:33.355  INFO 11268 --- [           main] o.s.w.c.s.GenericWebApplicationContext   : Refreshing org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:39.040  INFO 11268 --- [           main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:39.104  INFO 11268 --- [           main] o.hibernate.jpa.internal.util.LogHelper  : HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2017-07-05 09:11:39.308  INFO 11268 --- [           main] org.hibernate.Version                    : HHH000412: Hibernate Core {5.0.12.Final}
2017-07-05 09:11:39.308  INFO 11268 --- [           main] org.hibernate.cfg.Environment            : HHH000206: hibernate.properties not found
2017-07-05 09:11:39.324  INFO 11268 --- [           main] org.hibernate.cfg.Environment            : HHH000021: Bytecode provider name : javassist
2017-07-05 09:11:39.443  INFO 11268 --- [           main] o.hibernate.annotations.common.Version   : HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2017-07-05 09:11:39.948  INFO 11268 --- [           main] org.hibernate.dialect.Dialect            : HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2017-07-05 09:11:40.073  INFO 11268 --- [           main] o.h.e.j.e.i.LobCreatorBuilderImpl        : HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
2017-07-05 09:11:41.088  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-05 09:11:41.104  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000476: Executing import script '/import.sql'
2017-07-05 09:11:41.119  INFO 11268 --- [           main] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete
2017-07-05 09:11:41.323  INFO 11268 --- [           main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:44.571  INFO 11268 --- [           main] o.s.b.t.m.w.SpringBootMockServletContext : Initializing Spring FrameworkServlet ''
2017-07-05 09:11:44.571  INFO 11268 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization started
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/email],methods=[POST],consumes=[application/json],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.email.response.EmailResponse> com.email.controller.EmailController.enviar(com.email.request.EmailRequest)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/email/{id}],methods=[GET],produces=[application/json]}" onto public org.springframework.http.ResponseEntity<com.email.model.Email> com.email.controller.EmailController.consultar(java.lang.Long)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2017-07-05 09:11:44.854  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2017-07-05 09:11:45.119  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:45.119  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:45.228  INFO 11268 --- [           main] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2017-07-05 09:11:46.370  INFO 11268 --- [           main] s.w.s.m.m.a.RequestMappingHandlerAdapter : Looking for @ControllerAdvice: org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:46.556  INFO 11268 --- [           main] .m.m.a.ExceptionHandlerExceptionResolver : Detected @ExceptionHandler methods in globalExceptionHandler
2017-07-05 09:11:46.823  INFO 11268 --- [           main] o.s.t.web.servlet.TestDispatcherServlet  : FrameworkServlet '': initialization completed in 2252 ms
2017-07-05 09:11:47.948  INFO 11268 --- [           main] c.a.e.controller.EmailControllerTest     : Started EmailControllerTest in 17.313 seconds (JVM running for 21.805)
2017-07-05 09:11:48.354  INFO 11268 --- [           main] c.aws.email.controller.EmailController   : No email has been found with this id... :(

MockHttpServletRequest:
      HTTP Method = GET
      Request URI = /email/1
       Parameters = {}
          Headers = {}

Handler:
             Type = com.email.controller.EmailController
           Method = public org.springframework.http.ResponseEntity<com.email.model.Email> com.email.controller.EmailController.consultar(java.lang.Long)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = null

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = {}
     Content type = null
             Body =
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] o.s.w.c.s.GenericWebApplicationContext   : Closing org.springframework.web.context.support.GenericWebApplicationContext@2f8ab088: startup date [Wed Jul 05 09:11:33 BRT 2017]; root of context hierarchy
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'
2017-07-05 09:11:48.417  INFO 11268 --- [       Thread-7] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000227: Running hbm2ddl schema export
2017-07-05 09:11:48.432  INFO 11268 --- [       Thread-7] org.hibernate.tool.hbm2ddl.SchemaExport  : HHH000230: Schema export complete

** The JUnit fail log:
java.lang.AssertionError: No value at JSON path "$.id", exception: json can not be null or empty
    at org.springframework.test.util.JsonPathExpectationsHelper.evaluateJsonPath(JsonPathExpectationsHelper.java:245)
    at org.springframework.test.util.JsonPathExpectationsHelper.assertValue(JsonPathExpectationsHelper.java:99)
    at org.springframework.test.web.servlet.result.JsonPathResultMatchers$2.match(JsonPathResultMatchers.java:100)
    at org.springframework.test.web.servlet.MockMvc$1.andExpect(MockMvc.java:171)
    at com.email.controller.EmailControllerTest.deveBuscarEmailPorIdComSucesso(EmailControllerTest.java:56)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Edit: my project structure:
project tree

A: You need to define the dummy data before running the Unit test,the link you gave does that in the DemoApplication.class and loads it using @ContextConfiguration on the test class. That part is missing in your code.In your unit test the import.sql will not run until you mention it.It can be done using @Sql annotation
@Sql({ "import.sql" })

Also for unit test you dont need to make database calls,it is generally done in integration testing. For junits you can mock your service call as shown below
when(emailService.buscar(anyInt()).thenReturn(new Email());

A: JUnit issue (which is basically assertion issue) which says there is no ID meaning two things:

*

*Resulting JSON does not contain ID

*Resulting JSON empty

your case is second, cause ID I can see from you Entity and also I see you have create-drop hibernate DDL, but note that it is not populating DB with dummy information and just creating that.
So, that will mean, that you need to populate DB with some dummy data.
For that, you can add a file named "import.sql" to your classpath (i.e. in src/main/resources if you're using a Maven/Gradle project layout).


text:
Q: What does "HAD" imply here? (I didn't realize you HAD + noun) When you say "I didn't realize you had the apple", does it mean the person who is spoken to still has "the apple"? Or because it's "HAD", does it imply the person doesn't have the apple anymore?

A: Like most statements using a past tense, there is no implication about the present.

My wife was interested in economics

says nothing about the present. She may still be interested in economics, or she may not. The statement deals with the past rather than the present.

I loved her when we married, but have hated her since we divorced

makes sense.

I loved her when we married and love her more after a life shared together

also makes sense.
The past may or may not differ from the present.

A: If you unexpectedly meet someone you know, at a party for example, "I didn't know you were here" is much more idiomatic than "are here". It's difficult to give a logical explanation, but it comes naturally to a native speaker.


text:
Q: Concatenating odd number of bytes and reading as an Int I'm interested in being able to read and write 24-bit wav files. The web audio api + recorderjs seems great for 16-bit wavs, but professional audio is recorded and manipulated at 24-bit usually. I'm wondering if there is a way in javascript to concatenate 3 binary bytes from an array buffer and read them as an int.
Solution:
var sample = 0;

for (var b = 0; b < bytesPerSample; b++) {

    sample <<= 8;
    sample |= data[b]; // data is a Uint8Array

}

A: Sure:
var a = [0xc,0xa,0xb];
a.reduce(function(p,c){return p<<8|c;},0).toString(16) // "c0a0b"


text:
Q: Elasticsearch Linux user I installed an Elasticsearch 7 on CentOS 7 using rpm file. After install, elaticsearch user and group is created, user which can't be used to manage elasticsearch (no login) but from what I saw will own es data directory. I don't want to manage elasticsearch with root user. Should I create a new user for that or to modify elasticsearch user? What will be the best approach?
Thank you!

A: I found that, after elasticsearch is started, another user is created (elastic), owner of the elasticsearch process. This user can by added to the sudoers file and can by used to start/stop elasticsearch. But, I think  the best partice is to use other user for that, added in sudoers, of cource.


text:
Q: Get Function Not Working I have this code using a .get() function to retrieve the input from a Tkinter Entry:
from Tkinter import *
def access():
    access_window = Toplevel(root)
    access_window.title("Access a Contact")
    Label(access_window, text="Enter a first name: ").grid(row=0, sticky=W+E)
    access_key = Entry(access_window, width=8)
    access_key.grid(row=1, sticky=W+E)
    Button(access_window, text="Submit", command=lambda: get_info(str(access_key.get("1.0", "end")))).grid(row=2, sticky=W+E)

But when I click the button, I get this error:
Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk/Tkinter.py", line 1470, in __call__
    return self.func(*args)
  File "/Users/stephenhjb/Documents/First tkinter", line 17, in <lambda>
    Button(access_window, text="Submit", command=lambda: get_info(str(access_key.get("1.0", "end")))).grid(row=2, sticky=W+E)
TypeError: get() takes exactly 1 argument (3 given)

Why is this happening?

A: The method .get() of the Entry object does not accept any parameter. It is used to get the value in the Entry object. (Gets the current contents of the entry field). Do not confuse this .get() with the built-in get() of Python.
Font: http://effbot.org/tkinterbook/entry.htm


text:
Q: Find Google Console Access? I have a working app with GOOGLE_APP_ID and GOOGLE_APP_SECRET but I cannot recall which account was used to manage these, and when I log in using my existing emails - I cannot find them (while they are still working)
How can I find out which email was used to manage the console that owns my existing keys?

A: Looks like you want to migrate that applicaton to another account.
Just open a ticket with google support and tell them the GOOGLE_APP_ID and ask how you can translate that application.
Maybe you can remember which account is by looking at the domain validation records on the DNS. But the safest bet is go to Google support.


text:
Q: WPF Rounded corners - is a consistent gradient around the corner possible? I've made a gradient that I quite like in expression blend, and I'm trying to work out if I can make the gradient curve around a corner, to give me a rounded border effect with the gradient.
The problem is that I can't use a normal border, because the gradient wont be consistent.
I came up with the following which should help demonstrate what I'm thinking:
rounded corner with gradient http://img232.imageshack.us/img232/9899/roundedcornerrg0.th.jpg
<Grid x:Name="grid" >
    <Border
        BorderThickness="0,0,40,40"
        CornerRadius="0,0,40,0"
        Padding="2" Height="60" VerticalAlignment="Bottom" Width="65" HorizontalAlignment="Right" >
        <Border.BorderBrush>
            <RadialGradientBrush>
                <RadialGradientBrush.RelativeTransform>
                    <TransformGroup>
                        <ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="2.058" ScaleY="2.177"/>
                        <SkewTransform AngleX="0" AngleY="0" CenterX="0.5" CenterY="0.5"/>
                        <RotateTransform Angle="-119.481" CenterX="0.5" CenterY="0.5"/>
                        <TranslateTransform X="0.209" Y="0.52"/>
                    </TransformGroup>
                </RadialGradientBrush.RelativeTransform>
                <GradientStop Color="#FF000000" Offset="0"/>
                <GradientStop Color="#000A0A0A" Offset="1"/>
                <GradientStop Color="#6B050505" Offset="0.829"/>
                <GradientStop Color="#BB020202" Offset="0.763"/>
            </RadialGradientBrush>
        </Border.BorderBrush>
    </Border>
    <Rectangle VerticalAlignment="Stretch" Height="100" Width="40" HorizontalAlignment="Right" Margin="0,0,0,60" StrokeThickness="0" Panel.ZIndex="0">
        <Rectangle.Fill>
            <LinearGradientBrush EndPoint="-0.025,0.5" StartPoint="1,0.5">
                <GradientStop Color="#FF000000" Offset="0"/>
                <GradientStop Color="#000A0A0A" Offset="1"/>
                <GradientStop Color="#6B050505" Offset="0.829"/>
                <GradientStop Color="#BB020202" Offset="0.763"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>
    <Rectangle VerticalAlignment="Bottom" Height="40" Width="100" HorizontalAlignment="Stretch" Margin="0,0,65,0">
        <Rectangle.Fill>
            <LinearGradientBrush EndPoint="0.5,0" StartPoint="0.5,1">
                <GradientStop Color="#FF000000" Offset="0"/>
                <GradientStop Color="#000A0A0A" Offset="1"/>
                <GradientStop Color="#6B050505" Offset="0.829"/>
                <GradientStop Color="#BB020202" Offset="0.763"/>
            </LinearGradientBrush>
        </Rectangle.Fill>
    </Rectangle>
</Grid>

Is there any way to get a gradient bending around a corner like I'm thinking? I saw a suggestion online to nest borders in each other, but this is no good for me either, as the gradient makes life difficult.

A: You might want to check out Charles Petzolds article on Graphical Paths with Gradient Colors in which he discusses a similar problem to yours.

A:     <Grid x:Name="grid" VerticalAlignment="Top" HorizontalAlignment="Left" Width="100" Height="100" Margin="200,200,0,0">
         <Rectangle VerticalAlignment="Stretch" Width="20" HorizontalAlignment="Right" Margin="0,20,0,20" StrokeThickness="0" Panel.ZIndex="0">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="1,0" StartPoint="0,0">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Bottom" Height="20" HorizontalAlignment="Stretch" Margin="20,0,20,0">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="1,1" StartPoint="1,0">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Stretch" Width="20" HorizontalAlignment="Left" Margin="0,20,0,20" StrokeThickness="0" Panel.ZIndex="0">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="0,0" StartPoint="1,0">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Top" Height="20" HorizontalAlignment="Stretch" Margin="20,0,20,0">
            <Rectangle.Fill>
                <LinearGradientBrush EndPoint="1,0" StartPoint="1,1">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </LinearGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Top" Height="20" Width="20" HorizontalAlignment="Left" Margin="0,0,0,0">
            <Rectangle.Fill>
                <RadialGradientBrush Center=".9,.9" GradientOrigin="1,1" RadiusX=".85" RadiusY=".85">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </RadialGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Bottom" Height="20" Width="20" HorizontalAlignment="Right" Margin="0,0,0,0">
            <Rectangle.Fill>
                <RadialGradientBrush Center=".1,.1" GradientOrigin="0,0" RadiusX=".85" RadiusY=".85">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </RadialGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Top" Height="20" Width="20" HorizontalAlignment="Right" Margin="0,0,0,0">
            <Rectangle.Fill>
                <RadialGradientBrush Center=".1,.9" GradientOrigin="0,1" RadiusX=".85" RadiusY=".85">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </RadialGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
        <Rectangle VerticalAlignment="Bottom" Height="20" Width="20" HorizontalAlignment="Left" Margin="0,0,0,0">
            <Rectangle.Fill>
                <RadialGradientBrush Center=".9,.1" GradientOrigin="1,0" RadiusX=".85" RadiusY=".85">
                    <GradientStop Color="#00FFFFFF" Offset="0"/>
                    <GradientStop Color="#FFFFFFFF" Offset="1"/>
                    <GradientStop Color="#22FFFFFF" Offset="0.5"/>
                    <GradientStop Color="#11FFFFFF" Offset="0.3"/>
                </RadialGradientBrush>
            </Rectangle.Fill>
        </Rectangle>
    </Grid>


text:
Q: Redirect from one controller action to another including a http header I am working with a .net framework 4.6.2, MVC project where I want to call a controller action, do some processing and once complete, redirect to another controller action, passing to it a http header with a get request.
To achieve this, to pass a http header, do I need to return back to the browser the initial controller action and get the browser to perform the subsequent redirect client side, including the http header in it? From my research I can find a way for one controller action call another controller action, via a GET, including a header with it.


text:
Q: Does React Re render All Ui elements when Data/State Change? i am working on a project in which i am using a socket.io for real time data streaming.I have front end in react.My app component structure looks like this
<App>
    <Circle />
    <Component./>
    <........./>
</App>

my app component is receiving data over socket.io and passing it to child  component .Like this
        <CircleC dataS={dataS}  dataC={dataC}/>

*

*dataS is 10000 length array

*dataC is also 10000 length array

and these array also changes after 100milisecond.mean i am receiving 2 arrays of 10000 records after every 100 millisecond in real time.
This is my Circle Component
return (
<div className="show-data" onWheel={onWheelHandler}>
{

    dataS.map((item,id)=>(

        <button className="wave-circle" style={{ backgroundColor: "grey",padding:pad }} key={id}>{id}</button>
        :    dataC[id]==1?
        <button className="wave-circle" style={{ backgroundColor: "green",padding:pad }} key={id}>{id}</button>
        :    dataC[id]==2?
        <button className="wave-circle" style={{ backgroundColor: "yellow",padding:pad }} key={id}>{id}</button>
        :    spike[id]==3?
        <button className="wave-circle" style={{ backgroundColor: "cyan",padding:pad }} key={id}>{id}</button>
        :       <button className="wave-circle" style={{ backgroundColor: "purple",padding:pad }} key={id}>{count}</button>

        ))

.
Problems i am facing.

*

*Every time data Changes/new data arrives.All the UI Elements(circle html) redraw again(i think so).
-What we can do to avoid re-drawing of UI .only data within these elements should be display
i ONLY WANT TO know how we can draw UI only one time and then when new data arrives only content or styling change .Cicrle or UI should not be redrawn.


text:
Q: A Variation on Neural Machine Translation I have been processing this thought in my head for a long time now. So in NMT, We pass in the text in the source language in the encoder seq2seq stage and the language in the target language in the decoder seq2seq stage and the system learns the conditional probabilities for each word occurring with its target language word. Ex: P(word x|previous n-words). We train this by teacher forcing.
But what if I pass in the input sentence again as input to the decoder stage instead of the target sentence. What would it learn in this case? I'm guessing this will learn to predict the most probable next word in the sentence given the previous text right? What are your thoughts
Thanks in advance

A: In that case, you would be learning a model that copies the input symbol to the output. It is trivial for the attention mechanism to learn the identity correspondence between the encoder and decoder states. Moreover, RNNs can easily implement a counter. It thus won't provide any realistic estimate of the probability, it will assign most of the probability mass to the corresponding word in the source sentence.


text:
Q: Limitations of Custom Fields in Active Directory I am currently looking into the possibility/feasibility of using Custom Fields in Active Directory for storing information per user within our domain network, but have a few questions regarding the custom fields themselves, namely:

*

*What are the limitations of these fields, if any?

*Is there a maximum field length?

*Is there a maximum number of custom fields available per user?

*Are there any known read/write performance issues (from C#) with using them for this purpose?

A: edit: Wrote this answer before I knew you were talking about Exchange, so it's more about AD in general.
Yes there are limits.  Your first consideration might be that the attribute you want to use is not indexed. This is as easy as clicking a checkbox to change. Indexing an attribute makes queries involving that attribute faster, at the cost of database and replication size.
Secondly, your custom attribute may not be replicated to Global Catalogs.  This may be an issue if you have many domains and you might need to access this information from another domain.  This is also easy to fix, but again, be mindful that you're adding replication load.
There are a ton of attributes already in the AD schema that are not being used. Perhaps you can repurpose some of them.  For instance, the Likewise/Powerbroker and Centrify clients that allow Linux computers to join AD domains... no AD schema extensions are required because those clients use preexisting attributes in AD to store Unix-specific information.
Yes attributes have a set size limit, and that limit is different for every attribute. Not just size limit, but they can be different types of data as well. A multi-valued string, for instance. Each attribute can also have a specific allowed range, security descriptor, etc. These constraints are fixed as part of the schema.  Here is a reference of Active Directory attributes... the info is a little old but the idea is the same. You have linked attributes, ANR (ambiguous name resolution) attributes, etc., that all behave a little differently and have different purposes.
As a last piece of advice - consider any changes you make to your AD schema permanent and irreversible. So do it only after a lot of forethought and planning.

A:
Are there any known read/write performance issues (from C#) with using them for this purpose?

A multivalued attribute offers better query performance than using a single-valued attribute and separating multiple pieces of information with delimiters.  Just like SQL Server, if a query wildcard is prefixed with an *, the performance will be poor.  When you query for a non-wildcard value or a wildcard suffixed value, and it matches one of the values in a multivalued attribute, the query succeeds.  Some people are unaware of that advantage.
Attributes may also be indexed, and you should consider doing that.
If you have multiple domains and need the information available in other domains than the object that has the attribute, you may want to add the attribute to the Global Catalog (sometimes called the Partial Attribute Set or Filtered Attribute Set).

Indexing in Active Directory
Creating More Efficient Microsoft Active Directory-Enabled Applications


text:
Q: pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None) while running with task scheduler on a server I'm attempting to use Python to convert xlsx files to PNGs.
I created an executable file and am attempting to run it from the server. Every time I try to manually run the exe, everything goes smoothly. But the exe throws the following error whenever I try to run this task from the task scheduler.
import cv2
import os
import base64
import excel2img
import time

def create_img(excel_path, root_loc,file_first):
    # workbook = Workbook(excel_path)

    wb_file_name = excel_path

    os.chdir('../')
    f_first = file_first
    img_folder = os.path.join(root_loc, 'images')
    print(img_folder)

    img_path = os.path.join(img_folder, f'{f_first}.png')
    print(img_path)

    time.sleep(5)
    excel2img.export_img(excel_path, img_path, "", "Sheet1!B2:L47")

The error:
Traceback (most recent call last):
  File "excel2img\excel2img.py", line 120, in export_img
  File "<COMObject Range>", line 2, in CopyPicture
  File "win32com\client\dynamic.py", line 368, in _ApplyTypes_
pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 748, in <module>
  File "xl_to_img2.py", line 23, in create_img
  File "excel2img\excel2img.py", line 84, in export_img
  File "excel2img\excel2img.py", line 39, in __exit__
  File "excel2img\excel2img.py", line 64, in close
  File "<COMObject Open>", line 2, in Close
pywintypes.com_error: (-2147418111, 'Call was rejected by callee.', None, None)

How to fix it?


text:
Q: How did Ron find Harry in the pond? How did Ron get the Horcrux locket off Harry when they were in the lake/pond? How did he find them in the first place?

A: Ron found Harry and Hermione using the Deluminator. It released a ball of energy that somehow (insert plothole here) guided him to his friends' location.

'So I took it out,' Ron went on, looking at the Deluminator, 'and it didn't seem different, or anything, but I was sure I'd heard you. So I clicked it. And the light went out in my room, but another light appeared right outside the window.'
Ron raised his empty hand and pointed in front of him, his eyes focused on something neither Harry nor Hermione could see.
'It was a ball of light, kind of pulsing, and bluish, like that light you get around a Portkey, you know?'
'Yeah,' said Harry and Hermione together, automatically.
'I knew this was it,' said Ron. 'I grabbed my stuff and packed it, then I put on my rucksack and went out into the garden.
'The little ball of light was hovering there, waiting for me, and when I came out it bobbed along a bit and I followed it behind the shed and then it … well, it went inside me.'
'Sorry?' said Harry, sure he had not heard correctly.
'It sort of floated towards me,' said Ron, illustrating the movement with his free index finger, 'right to my chest, and then – it just went straight through. It was here,' he touched a point close to his heart, 'I could feel it, it was hot. And once it was inside me I knew what I was supposed to do, I knew it would take me where I needed to go. So I Disapparated and came out on the side of a hill. There was snow everywhere …'
'We were there,' said Harry. 'We spent two nights there, and the second night I kept thinking I could hear someone moving around in the dark and calling out!'
'Yeah, well, that would've been me,' said Ron. 'Your protective spells work, anyway, because I couldn't see you and I couldn't hear you. I was sure you were around, though, so in the end I got in my sleeping bag and waited for one of you to appear. I thought you'd have to show yourselves when you packed up the tent.'

Once he found Harry, Ron swam down to collect the Sword of Gryffindor from the bottom of the lake and used it to cut the Horcrux off of Harry's neck.

Nothing but the shock of hearing that voice could have given Harry the strength to get up. Shivering violently, he staggered to his feet.
There before him stood Ron, fully dressed but drenched to the skin, his hair plastered to his face, the sword of Gryffindor in one hand and the Horcrux dangling from its broken chain in the other.
*'Why the hell,' panted Ron, holding up the Horcrux, which swung backwards and forwards on its shortened chain in some parody of hypnosis, 'didn't you take this thing off before you dived?'
HP: DH

A: The Deluminator that Dumbledore left him in his will. It started to transmit the words that Harry and Hermione were saying, and then a ball of light came out of it, and went inside him. So Ron Apparated to the forest, where he found Harry. Will add quotes later.

"No, I heard you coming out of my pocket. Your voice," he held up the Deluminator again, "came out of this."
...
"And the light went out in my room, but another light appeared right outside my window. ... It was a ball of light, kind of pulsing, and bluish, like that light you get around a Portkey, you know?"
'Yeah,' said Harry and Hermione together, automatically.
'I knew this was it,' said Ron. 'I grabbed my stuff and packed it, then I put on my rucksack and went out into the garden.
'The little ball of light was hovering there, waiting for me, and when I came out it bobbed along a bit and I followed it behind the shed and then it … well, it went inside me.'
'Sorry?' said Harry, sure he had not heard correctly.
'It sort of floated towards me,' said Ron, illustrating the movement with his free index finger, 'right to my chest, and then – it just went straight through. It was here,' he touched a point close to his heart, 'I could feel it, it was hot. And once it was inside me I knew what I was supposed to do, I knew it would take me where I needed to go. So I Disapparated and came out on the side of a hill. There was snow everywhere …'

And he cut the Horcrux off of Harry with the Sword of Gryffindor. Later he stabbed the locket with the Sword, destroying it.


text:
Q: robovm plugin won't work I'm trying to use robovm on Eclipse. I have installed the robovm plugin.
But when I create a RoboVM eclipse project, Eclipse gives me an exception:
The selected wizard could not be started.
Plug-in org.robovm.eclipse.ui was unable to load class org.robovm.eclipse.internal.NewCocoaTouchProjectWizard.
An error occurred while automatically activating bundle org.robovm.eclipse.ui (244).

I get a similar message when I try to go to "Settings" > "RoboVM":
Unable to create the selected preference page.
An error occurred while automatically activating bundle org.robovm.eclipse.ui (244).

Can anyone can help me?
Eclipse Standard/SDK

Version: Kepler Service Release 1
Build id: 20130919-0819

A: It was fixed by RoboVM.
Show following resources:
Issue #246 on https://github.com/robovm/robovm/issues/246
Commit #1702b68 from https://github.com/robovm/robovm/commit/1702b68ffd362788fab74a8d9cbf2bd6411bcf5f

A: A moderator has delete my answer - Confusing why (reason: "your post was converted to a comment")!
For future readers,
Here is the right answer:

But i've found and solved the Problem today. I had installed Java 6 AND 7. eclipse had use Java 6.
For other peoples there have the same Problem: Go to the Settings App > Java and go to the Java-Tab. Here are all installed Java versions listed. Change the priority for the version otherwise deinstall or disable older Versions.


text:
Q: Horizontal navigation bar messes up when I resize window plus more I am working on making a website that sells music as a class project. I made a horizontal navigation bar but when I resize the window... it messes up.
PICS:
Full screen on my laptop:
http://i.imgur.com/86iazhM.png
Resized:

Heres my code for the bar:
The css part
 span{}
.bar{
display:inline;
padding:2.5cm;
}

#top{
background-color:#000000;
padding:16px;
}

#top a{
text-decoration: none;
color:white;
}

#top a:hover{
background-color:#FF9900;
}

Heres the html part:

HOME

DOWNLOAD

POPULAR

CONTACT

CONNECT

how do I fix this?
Question 2) how do I make an image appear beside my vertical navigation bar? When i do float:right for the image, it goes to the right but it does so below the navigation bar not beside it. Thanks a lot!

A: Question 1 try to use
.bar{
   display:inline-block;
   padding:2.5em;
 }

Q2 to append an image u can use background-image: or pseudo element :before

A:  .bar{
       display:inline-block;
       padding:5px;
      width:19.233333%;
      border:1px solid red;
      float:left;
      position:relative;
  }

A: You have used li tag under span which is incorrect. li should always be within ul tag. Best way to create menu is as follows:
<!doctype html>

HOME

DOWNLOAD

POPULAR

CONTACT

CONNECT

HOME

DOWNLOAD

POPULAR

CONTACT

CONNECT

Ans 2) You can add float:left for image tag/image container to make it beside vertical menu. (Please note that vertical menu should also have float:left property.)