text:
Q: Embeddable CMS for .NET Can you recommend a CMS framework that could be embedded into existing web application?
The requirements are:

*

*Users can go nuts and customise it to their liking.

*User friendly and easy to use.

*Should support multitenancy (users have their own sites).

*Should support multiple subdomains (so file uploads and stuff should not be mixed up).

*Use existing (very) custom authentication and authorisation system.

*Should be part of the application so that it is easy to share the same database and data structures.

*Should be easily unit-testable.

Thanks.

A: I would say CMS is not supposed to be used as an embedded into existing web applicaton. In this case I would suggest to find not CMS, but some third-party components that will do everything for you: EntLib for User Authentication, Yahoo UI for User Experience, and so on.
In other way take a look at Orchard Project by Microsoft - it's free, open source, well structured and organized (modules, ui customization, IoC, etc.), and well community supported CMS.
If your web application is made with ASP.NET MVC then it will not be hard to make 'a Bridge' between Orchard CMS API and your web application -- Model, Business Logic, Controllers ("Drivers" in terms of Orchard), etc. as Orchard Modules.

A: It turned out that Orchard was as close as you can get in .NET.
Unfortunately it sounds good in theory but showed itself bad in practice.
The answer to the questions - there is none.
You would be better of using an external one or just roll your own with small feature sets.
Neither solution is perfect and should be considered on a case-by-case basis.


text:
Q: Validation of youtube video through url id I am using php and yt API to determine if a video exists. I have implemented two functions two help me along this cause. The issues is with the function isYoutubeVideo is returning me  null value when a video is valid or invalid. I have checked its paremeters but I am still not sure why is giving me null value. Do i have the isYoutubeVideo function set up wrong/missing something/needs change?
        function isYoutubeVideo($formatted_url) {
            $isValid = false;
            if (isValidURL($formatted_url)) {
                $idLength = 11;
                $idStarts = strpos($formatted_url, "?v=");
                if ($idStarts === FALSE) {
                    $idStarts = strpos($formatted_url, "&v=");
                }
                if ($idStarts !== FALSE) {
                    //there is a videoID present, now validate it
                    $v = substr($formatted_url, $idStarts, $idLength);
                    $headers = get_headers('http://gdata.youtube.com/feeds/api/videos/' . $videoID);
                    //did the request return a http code of 2xx?
                    if (!strpos($headers[0], '200')) {
                        $isValid = true;
                    }
                }
            }
            return $isValid;

A: Why aren't your first two echo statements also echoing  ?;
With the current markup and jQuery code this is why jQuery populates #special with null.
You need to change you PHP code to:
echo('
The YouTube video does not exist.
');

echo('
that is a valid youtube video
');

Although, I do not understand why you used such a roundabout way to populate #special. You could have just started with a
 inside
 and then use the selector $("#special > p")
Good luck!

redpajama_set_name: RedPajamaStackExchange


text:
Q: parent and child directive communication issue i have two directives - a parent and a child
in the parent directive controller i have this particular code
$scope.someRandomFunction = function(){
        someService.getSomeRandomData().then(function (data) {
          $scope.dataForSomething = [];
          data.forEach(function(value) {
            var obj= {};
            obj.id = value.id
            obj.name = value.name;
            obj.moreData = [];
            $scope.dataForSomething.push(obj);
          });

          getData();
        });
      };

function getData(){
        sharedService.getSomething(opts).then(function (data) {
          //i'm putting some data in obj.moreData from the data that i get here
        });
      }

In my view i have
<parent-directive>

        <track val="val"></track>

</parent-directive>

The issue is before i get data from getData() - child directive executes due to which val.moreData comes out undefined as data has not yet come from the call made.

A: You need to process the data after the getData() promise has finished. Rather then access data from the scope. Try to chain promises by returning new values for the next call to then.
For example, getData and return innerData.
$scope.someRandomFunction = function(){
        someService.getSomeRandomData().then(function (outerData) {
          $scope.dataForSomething = [];
          getData(outerData).then(function(innerData){
             outerData.forEach(function(value) {
                 var obj= {};
                 obj.id = value.id
                 obj.name = value.name;
                 obj.moreData = [];
                 // array is updated after everything is ready.
                 $scope.dataForSomething.push(obj);
             });
          });
        });
      };

function getData(){
        return sharedService.getSomething(opts).then(function (data) {
             // do stuff with data, and then return it
             return data; // <-- turns into innerData var
        });
      }

<parent-directive>

        <track val="val"></track>

</parent-directive>


text:
Q: Firebase admin SDK getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND" I'm trying to set up the admin sdk and also created a new private key. I even reverted back to an old version with only the admin sdk and it won't work. Is there anything which could be cached on my device?
Nest application successfully started NestApplication true
Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND". Error: Credential implementation provided to initializeApp() via the "credential" property failed to fetch a valid Google OAuth2 access token with the following error: "Error fetching access token: Error while making request: getaddrinfo ENOTFOUND metadata.google.internal. Error code: ENOTFOUND".
    at FirebaseAppError.FirebaseError [as constructor] (/Users/user/Documents/Dev/project/demo/node_modules/firebase-admin/lib/utils/error.js:42:28)
    at FirebaseAppError.PrefixedFirebaseError [as constructor] (/Users/user/Documents/Dev/project/demo/node_modules/firebase-admin/lib/utils/error.js:88:28)
    at new FirebaseAppError (/Users/user/Documents/Dev/project/demo/node_modules/firebase-admin/lib/utils/error.js:122:28)
    at /Users/user/Documents/Dev/project/demo/node_modules/firebase-admin/lib/firebase-app.js:121:23
    at processTicksAndRejections (internal/process/task_queues.js:85:5)
    at /Users/user/Documents/Dev/project/demo/node_modules/@nestjs/core/router/router-execution-context.js:44:28
    at /Users/user/Documents/Dev/project/demo/node_modules/@nestjs/core/router/router-proxy.js:8:17 ExceptionsHandler

This is how I'm trying to use both packages:
import * as firebase from 'firebase-admin';
import * as serviceAccount from '../../firebase_credentials.json';

const config = {
    type: serviceAccount.type,
    projectId: serviceAccount.project_id,
    privateKeyId: serviceAccount.private_key_id,
    privateKey: serviceAccount.private_key,
    clientEmail: serviceAccount.client_email,
    clientId: serviceAccount.client_id,
    authUri: serviceAccount.auth_uri,
    tokenUri: serviceAccount.token_uri,
    authProviderX509CertUrl: serviceAccount.auth_provider_x509_cert_url,
    clientC509CertUrl: serviceAccount.client_x509_cert_url,
};

if (!firebase.apps.length) {
    firebase.initializeApp(config);
}

export const firebaseAuth = firebase.auth();

export function create(email: string, password: string) {
    firebaseAuth.createUser({
        email: email,
        emailVerified: false,
        password: password,
        displayName: email,
        disabled: false,
    })
        .then( (userRecord) => {
            // See the UserRecord reference doc for the contents of userRecord.
            console.log('Successfully created new user:', userRecord.uid);
        })
        .catch((error) => {
            console.log('Error creating new user:', error);
        });

}

What should I try to get this resolved?
Thanks for any help

A: You can't use both the Admin SDK and the regular Firebase JavaScript SDK in a single application. If the app runs in a potentially untrusted environment, you should use the regular JavaScript SDK. If it runs in a trusted environment (such as your development machine, a server you control, or Cloud Functions) you can use either the JavaScript SDK or the Admin SDK for that environment (in your case for Node.js).


text:
Q: How can you get the number of digits contained in a double? I'm trying to get the number of digits in the following double value: 56.46855976 without using converting it to a string (and simply replacing the "." with a "").
Anybody got any ideas?

A: Count how often you must divide the number by 10 until it's smaller than 1 -> that gives you the digits before the decimal point.
Then count how often you must multiply the original number by 10 until it equals the Math.Floor-result -> that gives you the digits behind the decimal points.
Add. Be glad.
Edit: As Joey points out, there is some uncertianity in it. Define a maximum number of digits beforehand so you don't create an infinite loop.
On the other hand - "How long is the coast of Denmark?"...

A:     /// Returns how many digits there are to the left of the .
    public static int CountDigits(double num) {
        int digits = 0;
        while (num >= 1) {
            digits++;
            num /= 10;
        }
        return digits;
    }

As Martin mentioned, counting to the right of the . is pointless.
Tests:
MathPlus.CountDigits(56.46855976)                 -> 2
MathPlus.CountDigits((double)long.MaxValue + 1)   -> 19
MathPlus.CountDigits(double.MaxValue)             -> 309

A: Converting to a string might be the best option you have. Remember that doubles are represented in Base 2 internally. Therefore the decimal representation you see is only an approximation of the actually stored value (except for integers up to 253) which is a sum of individual powers of 2.
So trying to figure out the number of decimal digits from the binary representation is certainly not an easy or trivial task – especially since the framework might also apply rounding to make numbers like 3.999999999998 appear like 4.0 since they appear to have more precision than there actually is.


text:
Q: Start another activity to show image correspondingly of json after clicking the items in recycler view I have a recycler view which shows a list of all the movies title after parsing json . Now what i would like to achieve is that i want to start another activity to show a poster of each movie title . Like when i click on first list item named "Jurassic" then it should show me the jurassic poster,
second item named "The planet" , it should show me the poster of the planet movie after clicking on it.
Here it's my code for the onClickListener in my adapter
NowPlayingAdapter.class
 package swipe.vivek.com.swipedown.helper;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.NetworkImageView;

import java.util.List;

import swipe.vivek.com.swipedown.Fragments.ContentFragment;
import swipe.vivek.com.swipedown.Fragments.Top;
import swipe.vivek.com.swipedown.MainActivity;
import swipe.vivek.com.swipedown.R;
import swipe.vivek.com.swipedown.activity.Single;
import swipe.vivek.com.swipedown.app.AppController;

/**
 * Created by Shiva on 01-07-2015.
 */
public class NowPlayingAdapter extends RecyclerView.Adapter<NowPlayingAdapter.NowPlayingHolder> {
    @Override
    public NowPlayingHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.listnow , parent ,false);

        return new NowPlayingHolder(v);
    }

    @Override
    public void onBindViewHolder(NowPlayingHolder holder, int position) {
        NowPlayingInfo trailer_info = trailer.get(position);

         holder.title.setText(trailer_info.getTitle());

    }

    @Override
    public int getItemCount() {
        return trailer.size();
    }

    Activity activity;
    public List<NowPlayingInfo> trailer ;
    public NowPlayingAdapters(Activity activity , List<NowPlayingInfo> trailer){
        this.activity = activity;
        this.trailer = trailer;
    }

    public static class NowPlayingHolder extends RecyclerView.ViewHolder implements View.OnClickListener{

        protected TextView title ;

        public NowPlayingHolder(View v){

            super(v);
            v.setOnClickListener(this);
            title = (TextView)v.findViewById(R.id.titleText);

        }

        @Override
        public void onClick(View view) {
            List<NowPlayingInfo> list;

            Intent i = new Intent(view.getContext() , Single.class);
            view.getContext().startActivity(i);
        }
    }
}

Where Single.class is :
package swipe.vivek.com.swipedown.activity;

import android.app.ProgressDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import swipe.vivek.com.swipedown.R;
import swipe.vivek.com.swipedown.app.AppController;
import swipe.vivek.com.swipedown.helper.NowPlayingAdapter;
import swipe.vivek.com.swipedown.helper.NowPlayingInfo;

/**
 * Created by Shiva on 02-07-2015.
 */
public class Single extends AppCompatActivity {

    private static final String TAG = Single.class.getSimpleName();

    // Movies json url
    private static final String url = "http://private-8149-themoviedb.apiary-mock.com/3/movie/now_playing?api_key=";
    private ProgressDialog pDialog;
    private List<NowPlayingInfo> bottom = new ArrayList<NowPlayingInfo>() ;

    NowPlayingAdapter adapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.singleimage);
        adapter = new NowPlayingAdapter(this, bottom);

        pDialog = new ProgressDialog(this);
        // Showing progress dialog before making http request
        pDialog.setMessage("Loading...");
        pDialog.show();

        JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, url, null,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        try {

                            JSONArray jsonArray = response.getJSONArray("results");
                            for (int i = 0; i < jsonArray.length(); i++) {

                                JSONObject jsonObject = jsonArray.getJSONObject(i);
                                NowPlayingInfo trailer = new NowPlayingInfo();

                                String iss = "http://image.tmdb.org/t/p/w500" + jsonObject.getString("poster_path") ;
                                trailer.setImage(iss);
                                bottom.add(trailer);
                                adapter.notifyDataSetChanged();

                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        adapter.notifyDataSetChanged();
                    }

                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                hidePDialog();
            }
        });
        AppController.getInstance().addToRequestQueue(jsonObjectRequest);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        hidePDialog();
    }

    private void hidePDialog() {
        if (pDialog != null) {
            pDialog.dismiss();
            pDialog = null;
        }
    }
}

Its not displaying the poster ..just the empty image view. pls help me.

A:         List<NowPlayingInfo> list;

        Intent i = new Intent(view.getContext() , Single.class);
        view.getContext().startActivity(i);

You're not doing anything with list there in your onClick method. My guess is the Single class doesn't know what to display. Try logging out iss to make sure that URL goes to an actual image.


text:
Q: Lindenbaum's lemma and algebraic closures Lindenbaum's lemma in predicate logic states that every consistent, first order theory $K$ has an extension to a consistent, complete extension.  This sounds very similar to the theorem  that every field has an algebraic closure.  In fact, the process of building such a theory is similar to building a field extension (i.e.  Given a consistent theory $K$ such that it's not the case that $\vdash_K \neg \beta$, let $K'$ be the theory obtained from $K$ by introducing $\beta$ as an axiom).   The complete, consistent extension is obtained inductively in the manner.
Are there any deeper connections between Lindenbaum's lemma and algebraic closures?

A: I am not aware of any intrinsic (non-formal) similarity between the two theorems. So I think it's just the very similar form of proofs they admit.
This begins with the somewhat similar definitions ("a structure that contains some type of witness for every element of some set") of the sought-after structures:

*

*A first-order theory $K$ is complete if it decides every formula $\phi$, i.e. for all $\phi$, either $K \vdash \phi$ or $K \vdash \neg \phi$.

*A field $F$ is algebraically closed if each polynomial $p \in F[X]$ has a root in $F$.

This similarity is reflected by the following proofs by means of Zorn's Lemma (details omitted):

*

*Given a consistent theory $(K_0,\Phi_0)$ ($\Phi_0$ is the set $\{\phi: K_0\vdash \phi\text{ or }K_0\vdash \neg\phi\}$). Let $(P, \le)$ be the poset with consistent theories $(K,\Phi)$ extending $(K_0,\Phi_0)$ as elements. Let $(K,\Phi) \le (K',\Phi')$ iff $\Phi \subseteq \Phi'$. It is non-empty and by the compactness theorem, $(\bigcup_i K_i, \bigcup_i \Phi_i)$ is an upper bound for a chain $(K_i,\Phi_i)_i$. By Zorn's Lemma, we have a maximal element, which is a complete and consistent theory extending $K_0$.

*Given a field $(F_0,Z_0)$ ($Z_0$ is the set of polynomials $\{p\in F_0[X]: \exists f \in F_0\,p(f)=0\}$). Let $(P,\le)$ be the poset with fields $(F,Z)$ containing $(F_0,Z_0)$ as elements (NB. I gloss over the matter of selecting a set of fields, which would obscure the main idea at work). Let $(F,Z) \le (F',Z')$ iff $Z \subseteq Z'$. Then $(\bigcup_i F_i,\bigcup_i Z_i)$ is an upper bound for a chain $(F_i,Z_i)_i$. By Zorn's Lemma, we have a maximal element, which is an algebraically closed extension of $F$.

Besides these rather similar proofs (which rely on some finiteness property of the relevant elements: the compactness theorem cq. that a polynomial has finitely many nonzero coefficients) I don't see any connection.


text:
Q: How does one verify that the app store version of an open source app is running the same code? There are many "open source" apps like K-9 mail on the android app store. If I compile and build the source code myself, I can be sure that the resulting apk, will indeed do what the source code says it will do.
But how can I verify, that the apk submitted to the store is actually the result of compiling the same source ? What is to stop the makers of k9 of inserting malicious code in the version submitted to the app store ? I don't see any hash, or other way of verifying the source.
(K-9 is just an example).

A: Compare the contents of the APKs: the one you pull off the device (that you got from the Play Store or wherever) and the one that you compiled yourself. If the compiled classes differ, then there may be cause for deeper investigation. It's possible the differences come from differences in compilers, bytecode converters, or obfuscator settings. Or, it's possible that the differences are indicative of "malicious code". That work is up to you.
Or, use a store like F-Droid that compiles from source itself.
Or, just use the version that you compiled from source yourself.


text:
Q: Requests python and dio flutter does not return same result I have python code like
import requests
headers = {'Host': 'www.google.com','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0','Accept': '*/*','Accept-Language': 'en-US,en;q=0.5','Accept-Encoding': 'gzip, deflate, br','Referer': 'https://www.google.com/','Origin': 'https://www.google.com','Connection': 'keep-alive','Content-Length': '0','TE': 'Trailers'}
response = requests.get("https://www.google.co.in/search?tbs=sbi:AMhZZivWlHh9fYSFQ1SYSgdWdYroq7vlNqRWbgzAeOHgb1_1aVO6EfHf9oo4N6kMf9pR-MjgXMeP5EG4VTTeZ5UujHI12znActXxMoyDqKsqI0cgI9YJ_11xd5R0DiKpo2drjWKnK2lNgGSGJYKdDFJ0ZNKhfBTUn3WKSmG72gLR07uPXdby9jCXC1KJFqBSpaGNrJ6Zc6LSQymwNqqJZrO8iwNYRPzJsoHlWUZNSoZ1X18Ii8X7x0TrlgSz0HySJ_1QO3E8LLbaE0rZluLVBsk6t0GDW2MR4IXs3dCuCcTMPDgqZS-CMks6Tgc6xkDLyLLBC051S6gNxRhXpZ3FVg75Vlt_1nAptI_1Vpw",headers=headers)
print(len(response.text))

and a flutter code like
import 'package:dio/dio.dart';
Dio dio = Dio();
var headers = {'Host': 'www.google.com','User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:71.0) Gecko/20100101 Firefox/71.0','Accept': '*/*','Accept-Language': 'en-US,en;q=0.5','Accept-Encoding': 'gzip, deflate, br','Referer': 'https://www.google.com/','Origin': 'https://www.google.com','Connection': 'keep-alive','Content-Length': '0','TE': 'Trailers'};
var response = await dio.get("https://www.google.co.in/search?tbs=sbi:AMhZZivWlHh9fYSFQ1SYSgdWdYroq7vlNqRWbgzAeOHgb1_1aVO6EfHf9oo4N6kMf9pR-MjgXMeP5EG4VTTeZ5UujHI12znActXxMoyDqKsqI0cgI9YJ_11xd5R0DiKpo2drjWKnK2lNgGSGJYKdDFJ0ZNKhfBTUn3WKSmG72gLR07uPXdby9jCXC1KJFqBSpaGNrJ6Zc6LSQymwNqqJZrO8iwNYRPzJsoHlWUZNSoZ1X18Ii8X7x0TrlgSz0HySJ_1QO3E8LLbaE0rZluLVBsk6t0GDW2MR4IXs3dCuCcTMPDgqZS-CMks6Tgc6xkDLyLLBC051S6gNxRhXpZ3FVg75Vlt_1nAptI_1Vpw",options: Options(headers: headers,followRedirects: true));
var a=response.data;
print(a.length);

The problem is that the result I am getting from both of the packages is not same. I want the output of python but have to implement python code in flutter. Flutter solution with any other package is also nice...


text:
Q: Adding several banners over each other Can we add multiple banners over each other within the same view controller?
It's technically possible, but is it legal for us to add several AdMob or iAd banners over each other in the same view controller so we can earn more money?

A: Is it possible, yes. Will it make you more money, no. The revenue generated per an impression of an ad is a fraction of the revenue generated per a tap on an ad. In addition, the iAd network will not like your app requesting numerous ads repeatedly and will in turn lower your fill rate. I would imagine AdMob has similar safeguards in place to avoid scenarios like this. As far as legal, I'm sure it would violate both Apple's and Google's TOS if you were to implement this.

A: You will get yourself kicked out of the Admob program permanently really quickly.

*

*It's against Googles Terms of Service.

*You earn money for clicks, not ad displays.

*Google can detect this. They know what the click through rate for apps and ads should be. If your app displays 8 times as many ads as anybody else or more clicks or less clicks, their automated computers will detect it and you will be kicked out, no money for you. Don't mess with Google - if you are kicked out there is no way back in. It is permanent.


text:
Q: laravel route undefined ErrorException in UrlGenerator.php I can't find solution to my Laravel routing error. Whenever I visit the link it shows the error 404 - page not found. Can any body help on this error. Below is my codes-
In web.php
Route::get('/post-ads-new/{cat}/{sub_cat}','PostController@postAdsNew');

In PostController.php
public function postAdsNew($cat,$sub_cat)
  {

        return view('post-ads-new');
  }

And used the url in HTML as
<a href="<?php echo $url.'/post-ads-new/?cat='.$category->id;?>&<?php echo 'sub_cat='.$sub_category->subid;?>">

A: You should use Laravel URL generator by adding a name to your route
Route::get('/post-ads-new/{cat}/{sub_cat}','PostController@postAdsNew')->name('ads');

And in your view:
Blade version:
 $category->id, 'sub_cat' => $sub_category->subid]) }}">

Native PHP version:
<a href="<?= route('ads', ['cat' => $category->id, 'sub_cat' => $sub_category->subid]) ?>">

Here is the documentation https://laravel.com/docs/7.x/urls

A: The variables are unnecessary in the url, you will need to construct your url like the following:
<a href="<?php echo $url.'/post-ads-new/'.$category->id.'/'.$sub_category->subid;?>">


text:
Q: Strange line-height in Chrome I'm experiencing a big problem with line height and block height which is a multiplicity of it. I have font-size of 15px, line height 1.5em (22.5px) and div height of: 16 lines * 1.5em = 24 em. It looks well in Firefox and MS Edge - div contains only 16 lines, as expected. But in Chrome actual text height becomes a bit smaller! And it shows also the parts of 17th line in blocks. Looks very weird.
Why does it happen and how to fix it with CSS?

.post-preview_main__content {
  box-sizing: border-box;
  font-size: 15px;
  height: 24em;
  line-height: 1.5em;
  width: 420px;
  overflow: hidden
}

p {
  margin: 0;
  padding: 0;
}

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates, necessitatibus, quidem in beatae quae quo perspiciatis nihil adipisci aut fuga ad possimus illo nisi vitae libero debitis accusantium magni esse. ipsum dolor sit amet, consectetur
    adipisicing elit. Culpa, natus, deleniti tenetur quos hic voluptate itaque nobis

cum magni magnam ipsa enim a labore maxime repellendus eaque exercitationem nihil doloribus! ipsum dolor sit amet, consectetur adipisicing elit. Quidem, aliquam voluptate atque ipsa eveniet tempore sed cumque non magnam accusamus enim consectetur fuga
    fugiat ducimus dolorum temporibus dolor facilis doloribus. ipsum dolor sit amet, consectetur adipisicing elit. Inventore, quisquam, vel dignissimos natus porro veniam velit quia odit quam dolorum reprehenderit vero eos modi non ea voluptate eligendi
    consectetur officia.

 cum magni magnam ipsa enim a labore maxime repellendus eaque exercitationem nihil doloribus! ipsum dolor sit amet, consectetur adipisicing elit. Quidem, aliquam voluptate atque ipsa eveniet tempore sed cumque non magnam accusamus enim consectetur fuga
    fugiat ducimus dolorum temporibus dolor facilis doloribus. ipsum dolor sit amet, consectetur adipisicing elit. Inventore, quisquam, vel dignissimos natus porro veniam velit quia odit quam dolorum reprehenderit vero eos modi non ea voluptate eligendi
    consectetur officia.

cum magni magnam ipsa enim a labore maxime repellendus eaque exercitationem nihil doloribus! ipsum dolor sit amet, consectetur adipisicing elit. Quidem, aliquam voluptate atque ipsa eveniet tempore sed cumque non magnam accusamus enim consectetur fuga
    fugiat ducimus dolorum temporibus dolor facilis doloribus. ipsum dolor sit amet, consectetur adipisicing elit. Inventore, quisquam, vel dignissimos natus porro veniam velit quia odit quam dolorum reprehenderit vero eos modi non ea voluptate eligendi
    consectetur officia.

cum magni magnam ipsa enim a labore maxime repellendus eaque exercitationem nihil doloribus! ipsum dolor sit amet, consectetur adipisicing elit. Quidem, aliquam voluptate atque ipsa eveniet tempore sed cumque non magnam accusamus enim consectetur fuga
    fugiat ducimus dolorum temporibus dolor facilis doloribus. ipsum dolor sit amet, consectetur adipisicing elit. Inventore, quisquam, vel dignissimos natus porro veniam velit quia odit quam dolorum reprehenderit vero eos modi non ea voluptate eligendi
    consectetur officia.

Firefox:

Chrome:

A: I figured out that the problem is in a fractional value of line-height - 22.5px (15px*1.5), WebKit doesn't handle this right, and this is its great disadvantage.
The problem is that even if I change line-height to give me integer px value, I can't keep it integer while font-size changes when user scales the page.


text:
Q: $(document).ready(function () not triggering again when form is submitted I have a Jquery script to launch a modal popup window as follows :-
<script type="text/javascript">
$(document).ready(function () {

    $('.modal_part').fadeIn('slow');
    $('#tn_select').load('OnBoarding.aspx');

});
</script>

This works fine first time, however when I submit the form, it is not being called the second time, and as so I am loosing all the css classes and also the form is not loading in a modal window again.
Is there a way to trigger this Jquery again after I submit the form?
Thanks for your help and time

A: if you are using update panel
than
try this
after postback call your javascript function
   //SCRIPT to refresh when data come from update panel
        var prm = Sys.WebForms.PageRequestManager.getInstance();
        prm.add_endRequest(EndRequest);
        function EndRequest(sender, args) {
           $('.modal_part').fadeIn('slow');
           $('#tn_select').load('OnBoarding.aspx');
        }

A: If you are using UpdatePanel in your page then you need to rebind all the event when AJAX request ends.
    function BindEvents(){
        //your code here
    }
    var prm = Sys.WebForms.PageRequestManager.getInstance();

    prm.add_endRequest(function() {
        BindEvents();
    });

    $(document).ready(function () {
        BindEvents();
    });

A: Try :
 $(document).ready(function () {

    modal(); // call this wherever necessary

 });

 function modal() {
     $('.modal_part').fadeIn('slow');
     $('#tn_select').load('OnBoarding.aspx');
 }

If your form using ajax use modal() on "success" of the ajax call.

A: Make a hidden field in your page ...and when you submit the page set the value in it..
again in page load you need to place a check for the value..
in aspx
<asp:HiddenField ID="hdnfld" runat="server"/>

Now in JS :-
<script type="text/javascript">
$(document).ready(function () {
    var myval=$("#hdnfld").val();
if(myval=="submitted"){
// this will execute after submit:-// you can add necessary code here :-
    $('.modal_part').fadeIn('slow');
    $('#tn_select').load('OnBoarding.aspx');
    // Set its value again to null;
    $("#hdnfld").val("");
}
else
{
    // This will execute when page will load first time :-
    $('.modal_part').fadeIn('slow');
    $('#tn_select').load('OnBoarding.aspx');
}

});
</script>

and in Code Behind:-
protected void btn1_clicked(object sender,EventArgs e){
// set the hdn field:-
hdnfld.value="submitted";
}

A: If you are using update panel try using the below code:
Try calling jquery function:
function pageload(sender, args){
    //jquery code here
}

Instead of document.ready function.


text:
Q: Different chi-square answers from application of chi-test I have calculated the chi-test for two variables hhldsize and tenure through two functions chi.test and crosstable() (wherein I set expected=TRUE to calculate it below the crosstable). I did so just to double check that I had the same answers and was surprised to find that they were different as the p-values werent the same. Now i'm not sure which one I'm supposed to use in interpreting the graph...
(the two variables are both contained in the object hhldsize.tenure )
Standalone chi-test code and output:
> chisq.test(hhldsize.tenure$hhldsize, hhldsize.tenure$tenure, correct=FALSE)

Pearson's Chi-squared test

data:  hhldsize.tenure$hhldsize and hhldsize.tenure$tenure
X-squared = 114.75, df = 10, p-value < 2.2e-16

Warning message:
In chisq.test(hhldsize.tenure$hhldsize, hhldsize.tenure$tenure,  :
  Chi-squared approximation may be incorrect

CHI TEST THROUGH CONTINGENCY TABLE CODE:

Your help is much appreciated!


text:
Q: How to serializer and deseralize a sub class of set as a known set with jackson 2 I am trying to serializde a jpa managed class (openjpa).
This class contains a set. At runtime this set's type is org.apache.openjpa.util.java$util$LinkedHashSet$proxy (we're using openjpa).
Jackson will serialize this fine but then will fail when it comes to deserialize as this type cannot be constructed (and when using spring security's jackson config, it is not whitelisted).
So now I think the solution is to customise the serialization so it is serailized and deserialized as a more standard set. When it is deserialized it need only implement Set.
And I want to try and avoid polluting the persistent class (so want to use mixins).
The container class is the User class and it contains set of the Role class.
So far I have:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY, getterVisibility = JsonAutoDetect.Visibility.NONE)
public static class UserMixin {
    @JsonDeserialize(as = LinkedHashSet.class, contentAs = LinkedHashSet.class)
    @JsonSerialize(as = LinkedHashSet.class, contentAs = LinkedHashSet.class, typing = Typing.DYNAMIC)
    private Set<Role> roles;

}

But when I run with this I get
Invalid definition for property roles (of type 'Lxxx/yyy/User;'): Can not refine serialization content type [simple type, class xxx.yyy.Role] into java.util.LinkedHashSet; types not related
And this error occurs when serializing.
So it seems like it is not honouring the set container or something.

A: So the answer that I settled is on is based on how jackson does not support non standard collections out of the box. It stands to reason that only java sdk collections would work out of the box.
So what I ended up doing is the same thing that spring security does with the non standard collections it adds.
context.setMixInAnnotations(Collections.<Object>unmodifiableSet(Collections.emptySet()).getClass(), UnmodifiableSetMixin.class);

(from org.springframework.security.jackson2.CoreJackson2Module)
So I did the same:
context.setMixInAnnotations(org.apache.openjpa.util.java$util$LinkedHashSet$proxy.class, OpenJpaLinkedHashSetProxyMixin.class);

This means that I can customise how jackson treats this class.
Now jackson serializes this collection no problem. The problem has ever been with serialization. Jackson seems to support any sub class of Set when it comes to serialization. It is on deserialization that it struggles.
That Spring does is provide a custom deserializer for that unmodifiable set and that seems to be the only way to go with this.
So then the mixin:
@JsonTypeInfo(use = JsonTypeInfo.Id.CLASS, include = JsonTypeInfo.As.PROPERTY)
@JsonDeserialize(using = Deserializer.class)
public static class OpenJpaLinkedHashSetProxyMixin {

}

Where minor adjustments are made on the deserializer copied from

org.springframework.security.jackson2.UnmodifiableSetDeserializer

and is:
class UnmodifiableSetDeserializer extends JsonDeserializer<Set> {

    @Override
    public Set deserialize(JsonParser jp, DeserializationContext ctxt) throws IOException, JsonProcessingException {
        ObjectMapper mapper = (ObjectMapper) jp.getCodec();
        JsonNode node = mapper.readTree(jp);
        Set<Object> resultSet = new HashSet<Object>();
        if (node != null) {
            if (node instanceof ArrayNode) {
                ArrayNode arrayNode = (ArrayNode) node;
                Iterator<JsonNode> nodeIterator = arrayNode.iterator();
                while (nodeIterator.hasNext()) {
                    JsonNode elementNode = nodeIterator.next();
                    resultSet.add(mapper.readValue(elementNode.traverse(mapper), Object.class));
                }
            } else {
                resultSet.add(mapper.readValue(node.traverse(mapper), Object.class));
            }
        }
        return Collections.unmodifiableSet(resultSet);
    }
}

I just return the hash set directly (without wrapping it in the unmodifiable set) for example.
I guess the bottom line is that I do not need the set serialized back into the same class it came from (org.apache.openjpa.util.java$util$LinkedHashSet$proxy) so as long as it is a Set it doesn't matter what implementation. In this case I think the implementation is HashSet.
And I suspect this is the recommended/only way to successfully deserialize collections that jackson does not support out of the box.


text:
Q: y-axes misaligning in highcharts after zooming in In my application, I create a highcharts object, with zoomtype set to xy. Each dataset has its own y-axis due to different range of values (e.g. one dataset could have an infinite max, whereas other percentage based values are limited to 100/-100). If a dataset with only positive values and a dataset with both positive and negative values are loaded, I can align the zeros of the y-axes nicely.
However, upon zooming in, the zeros disalign. If I would zoom in on the range of 20 to -10, datasets that don't have any negative values will only show the range of 20 to 0. After resetting the zoom everything is fine. If I use the y-axis that's added by default by highcharts, the bars of the column graph are aligned nicely upon zooming in. However, this doesn't solve the issue of the zeros disaligning. I've been running into this issue for a few days now and I can't seem to solve it. I've tried playing around with the yAxis settings, and other settings of the graph, but this didn't solve anything for me either.
Any help would be appreciated and if needed I can supply some of my code.
Code for adding y-axis:
function addYAxis(opposite){
chart.addAxis({

    // set ID to axis number
    id: yAxisCounter,

    // Don't align the labels on the y-axis
    alignTicks: false,

    // Don't allow decimals values on the axis labels
    allowDecimals: false,

    // set max padding to 0
    maxPadding: 0,

    // set minimum padding to 0 so the chart does not add any padding
    minPadding: 0,

    // Hide this axis if it doesn't have associated values and/or labels
    showEmpty: false,

    // Set the space between labels on the axis
    //tickInterval: tickInterval,
    tickPixelInterval: 25,

    // set the color of the gridlines in the chart
    gridLineColor: '#FFFFFF',

    // set the location of the yAxis
    opposite: opposite,

    // Construct label value that is shown when hovering over a bar in the chart
    labels: {
            formatter: function(){
                return this.value;
            },
            style: {

                // Set the color of the label text
                color: getColor(),

                // Set the letter size of the label text
                fontSize: 10
            }
    }
});
}

function addSeries(id, vals){
// Add a series of data to the chart;
chart.addSeries({

  // Construct series name
  name: id,

  // Construct identifier to we can distinguish different datasets
  identifier: id,

  // Set the data
  data: vals,

  // Link these series to the current y-Axis
  yAxis: yAxisCounter,

  // Make this series visible
  visible: true,

  // Don't add shadows'
  shadow: false,

  // Set the color of the bars associated to these values
  color: getColor()
});
}

Code after resetting zoom:
chart.axes[0].setExtremes(chart.axes[0].dataMin, chart.axes[0].dataMax);
var yAxes = chart.yAxis;
var negativeVals = false;

// Check if any of the yAxes contain negative values in the associated dataset
for (var axis in yAxes){
    var minVal = yAxes[axis].dataMin;
    if (minVal < 0){
        negativeVals = true;
    }
}

// Loop through the y-axes
for (var axis in yAxes){

    // Get the min and max vals of the associated dataset
    var minVal = yAxes[axis].dataMin;
    var maxVal = yAxes[axis].dataMax;

    // If we have any negative values
    if (negativeVals){

        // Boolean to determine if the maximum value is larger than the minimum
        var maxGreaterThanMin = maxVal >= (minVal * -1);

        // If the maximum value is greater than the absolute minimum value
        if (maxGreaterThanMin){

            // Calculate min and max
            var maximum = maxVal;
            var minimum = maxVal * -1;

            // Set the extremes of the yAxis
            yAxes[axis].setExtremes(minimum, maximum, false);
        }

        // If the absolute minval is greater than the max value
        else{

            // Calculate the min and max
            var maximum = minVal * -1;
            var minimum = minVal;

            // Set the extremes of the yAxis
            yAxes[axis].setExtremes(minimum, maximum, false);
        }
    }

    // If there are no negative values present at all, we can set the range from 0 to maxVal
    else{
        yAxes[axis].setExtremes(0, maxVal, false);
    }

}

chart.xAxis[0].isDirty = true;
chart.redraw();

Edit: solved the problem by overriding the default behaviour when zooming in. I used the min and max values of the selection event to set the extremes of the x-axis. After that I aligned the zero values of the y-axes with an edited version of the code that's called after resetting the zoom. Fiddle: http://jsfiddle.net/5m9JW/355/
Hopefully this can also help people out that run into the same problem.

A: Unfortunately Highcharts doesn't provide options to align yAxis together in the same value (like 0-value for your case). I have a while ago prepared example to make the same position for two axis: http://jsfiddle.net/5m9JW/349/ You probably should be able to upgrade to get the same for more axis
while (chart.yAxis[1].translate(0) != chart.yAxis[0].translate(0) && i > 0) {
    chart.yAxis[0].setExtremes(chart.yAxis[0].getExtremes().min - chart.yAxis[0].translate(chart.yAxis[1].translate(0), true));
    i--;
};

Also, I think toPixels() and toValue() would be easier to use than translate().

A: Solved the problem by overriding the default behaviour when zooming in. I used the min and max values of the selection event to set the extremes of the x-axis. After that I aligned the zero values of the y-axes with an edited version of the code that's called after resetting the zoom. Fiddle: http://jsfiddle.net/5m9JW/355/ This example works for multiple axes
See JS fiddle for my solution

Hopefully this can also help people out that run into the same problem.


text:
Q: Multi-Type search in elasticsearch with distinct ID's after ordering I have elastic index with types for different languages.
I need to select distinct documents with current language if available and any single other if current language is not available.
I can do something like this in PostgreSQL (although there's probably a better way to do this):
SELECT DISTINCT ON (i) * FROM
(SELECT * FROM
(SELECT id i, name n, locale l, f_active a FROM news c
UNION ALL
SELECT id i, name n, locale l, (SELECT cc.f_active FROM news cc WHERE cc.id = cl.id) a FROM news_locale cl
) s
ORDER BY l = 'en' DESC
) ss
WHERE a = true

I wonder, if it's possible to do so in elasticsearch?
P.S. I could've stored all localed fields in one document, but the problem is that most of the time I need to select only one particular locale.

A: I've managed to achieve something like this:
{
        "query": {
            "query_string": {
                "query": "(isActive:true) AND (isDeleted:false)"
            }
        },
        "aggs": {
            "top_ids": {
                "terms": {
                    "field": "id",
                    "order": {
                        "title": "desc"
                    },
                    "size": 10
                },
                "aggs": {
                    "top_ids_hits": {
                        "top_hits": {
                            "sort": {
                                "_script": {
                                    "type": "number",
                                    "script": {
                                        "inline": "doc['locale'].value == lang ? 1 : 0",
                                        "params": {
                                            "lang": "ru"
                                        }
                                    },
                                    "order": "desc"
                                },
                                "_score": {
                                    "order": "desc"
                                }
                            },
                            "size": 1
                        }
                    },
                    "title": {
                        "max": {
                            "field": "num_field"
                        }
                    }
                }
            }
        },
        "size": 0
    }

But there are two problems: I cannot set from for top_ids terms and cannot sort by non-numeric fields.
I guess for now there's no solution for these problems.


text:
Q: trying to print and addition plus variable readen before but the pinting only shows the basic addition variable In the code part you see there is a variable named "Sumar" which is a basic addition and it's meant to make the addition plus the value given to N in the reading method
import javax.swing.JOptionPane;

public class Suma {

    static int n = 0;

    public static void leerN()
    {
        JOptionPane.showInputDialog("Ingrese el valor de 'n'");
    }
    public static void resSum(){
        int sumar = 1+2+3+4+5+(n);

        JOptionPane.showMessageDialog(null, "el valor de la suma es igual a:\n"+sumar);
        }
}

[Reading]The reading method reads the number 52
[Result]But the result shows 5 which comes being the result of the addition withouth the value of N, I've tried changing many things and sitll don't get it to add the value of n when showing the result3

A: use a loop,
you could use the Scanner by importing the Scanner class at the beginning of the program:
import java.util.Scanner;
public static void resSum()
{
    Scanner scan = new Scanner(System.in); // creating a Scanner obj for getting input
    int input = scan.nextInt(); // getting input from user
    n = input;
    int sumar = 0;
    for(int i = 1 ; i <= n ; i++)
    {
        sumer += i;
    }
    System.out.print("el valor de la suma es igual a:\n"+sumar); // using the print method to print to console.
}

see more about loops in here: Help with understanding java 'for' loops


text:
Q: Data Transfer to power Bi via pythonscript I'm gonna connect to Cockroachdb direct and pickup data in power Bi with python script.
(There are not CocroachDB as a Dataresource in Power Bi)
what is the easiest und faster way to do that?
could you please guide me? I'm not profi in python
I have tried to connect DB with
psycopg2 and SQLALchere  but I think I did not do correctly.

A: Microsoft has a guide on how to use Python scripts to import data:
https://learn.microsoft.com/en-us/power-bi/connect-data/desktop-python-scripts
This shouldn't be a problem in Power BI Desktop, but there are some restrictions wrt the available Python packages in the Power BI Service.


text:
Q: SimpleModal - closing iframe with close button So I've searched around and I couldn't find a definitive answer.  I want my iframe to have a close button so that users can click it instead of going with the ESC key to close the SimpleModal container.
I've tried several things, but it doesn't seem like anything is being passed into the iframe to be able to close the container.

A: Try the following:
parent.$.modal.close();

source

A: try this:
$(document).keyup(function (e) {
        if (e.keyCode == 27) {
            return;
        }
    });

A: I've had the same problem. It occured when my iFrame's "src" attribute used https as protocol. In that case parent.$.modal.close(); wouldn't work.
What I did to fix it was add the usual close button that Eric talks about on the SimpleModal project page.
Add the closeHTML line to your modal script:
closeHTML:"",

This will add the close button on the outside of the modal, not inside the iFrame.
You'll then need to style the close button, using this CSS on your page:

You can find the image here:
SimpleModal Demo's x.png
Here's a full script for you:

I hope this helps!
Cheers
Paul

A: I solve this in a simple way, but I used a link  instead of a button, but is the same.
Just simple put this: class="simplemodal-close"
For example,
if you want a button to close: <input type="submit" class="simplemodal-close" value="Close" />
Try it, no functions, no onclick="", no nothing. It Works
Assuming you are using the Simplemodal of: http://www.ericmmartin.com/projects/simplemodal_v101/
Good Luck!


text:
Q: Unstable results using LSTM for High Frequency stock forecasting I have several datasets containing High Frequency data (Limit Order Books) from Nasdaq.
For whoever is interested in this kind of data, I strongly suggest checking out https://github.com/martinobdl/ITCH for a Book Constructor and some sample data (more than you gonna get anywhere else, anyway)
I would like to use an LSTM network to try and predict both the next bid and next ask price, using some other features as well, such as volumes and volumes imbalances from the order book.
This is how the first five columns of my train data look like (data from AAPL, 1s between datapoints):
Bid     Ask        1_bid_vol  1_ask_vol  2_bid_vol  2_ask_vol
162.49  162.52     300.0      200.0      500.0      200.0
162.48  162.51     300.0      600.0      800.0      500.0
162.49  162.51     100.0      10.0       1000.0     500.0
162.48  162.52     469.0      600.0      618.0      500.0

As well as normalizing data, I create fixed-lenght sequences, as it's appropriate for LSTMs, as follows:
def slicing(df,history_size):
data = []
labels = []
tmp_df=np.array(df)
start_index = history_size
for i in range(start_index, len(df)):
    indices = range(i-history_size, i)
    data.append(tmp_df[indices,:])
    labels.append(tmp_df[i,:2])

return np.array(data), np.array(labels)

So that input data have shape = (n_samples, history_size, n_features)
My current architecture is as follows:
callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=5)
LSTM = tf.keras.models.Sequential([
  tf.keras.layers.LSTM(128,input_shape=
      (X_train.shape[1],X_train.shape[2]),activation='relu',return_sequences=True),
  tf.keras.layers.LSTM(62,input_shape=(X_train.shape[1],X_train.shape[2]),activation='relu'),
  tf.keras.layers.Dropout(0.2),
  tf.keras.layers.Dense(2)
   ])
 opt = tf.keras.optimizers.Adam(learning_rate=0.001)
 LSTM.compile(optimizer=opt, loss='mse')
 LSTM.fit(x=X_train,y=y_train, epochs=50, validation_data=(X_val,y_val),callbacks=[callback])

These are the results I get on the validation set using 14k datapoints for training (I'll let y'all imagine what it's like on the test set):
Predictions on validation set
As you can see, the model starts off well on the validation set, than it basically starts predicting random outliers/spikes along the way.
Note that this result consistently appears even after changing hyperparameters, model architecture, and even changing data (e.g. using other stocks), and using smaller timewindows so that I can use way more data to train. Given this, I suspect it must be some kind of common problem, and any help/resource from someone who experienced it / is well versed in using RNN/LSTMs would be highly appreciated.

A: Here is a LSTM model to predict future stock prices, but it predicts the next day's stock price, not the next second's stock price. I made millions and millions of dollars using this strategy, and other very similar strategies, but it take a little time to make millions and I don't think you're going to do it in one second.
from pandas_datareader import data as wb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.preprocessing import MinMaxScaler

start = '2019-06-30'
end = '2020-06-30'

tickers = ['GOOG']

thelen = len(tickers)

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])

#names = np.reshape(price_data, (len(price_data), 1))

df = pd.concat(price_data)
df.reset_index(inplace=True)

for col in df.columns:
    print(col)

#used for setting the output figure size
rcParams['figure.figsize'] = 20,10
#to normalize the given input data
scaler = MinMaxScaler(feature_range=(0, 1))
#to read input data set (place the file name inside  ' ') as shown below

df['Adj Close'].plot()
plt.legend(loc=2)
plt.xlabel('Date')
plt.ylabel('Price')
plt.show()

ntrain = 80
df_train = df.head(int(len(df)*(ntrain/100)))
ntest = -80
df_test = df.tail(int(len(df)*(ntest/100)))

#importing the packages
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM

#dataframe creation
seriesdata = df.sort_index(ascending=True, axis=0)
new_seriesdata = pd.DataFrame(index=range(0,len(df)),columns=['Date','Adj Close'])
length_of_data=len(seriesdata)
for i in range(0,length_of_data):
    new_seriesdata['Date'][i] = seriesdata['Date'][i]
    new_seriesdata['Adj Close'][i] = seriesdata['Adj Close'][i]
#setting the index again
new_seriesdata.index = new_seriesdata.Date
new_seriesdata.drop('Date', axis=1, inplace=True)
#creating train and test sets this comprises the entire data's present in the dataset
myseriesdataset = new_seriesdata.values
totrain = myseriesdataset[0:255,:]
tovalid = myseriesdataset[255:,:]
#converting dataset into x_train and y_train
scalerdata = MinMaxScaler(feature_range=(0, 1))
scale_data = scalerdata.fit_transform(myseriesdataset)
x_totrain, y_totrain = [], []
length_of_totrain=len(totrain)
for i in range(60,length_of_totrain):
    x_totrain.append(scale_data[i-60:i,0])
    y_totrain.append(scale_data[i,0])
x_totrain, y_totrain = np.array(x_totrain), np.array(y_totrain)
x_totrain = np.reshape(x_totrain, (x_totrain.shape[0],x_totrain.shape[1],1))

In [85]:

#LSTM neural network
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_totrain.shape[1],1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adadelta')
lstm_model.fit(x_totrain, y_totrain, epochs=10, batch_size=1, verbose=2)
#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values
myinputs = myinputs.reshape(-1,1)
myinputs  = scalerdata.transform(myinputs)
tostore_test_result = []
for i in range(60,myinputs.shape[0]):
    tostore_test_result.append(myinputs[i-60:i,0])
tostore_test_result = np.array(tostore_test_result)
tostore_test_result = np.reshape(tostore_test_result,(tostore_test_result.shape[0],tostore_test_result.shape[1],1))
myclosing_priceresult = lstm_model.predict(tostore_test_result)
myclosing_priceresult = scalerdata.inverse_transform(myclosing_priceresult)

totrain = df_train
tovalid = df_test

#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values

#  Printing the next day's predicted stock price.
print(len(tostore_test_result));
print(myclosing_priceresult);

Result:
[[1396.532]]

You can find a few other samples of predicting future stock prices at my blog, below.
https://github.com/ASH-WICUS/Notebooks


text:
Q: Scala Data Modeling and Generics I'm using the Play Framework and Squeryl to make a fairly basic front end for a database, but I know I'm rewriting too much code. I have different models to represent data in my db, and they all do the same six functions
object ModelType{
    def add(model:ModelType):Option[ModelType] = Option(AppDB.tablename.insert(model))
    def remove(id: Long) = AppDB.tablename.delete(id)
    def getAll():List[ModelType] = from(AppDB.tablename)(model => select(model) orderBy(model.aDifferentFieldForEachModel)) toList
    def toJson(model:ModelType):JsValue ={
      Json.toJson(
      Map("field" -> Json.toJson(model.field))
      )
    }
    def allToJson() = {
      val json:List[JsValue] = getAll.map{toJson(_)}
      Json.toJson(json.toSeq)
    }
    def validate(different values for each model) = // is fairly different for each one. Validates the submitted fields from a user
}

So I'm using case classes for each of the models, and using an accompanying object for these commands. How can I use generics or traits in scala to make my life easier and not type all of these methods out every time?
EDIT: Mostly solved with gzm0's answer, but the problem is now how would I implement getAll in the trait? I want to be able to save some variable for each model that resembles the model.aDifferentFieldForEachModel as above.

A: You could try the following:
trait ModelOps[T] {
  def table: AppDB.Table // not sure about type
  def order: AppDB.OrderByPredicate // not sure about type
  def toJson(model: T): JsValue

  def add(model: T): Option[T] = Option(AppDB.categories.insert(model))
  def remove(id: Long) = AppDB.categories.delete(id)
  def getAll(): List[T] = from(table)(model => select(model) orderBy(order)) toList
  def allToJson() = {
    val json:List[JsValue] = getAll.map{toJson(_)}
    Json.toJson(json.toSeq)
  }

}

Then you can for each model type:
object ModelType extends ModelOps[ModelType] {
  def table = AppDB.examples
  def order = yourPredicate
  def toJson(model:ModelType):JsValue = {
    Json.toJson(Map("field" -> Json.toJson(model.field)))
  }
  def validate(different values for each model) = // is fairly different for each one. Validates the submitted fields from a user
}

UPDATE About the true type of AppDB.OrderByPredicate:
Calling select on PrimitiveTypeMode returns a SelectState. On this SelectState, you will call orderBy which takes a List[BaseQueryYield#O] (or multiple of those in the same argument list). Hence you should define:
def order(model: T): List[BaseQueryYield#O]

and
def getAll() = from(table)(model => select(model) orderBy(order(model))) toList

By the way, BaseQueryYield#O resolves to ExpressionNode.


text:
Q: rails toggle problem - ActionView::TemplateError (undefined method `[]' for #After this rails app has been running fine for over two years... just started getting this one error on only one page.
ActionView::TemplateError (undefined method `[]' for #<Enumerable::Enumerator:0xb25fbc4>) on line #10 of app/views/notes/_form.rhtml:
7:  <%= @n.text_field 'note', :size => 55  %>
8: </label>
9: <%= link_to_function('Custom Note', nil, :id => "custom_link", :class => 'control') do |page|
10:   page[:custom].toggle(:appear)
11:   page[:presets].toggle
12:   page[:custom_link].replace_html "Preset/Custom"
13: end %>

When I comment out lines 10 and 11, the lines with toggle, the page loads. But obviously doesn't do what I need.
Any suggestions on how to fix this?


text:
Q: mean-field variational inference in Nonconjugate Models I'm trying to conduct mean-field Variational Inference (VI) with Nonconjugate model.
I found Variational Inference in Nonconjugate Models.
But I want to check if there are any other additional methods for approaches!
I really appreciate any help you can provide.


text:
Q: Could not autowire hibernate 5 sessionfactory with spring 5 I'm trying to autowire hibernate 5 session factory bean with spring 5 in my DAO class. Maybe someone can see my mistakes here? Tried using Hibernate 4, EntityManagerFactory but every time it's hopeless.
Configuration class:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate5.HibernateTransactionManager;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.support.StandardServletMultipartResolver;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.*;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.templateresolver.SpringResourceTemplateResolver;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;

import javax.annotation.Resource;
import javax.sql.DataSource;
import java.util.Properties;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"webApp"})
@EnableTransactionManagement
@PropertySource("classpath:props.dbProps.properties")
public class WebConfig implements WebMvcConfigurer {

private static final String DRIVER = "driver";
private static final String URL = "url";
private static final String USER_NAME = "name";
private static final String PASSWORD = "pass";
private static final String SCAN = "packages";
private static final String DIALECT = "dialect";
private static final String SHOW_SQL = "showSql";
private static final String HBM2DLL = "hbm2dll";

@Resource
private Environment env;

@Bean
public ViewResolver viewResolver(SpringTemplateEngine engine){
    ThymeleafViewResolver resolver = new ThymeleafViewResolver();
    resolver.setTemplateEngine(engine);
    return resolver;
}

@Bean
public SpringTemplateEngine templateEngine(SpringResourceTemplateResolver templateResolver){
    SpringTemplateEngine engine = new SpringTemplateEngine();
    engine.setTemplateResolver(templateResolver);
    return engine;
}

@Bean
public SpringResourceTemplateResolver templateResolver(){
    SpringResourceTemplateResolver resolver = new SpringResourceTemplateResolver();
    resolver.setPrefix("classpath:/templates/");
    resolver.setSuffix(".html");
    resolver.setTemplateMode(TemplateMode.HTML);
    return resolver;
}

@Bean
public MultipartResolver multipartResolver(){
    return new StandardServletMultipartResolver();
}

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty(DRIVER));
    dataSource.setUrl(env.getRequiredProperty(URL));
    dataSource.setUsername(env.getRequiredProperty(USER_NAME));
    dataSource.setPassword(env.getRequiredProperty(PASSWORD));
    return dataSource;
}

@Bean
public LocalSessionFactoryBean getSessionFactory(){
    final LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(dataSource());
    lsfb.setPackagesToScan(env.getRequiredProperty(SCAN));
    lsfb.setHibernateProperties(hibProps());
    return lsfb;
}

@Bean
public PlatformTransactionManager transactionManager(){
    HibernateTransactionManager tx = new HibernateTransactionManager();
    tx.setSessionFactory(getSessionFactory().getObject());
    return tx;
}

private Properties hibProps(){
    Properties p = new Properties();
    p.put(DIALECT, env.getRequiredProperty(DIALECT));
    p.put(SHOW_SQL, env.getRequiredProperty(SHOW_SQL));
    p.put(HBM2DLL, env.getRequiredProperty(HBM2DLL));
    return p;
}

@Override
public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if(!registry.hasMappingForPattern("/static/**")){
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");
    }
}
}

Tried to autowire through constructor and setter - nothing helps.
DAO Class:
package webApp.data;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import webApp.model.Human;

import java.util.List;

@org.springframework.stereotype.Repository
public class HumanRepositoryImpl implements Repository<Human> {

    @Autowired
    private SessionFactory sessionFactory;

    private Session getSession() {
        return sessionFactory.getCurrentSession();
    }

    @Override
    public Human get(long id) {
        Human result = (Human)getSession().get(Human.class, id);
        return result;
    }

    @Override
    public Human getByName(String name) {
        Human result = (Human) getSession().createQuery("from human where name = '" + name + "'");
        return result;
    }

    @Override
    public void set(Human value) {
        getSession().save(value);
    }

    @Override
    public void update(Human value) {
        Human forUpdate = get(value.getId());
        forUpdate.setFirstName(value.getFirstName());
        forUpdate.setLastName(value.getLastName());
        forUpdate.setUsername(value.getUsername());
        forUpdate.setEmail(value.getEmail());
        forUpdate.setPassword(value.getPassword());
        getSession().update(forUpdate);
    }

    @Override
    public void delete(Human value) {
        Human forDelete = get(value.getId());
        if(forDelete != null)
            getSession().delete(forDelete);
    }

    @Override
    @SuppressWarnings("unchecked")
    public List<Human> list() {
        return getSession().createQuery("from human").list();
    }
}

Dependencies: Spring 5.0.2.Release, Hibernate 5.2.12.Final
Exception Stack Trace:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'humanRepositoryImpl': Unsatisfied dependency expressed through field 'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:586)
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:91)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:372)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1344)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:582)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:758)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
    at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:409)
    at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:291)
    at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:103)
    at org.eclipse.jetty.server.handler.ContextHandler.callContextInitialized(ContextHandler.java:890)
    at org.eclipse.jetty.servlet.ServletContextHandler.callContextInitialized(ServletContextHandler.java:532)
    at org.eclipse.jetty.server.handler.ContextHandler.startContext(ContextHandler.java:853)
    at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:344)
    at org.eclipse.jetty.webapp.WebAppContext.startWebapp(WebAppContext.java:1514)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.startWebapp(JettyWebAppContext.java:359)
    at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1476)
    at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:785)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStart(ServletContextHandler.java:261)
    at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:545)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStart(JettyWebAppContext.java:434)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:113)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.handler.ContextHandlerCollection.doStart(ContextHandlerCollection.java:167)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:113)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.start(ContainerLifeCycle.java:131)
    at org.eclipse.jetty.server.Server.start(Server.java:449)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStart(ContainerLifeCycle.java:105)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStart(AbstractHandler.java:113)
    at org.eclipse.jetty.server.Server.doStart(Server.java:416)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:68)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.startJetty(AbstractJettyMojo.java:467)
    at org.eclipse.jetty.maven.plugin.AbstractJettyMojo.execute(AbstractJettyMojo.java:333)
    at org.eclipse.jetty.maven.plugin.JettyRunMojo.execute(JettyRunMojo.java:180)
    at org.apache.maven.plugin.DefaultBuildPluginManager.executeMojo(DefaultBuildPluginManager.java:134)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:207)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:153)
    at org.apache.maven.lifecycle.internal.MojoExecutor.execute(MojoExecutor.java:145)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:116)
    at org.apache.maven.lifecycle.internal.LifecycleModuleBuilder.buildProject(LifecycleModuleBuilder.java:80)
    at org.apache.maven.lifecycle.internal.builder.singlethreaded.SingleThreadedBuilder.build(SingleThreadedBuilder.java:51)
    at org.apache.maven.lifecycle.internal.LifecycleStarter.execute(LifecycleStarter.java:128)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:307)
    at org.apache.maven.DefaultMaven.doExecute(DefaultMaven.java:193)
    at org.apache.maven.DefaultMaven.execute(DefaultMaven.java:106)
    at org.apache.maven.cli.MavenCli.execute(MavenCli.java:863)
    at org.apache.maven.cli.MavenCli.doMain(MavenCli.java:288)
    at org.apache.maven.cli.MavenCli.main(MavenCli.java:199)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launchEnhanced(Launcher.java:289)
    at org.codehaus.plexus.classworlds.launcher.Launcher.launch(Launcher.java:229)
    at org.codehaus.plexus.classworlds.launcher.Launcher.mainWithExitCode(Launcher.java:415)
    at org.codehaus.plexus.classworlds.launcher.Launcher.main(Launcher.java:356)
    at org.codehaus.classworlds.Launcher.main(Launcher.java:47)
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.hibernate.SessionFactory' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1504)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1101)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1062)
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:583)
    ... 68 more

A: Do you add sessionfactory in database.xml file like this:
  <bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean" >
            <property name="dataSource" ref="dataSource"/>
            <property name="packagesToScan">
                <list>
                    <value>com.isgm.iis.model</value> <!-- replace with your package name -->
                </list>
            </property>
            <property name="hibernateProperties">
                <props>
                    <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                    <prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
                    <prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
                </props>
            </property>
        </bean>

A: I don't think its a good design to mix up @EnableWebMvc with @EnableTransactionManagement. You should clear a separate class for Hibernate configuration in same package of class WebConfig. Remove the below code.
@EnableTransactionManagement
@PropertySource("classpath:props.dbProps.properties")

@Bean
public DataSource dataSource(){
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName(env.getRequiredProperty(DRIVER));
    dataSource.setUrl(env.getRequiredProperty(URL));
    dataSource.setUsername(env.getRequiredProperty(USER_NAME));
    dataSource.setPassword(env.getRequiredProperty(PASSWORD));
    return dataSource;
}

@Bean
public LocalSessionFactoryBean getSessionFactory(){
    final LocalSessionFactoryBean lsfb = new LocalSessionFactoryBean();
    lsfb.setDataSource(dataSource());
    lsfb.setPackagesToScan(env.getRequiredProperty(SCAN));
    lsfb.setHibernateProperties(hibProps());
    return lsfb;
}

@Bean
public PlatformTransactionManager transactionManager(){
    HibernateTransactionManager tx = new HibernateTransactionManager();
    tx.setSessionFactory(getSessionFactory().getObject());
    return tx;
}

private Properties hibProps(){
    Properties p = new Properties();
    p.put(DIALECT, env.getRequiredProperty(DIALECT));
    p.put(SHOW_SQL, env.getRequiredProperty(SHOW_SQL));
    p.put(HBM2DLL, env.getRequiredProperty(HBM2DLL));
    return p;
}

Clear a separate class like below. I have written code for Hibernate xml config,  you could also config properties file. Also, you haven't mentioned any class in setAnnotatedClasses method of  LocalSessionFactoryBean, add those. This configuration is recommended for Spring 5 with Hibernate 5.
@Configuration
@EnableTransactionManagement
public class HibernateConfig {

    @Autowired
    private ApplicationContext context;

    @Bean
    public LocalSessionFactoryBean getSessionFactory() {
        LocalSessionFactoryBean factoryBean = new LocalSessionFactoryBean();
        factoryBean.setConfigLocation(context.getResource("classpath:hibernate.cfg.xml"));
        factoryBean.setAnnotatedClasses(User.class);
        return factoryBean;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(getSessionFactory().getObject());
        return transactionManager;
    }
}


text:
Q: How to access a function in the list? Assume i have a list as below:
mylist<-list( c(12,3,12,5),"Hello R",sin  )

so, the third element of my mylist is a sin(x) function:
mylist[3]
[[1]]
function (x)  .Primitive("sin")

what if i want to pass an element to it?
For instance i want to get sin(90)
I have tried the mylist[3](90):
mylist[3](90)
Error: attempt to apply non-function

A: You are very very close. Notice that when you type mylist[3], next to your desired output, you also get [[1]]. This means that this is a list with element 1. You can see this if you do
> str(mylist[3])
List of 1
 $ :function (x)

To subset the very element of the list (and not just the third list element), you should use double bracket.
> mylist[[3]](90)
[1] 0.8939967

Here is a nice representation of how to work with lists in R.
Alternatively, you could name your elements and access them that way.
> mylist <- list(a = c(12,3,12,5), b = "Hello R", allmysins = sin)
> mylist$allmysins(90)
[1] 0.8939967


text:
Q: IOS - CredStore - performQuery - Error copying matching creds I am getting the erro below when i try to call the custom API that i have, i am using alamofire
let API_URL = "https://localhost:5001/api"

func registerNewUser(parameters: Parameters) {

        let urlString = API_URL + "/register/PostTest"
        let url = URL.init(string: urlString)

        print("URL: \(url!)")

        Alamofire.request(url!, method: .post, parameters: parameters, encoding: JSONEncoding.default, headers: nil).debugLog().responseJSON{ //--> point of failure
            response in
            if response.result.isSuccess {
                print("Success! the request to the API is successful")

                let userJson : JSON = JSON(response.result.value!)

                print(userJson)

            } else {
                print("Error \(response.result.error!)")
            }
        }
    }

info.plist file
<key>NSAppTransportSecurity</key>
        <dict>
            <key>NSExceptionDomains</key>
            <dict>
                <key>https://localhost</key>
                <dict>
                    <!--Include to allow subdomains-->
                    <key>NSIncludesSubdomains</key>
                    <true/>
                    <!--Include to allow HTTP requests-->
                    <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
                    <true/>
                    <!--Include to specify minimum TLS version-->
                    <key>NSTemporaryExceptionMinimumTLSVersion</key>
                    <string>TLSv1.1</string>
                </dict>
            </dict>
        </dict>

The Error is:

CredStore - performQuery - Error copying matching creds.  Error=-25300, query={
      class = inet;
      "m_Limit" = "m_LimitAll";
      ptcl = htps;
      "r_Attributes" = 1;
      sdmn = localhost;
      srvr = localhost;
      sync = syna;
  }


text:
Q: Sniff and send UDP traffic using Scapy I followed the tutorial below to implement a packet sniffer in Python:
http://www.binarytides.com/python-packet-sniffer-code-linux/
On receiving each UDP packet, I would like to send an already saved pcap file (test.pcap). The following snippet shows my implementation:
# receive a packet
while True:
  packet = s.recvfrom(65565)

  #packet string from tuple
  packet = packet[0]

  #parse ethernet header
  eth_length = 14

  eth_header = packet[:eth_length]
  eth = unpack('!6s6sH' , eth_header)
  eth_protocol = socket.ntohs(eth[2])
  print 'Destination MAC : ' + eth_addr(packet[0:6]) + ' Source MAC : ' +
    eth_addr(packet[6:12]) + ' Protocol : ' + str(eth_protocol)

  if eth_addr(packet[6:12]) != my_MAC_address:

      #Parse IP packets, IP Protocol number = 8
      if eth_protocol == 8 :
      #Parse IP header
      #take first 20 characters for the ip header
      ip_header = packet[eth_length:20+eth_length]

      #now unpack them :)
      iph = unpack('!BBHHHBBH4s4s' , ip_header)

      version_ihl = iph[0]
      version = version_ihl >> 4
      ihl = version_ihl & 0xF

      iph_length = ihl * 4

      ttl = iph[5]
      protocol = iph[6]
      s_addr = socket.inet_ntoa(iph[8]);
      d_addr = socket.inet_ntoa(iph[9]);

      print 'Version : ' + str(version) + ' IP Header Length : ' + str(ihl) + ' TTL : ' + str(ttl) + ' Protocol : ' + str(protocol) + ' Source Address : ' + str(s_addr) + ' Destination Address : ' + str(d_addr)

      #UDP packets
      if protocol == 17 :
         u = iph_length + eth_length
         udph_length = 8
         udp_header = packet[u:u+8]

         #now unpack them :)
         udph = unpack('!HHHH' , udp_header)

         source_port = udph[0]
         dest_port = udph[1]
         length = udph[2]
         checksum = udph[3]

         print 'Source Port : ' + str(source_port) + ' Dest Port : ' + str(dest_port) + ' Length : ' + str(length) + ' Checksum : ' + str(checksum)

         h_size = eth_length + iph_length + udph_length
         data_size = len(packet) - h_size

         #get data from the packet
         data = packet[h_size:]

         print 'Data : ' + data
         my_pkt = rdpcap("test.pcap")
         sendp(my_pkt)

Test.pcap contains a UDP packet with UDP_src=7777 and UDP_dest=9999.
Traffic is generated using netcat as follows:
nc -u -p 7777 ip_dst_addr 9999

The sniffer can receive only first netcat msg and send test.pcap in response. But subsequent netcat msgs are not received at all. However, using any other combination of UDP ports in netcat, the sniffer works fine. For example: running netcat as:
nc -u -p 8888 ip_dst_addr 9999

there is no problem and I am able to send test.pcap in response to each UDP packet/msg.
Any help would be greatly appreciated!

A: Scapy has several built-in sniffers, that are really easy to use.

>>> help(sniff)
Help on function sniff in module scapy.arch.windows.compatibility:

sniff(count=0, store=1, offline=None, prn=None, stop_filter=None, lfilter=None, L2socket=None, timeout=None, *arg, **karg)
    Sniff packets
    sniff([count=0,] [prn=None,] [store=1,] [offline=None,] [lfilter=None,] + L2ListenSocket args) -> list of packets
    Select interface to sniff by setting conf.iface. Use show_interfaces() to see interface names.
      count: number of packets to capture. 0 means infinity
      store: whether to store sniffed packets or discard them
        prn: function to apply to each packet. If something is returned,
             it is displayed. Ex:
             ex: prn = lambda x: x.summary()
     filter: provide a BPF filter
    lfilter: python function applied to each packet to determine
             if further action may be done
             ex: lfilter = lambda x: x.haslayer(Padding)
    offline: pcap file to read packets from, instead of sniffing them
    timeout: stop sniffing after a given time (default: None)
    L2socket: use the provided L2socket
    stop_filter: python function applied to each packet to determine
                 if we have to stop the capture after this packet
                 ex: stop_filter = lambda x: x.haslayer(TCP)

Which means you could simply do:
packets = rdpcap("test.pcap")
sniff(lfilter=lambda x: x.haslayer(UDP) and x[Ether].src==sending_mac and x[UDP].sport==port, prn=lambda x: send(packets))

This will append all UDP packets to the test.pcap file


text:
Q: How to track down a Drupal max_allowed_packet error? One of my staging sites has recently started spewing huge errors on every admin page along the lines of:
User warning: Got a packet bigger than 'max_allowed_packet' bytes query: UPDATE cache_update SET data = ' ... ', created = 1298434692, expire = 1298438292, serialized = 1 WHERE cid = 'update_project_data' in _db_query() (line 141 of /var/www/vhosts/mysite/mypath/includes/database.mysqli.inc). (where "..." is about 1.5 million characters worth of serialized data)
How should I go about tracking down where the error originates? Would adding debugging code to _db_query do any good, since it gets called so much?

A: No need to track this down because you can't fix it I think.
This is the cache from update.module, containing information about which modules have updated versions and so on. So this is coming from one of the "_update_cache_set()" calls in that module.
Based on a wild guess, I'd say it is the one in this function: http://api.drupal.org/api/drupal/modules--update--update.fetch.inc/function/_update_refresh/6
It is basically building up an huge array with information about all projects on your site and tries to store it as a single, serialized value.
How many modules do you have installed on this site?
I can think of three ways to "fix" this error:

*

*Increase the max_allowed_packet size. (max_allowed_packet setting in my.conf)

*Disable update.module (It's not that useful on a staging/production site anyway, when you need to update on a dev site first anyway)

*Disable some modules ;)

A: I had a similar error and went round and round for about an hour.
Increased memory limit to 512m and still had the issue. And figured that was enough. So went looking elsewhere.
I cleared the caches with drush, still the error, and then looked at the database tables.
I noticed that all the cache tables were cleared except cache_update. I truncated this table and bam, everything was working normally.
Before I got the memory limit error, I got a max_input_vars error since I am on PHP5.4. But this question and answer led me to this fix. Not quite sure how or why it worked, but it did.


text:
Q: JQuery doesn't reload even if data is undefined I've got this function which checks if the login data is correct (username and password) with ajax.
If the php result is an error, then I print the error, but if the result is empty I would like to reload the page.
function(data) {
  if (data.length && data != null) {
    $("span.error").remove();
    $(".login-overlay .login h3").after('' + data + '');
  } else {
    location.reload();
  }
}

The issue is that when the php result (data) is empty, the code prints an empty span

I think the error is in the if clause, but I tried everything:
data.length
data.length > 0
data != undefined
data != null
data

Thanks for your help!

A: function(data) {
  if (data && data.trim()) {
    data = data.trim();
    $("span.error").remove();
    $(".login-overlay .login h3").after('' + data + '');
  } else {
    location.reload();
  }
}

You probably just want to check whether data is defined. So this should work. Otherwise please show what the data exactly. Which you could do by doing console.log(data) at the start of your function

A: I think that since your checking for both the data and the data.length the IF statement is not passed. your passing data from the server wither way, so probably there will always be data and the IF statement won't work. I would try the following code if indeed DATA is a string:
function(data) {
    if(data.length > 0){
    $("span.error").remove();
    $(".login-overlay .login h3").after(''+data+'');
} else {
    location.reload(); }
}


text:
Q: Is this Proof of Linearity of Integrals Correct? My professor was trying to prove the linearity of the integral. That is,
$\int hf(x)+kg(x) dx=h\int  f(x)dx + k \int  g(x) dx$, where $f,g$ are continuous functions, and $h,k\in \mathbb{R}$.
The following is the proof he wrote on the board:
Proof:
Let $\frac{d}{dx}(F(x))=f(x)$ and $\frac{d}{dx}(G(x))=g(x).$
Since differentiation is linear, we have
$\frac{d}{dx}(hF(x)+kG(x))=h\frac{d}{dx}(F(x))+k\frac{d}{dx}(G(x))=hf(x)+kg(x)=\int hf(x)+kg(x) dx=hF(x)+kG(x)=h\int f(x)dx+k\int g(x)dx=h(F(x)+C_1)+k(G(x)+C_2)=hF(x)+hC_1+kG(x)+kC_2=hF(x)+kG(x)+hC_1+kC_2=hF(x)+kG(x)+C$, where $C$ is the constant of integration. QED
I understand most of the proof, however there is one step that makes no sense to me.
It is the following step:
$hf(x)+kg(x)=\int hf(x)+kg(x) dx$
If anyone could explain how this makes sense, I would be grateful.
By the way, it seems like it doesn't make sense to me, as if I tried a concrete example:
If $f(x)=2x$ and $g(x)=3x$, and $h=2$ and $k=3$ then that step is saying that
$2(2x)+3(3x)=\int 2(2x)+3(3x)\implies 4x+9x=\int 4x+9x \implies 13x=\frac{13x^2}{2}$, which doesn't make sense, right?

A: I'm guessing it was meant to be something like:
$\frac{d}{dx}(hF(x)+kG(x))=h\frac{d}{dx}(F(x))+k\frac{d}{dx}(G(x))=hf(x)+kg(x)$
therefore, by integrating both sides it follows that
$\int hf(x)+kg(x) dx=hF(x)+kG(x) +c$
etc.


text:
Q: Выборка из четырёх таблиц Есть четыре таблицы. Пользователи, статус пользователя (админ, юзер и т.д), количество сообщений пользователя и количество иных логируемых действий. Нужно посчитать у скольки админов за последние 2 недели было хотя бы одно действие или сообщение. И с наименьшим временем выполнения (достаточно найти 1 действие / сообщение в указанный период, а не перебирать миллионы).
В этом бреде ошибка уже сразу в районе второго JOIN. Как можно выполнить подобную задачу?
SELECT COUNT(*)
  FROM user
   JOIN user_status
    ON user_id = status_user_id
    WHERE user_rights = "admin"
   JOIN user_logs
    ON user_id = log_user_id
    WHERE log_timestamp  >= CURDATE() - interval 14 day
   JOIN user_messages
    ON user_id = msg_user_id
    WHERE msg_timestamp >= CURDATE() - interval 14 day;


text:
Q: When did Earth stop selecting jobs for its inhabitants? In the pilot episode of Futurama, Fry doesn't want his pre-selected job, a delivery boy. Leela informs him that:

You're assigned the job you're best at.

There are severe punishments for not doing the job you were assigned:

Fry: But I don't wanna be a delivery boy!
Leela: You'll be fired.
Fry: Fine.
Leela: From a cannon. Into the sun. You've gotta do what you've gotta do. It's the law.

In the same episode, several characters repeat the same 'You've gotta do what you've gotta do. It's the law.' phrase.
In several episodes, characters quit their job but are re-hired in another industry, most notably:

*

*Leela- Real Estate Agent (previous job: ship's captain)

*Fry- Police Officer (previous job: delivery boy)

*Zapp Brannigan & Kif Kroker- delivery boys (previous jobs: captain & first officer, should be noted that they were dishonorably discharged from their previous jobs)

*Fry & Bender (and unofficially Leela)- soldiers (through trying to get military discount)

Scruffy also appeared to have been a shipman in the 'space navy', but I'm unsure where this quote is from so I'm unsure if this was from an episode:

Space-Navy taught me ever'thing I know 'bout janitorial work. Mm-hmm. Five hunnerd men in a tin can, one terlet per species... Them spaceships is more clog than ship. T'ain't nothin' I look back fondly on neither. 'Cept fer the hookers. Wasn't fer the hookers, I'd'a killed myself long before I made Admiral.

This plot point appears to have been dropped somewhere in the earlier seasons, without there being an actual episode involving its abandonment.
Is there any canonical record of Earth abandoning job selection?

A: Becoming a policeman or a Soldier/Naval officer appear to be careers that anyone can undertake. It's certainly possible that Delivery Ship Officer and Delivery Boy were actually Zapp and Kif's likely professions before they joined up. It wouldn't have been a case of them changing careers, but rather returning to their formerly assigned careers.
This would also take care of why Smitty (the policeman) was able to work in his father's restaurant, how Scruffy (the janitor) could be ex-Navy and why Bender and Fry were able to enlist in the DOOP military.
Other relevant stuff.

*

*Fry lost his hands in Season 3 (when attempting to feed a dinosaur). It's possible, if not downright likely that his career chip was also lost in the process.

*Leela was responsible for inserting the chips and remains on very good terms with her former boss. He may be providing the crew with fake chips on an ad-hoc basis or she may simply have the ability to reprogram them. If anyone would know how to fix a chip, it's her.


text:
Q: Reason for a JMS Session object to be used in a single threaded context I am a newbie to JMS. So this may be a really noob question for the experts out here in SO.
However I am having difficulty trying to grok one very important concept of how JMS has been laid out to work.
From the Javadoc of the JMS Session(bold emphasis mine)

A Session object is a single-threaded context for producing and
  consuming messages. Although it may allocate provider resources
  outside the Java virtual machine (JVM), it is considered a lightweight
  JMS object.

I thought that the main advantage of JMS is asynchronous delivery of messages. The term asynchronous automatically lends itself to the notion of multiple threads concurrently  producing and consuming messages. So I am confused with the concept of a single threaded context for the all important Session object. What am I missing here?

A: Its for the same reason that JTA is single threaded. There aren't any hard guarantees about how/when threads are scheduled to run. In addition, without synchronization there are no guarantees about when threads will complete their work. Given these constraints it is difficult to create transactional guarantees while maintaining the benefits of parallel processing.
For instance, if I spawn a transaction, then spawn a thread that sends messages on that transaction, but arbitrarily commit the transaction in the main thread, what should the transaction manager do(ignore the commit()? fail the send()?). What if If I have other transactional work(database commits) that haven't completed, but my message sending thread is done and has called commit()? What if a thread spins up and starts more work while the TransactionManager is trying to determine 2-Phase-Commit status of all the transaction participants?
Transaction API's are all based on well defined units of work. These API's are pretty clear cut when the unit of work runs in a single thread. Things become complicated otherwise and are covered by implementations not addressed by the Java EE spec.  These transaction managers allow nested transactions and/or transactions that span multiple threads. These implementations use very carefully designed synchronization, have limited use cases, and likely just ends up serializing the work anyway.
For most users, the primary benefit of JMS is similar to that of any message based actors system. Many discrete steps can pull messages of a queue, process them, advance to the next step by placing the result on another queue. If any step becomes a bottleneck you can just add more processing agents(MDBs, spring beans, etc.). Each agent does its processing on a single thread and you scale to multiple cores by creating more agents.

A: The Session class handles transactions. So while there is normally only one Connection, you can have multiple threads having their own session context, each with its individual transaction context.


text:
Q: Send email to multiple recipients using individual SMTP transactions with MailKit In my environment we send email programatically using MailKit via Office 365 SMTP. I have recently become aware of the fact that if I send an email with multiple recipients and one of those addresses no longer exists in our organization the O365 server will reject the entire email (not sending it to the remaining recipients) if a single recipient is invalid. The error generated is
5.4.1 Recipient address rejected: Access denied.

When I send emails I prefer to show all recipients on the email so that everyone knows who is involved and can reply to the group. All recipients are within my organization so they already have each others email addresses.
Based on the way SMTP works (with separate RCPT and headers) it seems that I should be able to send an email with everyone in the headers, but use individual transactions with the SMTP server so I can catch the exception generated for each address.
Is this possible to do with MailKit?

A: Look into the Send() and SendAsync() methods that take MailboxAddress arguments:
http://www.mimekit.net/docs/html/M_MailKit_MailTransport_Send_2.htm
This allows you to control who, exactly, to send the message to rather than having MailKit's SmtpClient decide who to send the message to by collecting addresses from the To, Cc and Bcc headers.