text:
Q: symfony - querybuilder in controller I am using the querybuilder in my controller to receive data and output as json:
    $qb = $this->getDoctrine()->getManager();

    $qb = $qb->createQueryBuilder();

    $qb->select('c')
        ->from('AppBundle:Customer\Customer', 'c');

    $data = $qb->getQuery()->getResult();

    $response = new JsonResponse();
    $response->setData(
        [
            'data' => $data
        ]
    );

    return $response;

My Entity is in namespace:
namespace AppBundle\Entity\Customer;

use Doctrine\ORM\Mapping as ORM;
use Doctrine\Common\Collections\ArrayCollection;
use Symfony\Component\Validator\Constraints as Assert;

/**
 * @ORM\Table(name="customer")
 * @ORM\Entity(repositoryClass="AppBundle\Entity\Customer\Repository")
 */
class Customer {

....

There are two records saved in table.
When I load the url it just print two empty array´s and no data.
Anybody could explain why?

A: Try this and then extract it......
$response = new JsonResponse();
$response->setData(array( 'data' => $data ));


text:
Q: Tomcat hangs if C3P0 can't get a database connection I've an application that uses Spring+Hibernate+C3P0 as the connection pool. If I start the application and the database is down, Tomcat hangs for a long log time withouth giving any feedback. Is there some property that I can set to avoid this? For example, if after 30 seconds it can't get a connection, throw a connection timeout exception.

A: By default, it should take about 30 seconds before c3p0 signals a failure if it cannot acquire a Connection. You can control the length of time by modifying either the number of attempts c3p0 makes at the database or the interval between attempts.
See c3p0.acquireRetryAttempts and c3p0.acquireRetryDelay.
If you set c3p0.acquireRetryAttempts to one, c3p0 won't retry and connection attempts will fail retry immediately.
See also Configuring Recovery From Database Outages.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I ease the syntactic overhead of checking iterator values in C++? Basically, I'm a bit tired of writing:
std::map<key_t, val_t> the_map;
...
auto iterator = the_map.find(...);
if(iterator != the_map.end()) { // note the "inversed" logic and logically superflous end() call
  ...
}

What really made sense would be:
if(auto x=the_map.find(...)) {
  ... // x could either be an iterator or maybe something like boost::optional<val_t>
}

Is there some prior art that defines some helper stuff to shorten the != container.end() syntax or am I the only one annoyed by this?

A: You could write a class template auto_iterator_impl and use it through a function template auto_iterator which returns an instance of auto_iterator_impl, which can be implicitly converted into true or false:
A working implementation with minimal functionalities and consideration:
template<typename C>
struct auto_iterator_impl
{
    C & c;
    typename C::iterator  it;
    auto_iterator_impl(C & c,  typename C::iterator & it) : c(c), it(it) {}
    operator bool() const { return it != c.end(); }
    typename C::iterator operator->() { return it; }
};

template<typename C>
auto_iterator_impl<C> auto_iterator(C & c, typename C::iterator  it)
{
    return auto_iterator_impl<C>(c, it);
}

Test code:
void test(std::map<int, int> & m, int key)
{
    if (auto x = auto_iterator(m, m.find(key)))
    {
        std::cout << "found = " << x->second << std::endl;
        x->second *= 100; //change it
    }
    else
        std::cout << "not found" << std::endl;
}

int main()
{
    std::map<int,int> m;
    m[1] = 10;
    m[2] = 20;
    test(m, 1);
    test(m, 3);
    test(m, 2);

    std::cout <<"print modified values.." <<std::endl;
    std::cout << m[1] << std::endl;
    std::cout << m[2] << std::endl;
}

Output:
found = 10
not found
found = 20
print modified values..
1000
2000

Online demo : http://www.ideone.com/MnISh

A: Well, if it means that much to you, how about a little wrapper:
template <typename Container>
inline bool find_element(Container const & c,
                         typename Container::const_iterator & it,
                         typename Container::value_type const & val)
{
  return (it = c.find(val)) == c.end();
}

Usage:
std::vector<int> v;
std::vector<int>::const_iterator it;

if (find_element(v, it, 12)) { /* use it */ }

A: I think it's the most flexible decision to write a wrapper like
template<class Iterable>
bool CheckIterator(const typename Iterable::iterator& iter, const Iterable& collection)
{
    return !(iter == collection.end());
}

and use it
    map<int,string> m;
    m[1]="hello";
    m[2]="world";
    map<int,string>::iterator it = m.find(2);
    if(CheckIterator(it,m))
    {
        cout<<it->second;
    }

it may be used with another types of containers (e.g. vector's) as well

A: How about this?
BOOST_FOREACH(auto &x : c.equal_range(...)) {
    // x is a val_t &, or const if c is const.
}

I'm assuming that if it's OK for x to be boost::optional<val_t>, then you don't actually need the iterator, just the value, so a reference is OK.
You can use a C++11 range-based for loop instead of BOOST_FOREACH if you use a boost::iterator_range instead of a std::pair (which is what equal_range returns).

A: You could implement a wrapper function to do the != map.end() check for you, or you could use the preprocessor to do it using a macro like this:
#define map_find_if(iterator, container, func) \
    auto (iterator) = (func); \
    if ((iterator) != (container).end())

Use it like this:
map_find_if(iter, map, map.find(key)) {
   // found the key
}
// else clause could go here

Using a function is probably a cleaner implementation though, and more in the "C++ way".

A: If you're willing to lump your code into an anonymous function (looks like you are using auto already, so assuming c++11)?
#include <iostream>
#include <map>

template <typename Container, typename ExecF>
void exec_if(Container const& cont, typename Container::const_iterator it, ExecF f)
{
  if (it != cont.end())
    f();
}

int main(void)
{
  std::map<int, int> bar;
  bar.insert(std::make_pair(1, 1));
  bar.insert(std::make_pair(2, 2));
  bar.insert(std::make_pair(3, 3));

  auto it = bar.find(2);
  exec_if(bar, it, [&it]()
    {
      std::cout << it->first << ' ' << it->second << std::endl;
    });

}

EDIT: now I think it's a lot more cleaner


text:
Q: Q# Program does not contain a static 'Main' method suitable for an entry point I'm creating a program in Q#.

Problem

You are given two qubits in state |00⟩. Your task is to create the following state on them:
1/3–√(|00⟩+|01⟩+|10⟩)
You have to implement an operation which takes an array of 2 qubits as an input and has no output. The "output" of your solution is the state in which it left the input qubits.

Code

namespace Solution {
    open Microsoft.Quantum.Primitive;
    open Microsoft.Quantum.Canon;
    open Microsoft.Quantum.Math;
    open Microsoft.Quantum.Convert;

    operation Solve (qs : Qubit[]) : Unit
    {
        body
        {
            Ry(ArcCos(Sqrt(2.0/3.0))*2.0,qs[0]);
            (ControlledOnInt(0,H))([qs[0]],qs[1]);
        }
    }
}

But when I run it show me the following error.

Error

CSC : error CS5001: Program does not contain a static 'Main' method suitable for an entry point

[C:\Users\Pawar\Desktop\HK\codeforces\Q#\Solution\Solution.csproj]

So I tried to put EntryPoint() before the method declaration . Which shows me different error as

error QS6231: Invalid entry point. Values of type Qubit may not be used as arguments or return values to entry points. [C:\Users\Pawar\Desktop\HK\codeforces\Q#\Solution\Solution.csproj]

Please help me how to run it properly ?
thanks ✌

A: In order to run a Q# program as an executable, you need to have an @EntryPoint() operation defined. You can read more in this excellent blog post: https://qsharp.community/blog/qsharp-entrypoint/.
Specifically, in your case, the error message indicates that Qubit[] is not a valid parameter to the main entry point of your program. Which makes sense, because it doesn't make sense to pass an array of qubits when executing a program from the command line. And also, your operation doesn't print anything or return any results, so you won't be able to see what it's doing.
You should probably create an @EntryPoint() wrapper operation that invokes your existing operation with the appropriate parameters, maybe prints some diagnostics, and then returns some result. In your case, you could perhaps do something like this (note the additional namespaces you need to open):
    open Microsoft.Quantum.Diagnostics;
    open Microsoft.Quantum.Measurement;

    @EntryPoint()
    operation SolveForTwoQubits() : Result[]
    {
        using (qubits = Qubit[2])
        {
            Solve(qubits);                 // invoke your existing Solve operation
            DumpMachine();                 // outputs the state of your qubits
            let results = MultiM(qubits);  // measure the qubits
            ResetAll(qubits);              // reset the qubits to the initial state
            return results;                // return the measured results
        }
    }

This will give some output that looks like:
# wave function for qubits with ids (least to most significant): 0;1
∣0❭:     0.577350 +  0.000000 i  ==     *******              [ 0.333333 ]     --- [  0.00000 rad ]
∣1❭:     0.577350 +  0.000000 i  ==     *******              [ 0.333333 ]     --- [  0.00000 rad ]
∣2❭:     0.577350 +  0.000000 i  ==     *******              [ 0.333333 ]     --- [  0.00000 rad ]
∣3❭:     0.000000 +  0.000000 i  ==                          [ 0.000000 ]
[Zero,One]


text:
Q: xsel < /tmp/xselection not working in script I'm trying to use the following script:
#!/usr/bin/env bash
# Edit xselection in gvim
xsel > /tmp/xselection
gvim /tmp/xselection
xsel < /tmp/xselection

But the final line does not seem to be correctly loading the file into xselection. If I run that line immediately after calling the script it succeeds. I can't understand why. What am I missing?

A: You're missing the fact that the call to gvim does not block until you exit gvim, it returns immediately.  So the xsel < /tmp/xselection is processing the file before you edit it.

A: I ended up incorporating information from both/all three answers to generate the following:
#!/usr/bin/env bash
# Edit xselection in gvim

xsel > /tmp/xselection
gvim -f /tmp/xselection
xsel -i < /tmp/xselection

A: You need to use the -i option. (-o is the default)
xsel -i </tmp/xselection
# -o, --output   write the selection to standard output.
# -i, --input   read standard input into the selection.*

These optons work on the X primary selection (not the clipboard), so you need to center-click to see the resullt.  I've tested it with a pause before the final command. This allowed me to manually select some other text before the final command executed. The I center-clicked and it worked fine... and it works without the delay.
However testing it without the delay doesn't prove much, becaust the original selection is still selected... and, of course, if you select something else in the meantime, you will lose the script's primary selection.
Perhaps your issue is a combination of both the -i option, and Paul Tomblin's answer about the way gvim detaches from the script process.

A: My previous answer was getting a bit crowded and was incomplete (and had only one edit-itteration left). So here is an amended answer which includes both ideas... options and detaching.
As I've mentioned in a follow-up commen to Giles comment (previous answer), the -i option is definitely needed in some situations (on the test Ubuntu system).. so -i and -o are used here.
Because 'gvim' detaches from the script's process, it doesn't wait, and the next command is executed immediately. (Paul Tomblin has already pointed thos out in hes answer).
You can't use bash's wait command, as it only works for child processes. As workaround, you can set up a loop which waits for the non-child process to terminate. This works for an editor which starts with a new process each time (as 'gvim' does in this case).
Here is the modified script
xsel -o >/tmp/xselection

gvim /tmp/xselection 2>/dev/null
pid=$(pgrep -n "gvim")  # get gvim's pid and wait
while kill -0 "$pid" 2>/dev/null; do sleep 0.5; done

xsel -i </tmp/xselection

The above assumes that gvim` pid is already established by the time control is passed back to the script. If, under a high system load, the pid hasn't been established upon executing the next command, then this method of waiting for gvim should work.
xsel -o >/tmp/xselection

pre=$(pgrep -n gvim)    # get previous gvim pid
gvim /tmp/xselection 2>/dev/null
while pid=$(pgrep -n "gvim"); [[ "$pid" == "$pre" ]]; do sleep .1; done
while kill -0 "$pid" 2>/dev/null; do sleep 0.5; done

xsel -i </tmp/xselection


text:
Q: Forms Authentication Across Applications has no cookie I have two applications. The first one is an ASP.NET 4 MVC application that requires authentication. The second is an app that will handle the authentication and set the forms authentication cookie.
On the authorizing app, I call
FormsAuthentication.SetAuthCookie(username, false);

and then I do a simple Response.Redirect back to my MVC application.
In the MVC app, I am making a custom filter that inherits from AuthorizeFilter. On the OnAuthorization method, I was going to decrypt the cookie and grab some additional user data from the authorized user.
My problem is, that
HttpContext.Current.Request.Cookies

has nothing in it. I have checked out fiddler, and the authentication app correctly sets the cookie, and the MVC application gets the cookie, but when it gets to my filter, there is nothing there.
My web.config has in both applications has the exact same setup:
      <forms
    name=".ASPXFORMSAUTH"
    protection="All"
    path="/"
    timeout="30"
    enableCrossAppRedirects="true"
    domain="localhost"/>

And I have setup both with the same machineKey to be able to decrypt the cookie. The problem is, I am not seeing any cookie in my OnAuthorization method within my MVC filter.
Right now both applications are running on my local IIS instance.

A: All the weird behavior was due to the httpRuntime between each application being different. My MVC application was set to 4.5 while my application that was setting the cookie was 4.0. Apparently there was a change in how the crypto happens behind the scenes, and therefore when the cookie came through the pipeline, it would get stripped out as ASP.NET couldn't decrypt it.
I came across this when I manually tried to decrypt the cookie by setting the name property different. That way I could access the cookie and try to dectypt, but at that point I would get an exception.
I found the following link led me in the right direction: Sharing a cookie between two websites on the same domain
By setting the compatibility mode setting on the machine key, the cookie came through just fine and could be decrypted.


text:
Q: iptables rule not working on aliased interface even with interface and destination set I have 2 IP address, 1 bound to eth0 and the other bound to an aliased interface, eth0:1, both of these interfaces work without a problem.
However, in iptables I have the following set of rules:
-A INPUT -i eth0 -d 174.143.246.30 -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -i eth0 -d 174.143.241.61 -p tcp -m tcp --dport 80 -j ACCEPT

iptables shows them being loaded
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere
REJECT     all  --  anywhere             loopback/8          reject-with icmp-port-unreachable
ACCEPT     all  --  anywhere             anywhere            state RELATED,ESTABLISHED
LOG        all  --  anywhere             anywhere            limit: avg 5/min burst 5 LOG level debug prefix `iptables denied: '
ACCEPT     tcp  --  anywhere             eurus.iamkura.com   tcp dpt:www
ACCEPT     tcp  --  anywhere             eurus.iamkura.com   tcp dpt:www
REJECT     all  --  anywhere             anywhere            reject-with icmp-port-unreachable

But when I look at my logs I can see that iptables claims to be blocking access on port 80 on the second IP.
Feb 11 21:54:31 eurus kernel: [ 8212.861011] iptables denied: IN=eth0 OUT= MAC=40:40:f2:77:69:a8:00:1e:f7:19:b0:7f:08:00 SRC=<MY.IP.HERE> DST=174.143.241.61 LEN=52 TOS=0x00 PREC=0x00 TTL=116 ID=26993 DF PROTO=TCP SPT=51690 DPT=80 WINDOW=8192 RES=0x00 SYN URGP=0

I am actually able to connect to port 80 on that IP without any problems, even if iptables shouts in the logs.
Any ideas?

A: IPTABLES is not blocking access to that port, but limiting the rate:
limit: avg 5/min burst 5 LOG level debug prefix `iptables denied: '

careful when you accept what an output message says as true (or a source code comment). It usually happens when you've been staring at it for too long, or at least it happens for me :)


text:
Q: OnLoadFinished in fragment causes NullPointerException, unnable to fix or reproduce the crash I have app where by using fragmentManager I manage fragments. One of the fragments list is WikiItemsFragment
My problem is about NullPointerException in OnLoadFinished
x.x.fragments.WikiItemsFragment.onLoadFinished (WikiItemsFragment.java:97)
x.x.fragments.WikiItemsFragment.onLoadFinished (WikiItemsFragment.java:33)

where line 33 is describing this fragment class,
and line 97 is describing adapter.swapCursor(cursor);
Well I still cannot reproduce problem but I know it happen due crash raports and it happened to me only few times.
I still don't understand what am I doing wrong that my app crashes in OnLoadFinished method/
How could I force to make my fragment crashed? How could I fix it or even reproduce it? I am working on Nexus 4.
public class WikiItemsFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {

public static String TAG = WikiItemsFragment.class.getSimpleName();
private ListView listView;
private TextView emptyView;
private TextView wikiItemsInfoBar;
private CursorAdapter adapter;
private Uri uri;
private String[] array;

public static WikiItemsFragment getInstance(Uri contentUri, String[] projectionArray) {
    WikiItemsFragment f = new WikiItemsFragment();
    Bundle bundle = new Bundle();
    bundle.putParcelable("uri", contentUri);
    bundle.putStringArray("array", projectionArray);
    f.setArguments(bundle);
    return f;
}

@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_wiki_items, null);

    listView = (ListView) view.findViewById(R.id.listView);
    emptyView = (TextView) view.findViewById(R.id.empty_list);
    emptyView.setTypeface(Core.robotoRegular);
    wikiItemsInfoBar = (TextView) view.findViewById(R.id.wiki_items_info_bar);
    wikiItemsInfoBar.setTypeface(Core.robotoRegular);

    return view;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);

    uri = getArguments().getParcelable("uri");
    array = getArguments().getStringArray("array");

    if (uri == WikiItemsOffensiveTable.CONTENT_URI)
        adapter = new WikiItemsOffensiveAdapter(getActivity());
    else if (uri == WikiItemsDefensiveTable.CONTENT_URI)
        adapter = new WikiItemsDefensiveAdapter(getActivity());
    else if (uri == WikiItemsOtherTable.CONTENT_URI)
        adapter = new WikiItemsOtherAdapter(getActivity());
    else if (uri == WikiItemsUsableTable.CONTENT_URI)
        adapter = new WikiItemsUsableAdapter(getActivity());
    else if (uri == WikiItemsSpecialTable.CONTENT_URI)
        adapter = new WikiItemsSpecialAdapter(getActivity());
    else if (uri == WikiItemsArtifactTable.CONTENT_URI)
        adapter = new WikiItemsArtifactAdapter(getActivity());

    listView.setAdapter(adapter);

}

@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
    return new CursorLoader(getActivity(), uri, array, null, null, null);
}

@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {

    adapter.swapCursor(cursor);
}

@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
    adapter.swapCursor(null);
}

@Override
public void onResume() {
    super.onResume();
    getLoaderManager().initLoader(0, null, this);
}

@Override
public void onPause() {
    super.onPause();
    adapter.swapCursor(null);
}
}

A: Since CursorAdapter can use a null value for the method swapCursor, it must be that onLoadFinished was called before the adapter was set.
Actually it looks like you issued a lot of ifs here:
if (uri == WikiItemsOffensiveTable.CONTENT_URI)
    adapter = new WikiItemsOffensiveAdapter(getActivity());
else if (uri == WikiItemsDefensiveTable.CONTENT_URI)
    adapter = new WikiItemsDefensiveAdapter(getActivity());
else if (uri == WikiItemsOtherTable.CONTENT_URI)
    adapter = new WikiItemsOtherAdapter(getActivity());
else if (uri == WikiItemsUsableTable.CONTENT_URI)
    adapter = new WikiItemsUsableAdapter(getActivity());
else if (uri == WikiItemsSpecialTable.CONTENT_URI)
    adapter = new WikiItemsSpecialAdapter(getActivity());
else if (uri == WikiItemsArtifactTable.CONTENT_URI)
    adapter = new WikiItemsArtifactAdapter(getActivity());

But what if else? You must be getting another uri (possibly null, if args not set), so create a default adapter or log an error then. like this:
if (uri == WikiItemsOffensiveTable.CONTENT_URI)
    adapter = new WikiItemsOffensiveAdapter(getActivity());
else if ...
...
else
    Log.e("Oh no", "The uri was not recognized. Adapter was not created");

A: Found solution but I didn't really fully understand what had happened.. I had to change if statements to UriMatcher. Somehow comparing uri with string uri didn't work always. Sometimes I was comparing element1 with element1 and it was saying, hey it is not the same! Very strange.


text:
Q: ANR in Canvas.native_drawBitmap I've been receiving the same ANR reports recently.
The ANR happens when app tries to draw some bitmaps (when rendering a GridView with ImageViews as elements).
I've did a lot of debugging and can now surely say that hangs don't depend neither on bitmap, nor on position where it's being drawn.
The heap is 50% free, images are no bigger than 400px^2
Grid elements doesn't have any custom layout - just simple ImageView.
Tested on HTC Desire (1 GHz CPU), Hero, emulators, etc.
The ANR continues forever so it's like some infinite loop is running while drawing bitmap.
What else can cause such a hang?
The report follows:
DALVIK THREADS:
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 s=N obj=0x40020ba0 self=0xddd0
  | sysTid=32366 nice=0 sched=0/0 cgrp=unknown handle=-1345025972
  at android.graphics.Canvas.native_drawBitmap(Native Method)
  at android.graphics.Canvas.drawBitmap(Canvas.java:1045)
  at android.graphics.drawable.BitmapDrawable.draw(BitmapDrawable.java:323)
  at android.widget.ImageView.onDraw(ImageView.java:860)
  at android.view.View.draw(View.java:6740)
  at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
  at android.view.ViewGroup.drawChild(ViewGroup.java:1638)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
  at android.view.View.draw(View.java:6743)
  at android.widget.FrameLayout.draw(FrameLayout.java:352)
  at android.view.ViewGroup.drawChild(ViewGroup.java:1640)
  at android.view.ViewGroup.dispatchDraw(ViewGroup.java:1367)
  at android.view.View.draw(View.java:6743)
  at android.widget.FrameLayout.draw(FrameLayout.java:352)
  at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:1847)
  at android.view.ViewRoot.draw(ViewRoot.java:1407)
  at android.view.ViewRoot.performTraversals(ViewRoot.java:1163)
  at android.view.ViewRoot.handleMessage(ViewRoot.java:1727)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:123)
  at android.app.ActivityThread.main(ActivityThread.java:4627)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:521)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
  at dalvik.system.NativeStart.main(Native Method)

A: It's very hard to pinpoint your problem without your code or at least a small sample. You probably need to load you images using AsyncTask. Also turning on StrictMode is very helpful for finding ANR errors.
public void onCreate() {
 if (DEVELOPER_MODE) {
     StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
             .detectDiskReads()
             .detectDiskWrites()
             .detectNetwork()   // or .detectAll() for all detectable problems
             .penaltyLog()
             .build());
     StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
             .detectLeakedSqlLiteObjects()
             .detectLeakedClosableObjects()
             .penaltyLog()
             .penaltyDeath()
             .build());
 }
 super.onCreate();
 }

Make sure to remove StrictMode before you release. It will cause a VerifyError on devices before api level 9.
It's a nice feature to use during development. It will cause your app to crash gracefully when ever you do something that might block the UI thread.


text:
Q: Fisher's exact test vs chi-squared I've been trying to figure out the correct way to calculate the p-value for my data. I originally created a simulation that randomly selected numbers that were greater than or less than a certain number in a specific range given by a dataset. Let me give you an example of what my datasets looked like for clarity:
Expected dataset:
exon_number    number_of_exons
4              20
5              16
2              31
4              15
15             20

Observed dataset:
exon_number    number_of_exons
21             30
15             18
16             20

For each line in my datasets, I randomly selected say 100 numbers between 1 and 20 (for an example from the expected dataset) and determined if the randomly selected number was greater than or less than the exon_number. If it were greater than, I would bin it to the greater than bin. I would do this for all the lines in my datasets and created a total greater than or less than bin for my entire dataset. However, since my datasets were of different sizes, there were a greater amount of greater-thans or less-thans complied for the "expected dataset". Is this problematic? Here are my real results:
               Expected    Observed
Less than      698402      11105
Greater than   918898      13573

I understand that the Fisher's exact test is only for small numbers and should not be used, am I correct? I'm trying to test if the observed data seems to cluster more in the beginning or end of a transcript compared to the expected results.
In that case, I've been using the chi-squared method as below:
import numpy
import scipy.stats
scipy.stats.chisquare([11105, 13573], f_exp=[698402, 918898])

However my output gives me a p-value of 0. Am I doing something wrong? Am I running the test incorrectly? Is my data problematic? I'm new to programming and statistical testing. Any help would be greatly appreciated (and explanations)

A: You are right that you don't want to use Fisher's exact test here.  There isn't anything wrong with using it with large numbers, but it ends up being approximated then, so you lose the 'exact test' advantage that people sometimes want.  In addition, Fisher's exact test assumes the marginals are fixed in advance, which isn't true here (and is in fact rarely true).
The reason your chi-squared test is not working properly is that the numbers for the expected and observed are not similar.  The expected counts sum to 1617300, whereas the observed sum to 24678.  What you really want to compare your observed counts to is the expected proportions.  Using your data (and R), here is an example:
chisq.test(x=c(11105, 13573), p=c(698402, 918898)/1617300)
#         Chi-squared test for given probabilities
#
# data:  c(11105, 13573)
# X-squared = 33.185, df = 1, p-value = 8.381e-09

I do not believe this is the right analysis for your question, though.  I suspect you need to something like a Mann-Whitney U-test or Wilcoxon signed rank test.


text:
Q: Git repositories holding plugin repositories I've been struggling with which approach to take with this project for while and decided to take some advice from the community.
We are developing an open source framework that allows others to use its features by implementing some interface. By implementing this interface others are essentially developing a plugin the this framework (or at least that's how I see it and will call it for the rest of this question).
We use git as the framework's version control. (eventually will be uploaded to Github or such).
And the project is built using CMake.
In addition to allowing others the option of developing plugins of their own, we have some implementations of our own that we want to provide as open source. This is both for providing a common usage, and also for tutorial purposes (showing how to implement the interface and other usages examlpes). In order to simulate real world development of such plugins, our plugin (let's call it Plugin1) is implemented in a different git repository than the framework.
In order to support compilation of both the framework and our plugins, the framework has a "plugins" folder which we expect to contain folders of CMake projects that provide an implementation of the interface. We don't assume anything on the projects, other than that they use CMake. (to add the plugins to the tree - add_subdirectory() is called via script that search through the plugins folder)
So basically we have something like this:
. (framework repository)
├── CMakeLists.txt
├── plugins
│   ├── CMakeLists.txt
│   ├── plugin1
│   ├── plugin2
│   ├── user_implemented_plugin_1
│   └── other plugins...
├── src
├── tests
└── etc...

Where each plugin under ./plugins/ is a different git repository (some our own and some might be user implementations).
So in order to download each plugin we git clone each repo (and if we need we checkout some specific tag).
We don't expect users to use this way (they should make install the framework or install it via package), but for our development it is convenient.
This way helps us test the framework in our build system (using simple script that downloads the plugins repos).
As I've said eventually this will become open source and we would like developers to download the framework as well as the plugins we developed.
Here is where it might become inconvenient, since users will have to use a script to download the repositories, or will have to do it manually and I'm not sure this the best approach.
My question is really more of a request for advice and feedback.
I looked around the web for best practices and such for this sort of development but couldn't find anything.
Some suggested to use google repo but it seemed like an overkill.
Some suggested using git submodule, but from my understanding this is for cases where the parent repo depends on the child repo and my case is the other way around.
Am I doing some rookie mistake developing the project like this? does git have some support for managing this sort of tree? are there any tools that you recommend to use?

A: For the purpose to make plugins to depend on framework, you can add the code from framework repo to thee plugin repos. Assume you want the code of master branch in framework repo apply in plugin repos, you can use
git subtree add --prefix=user <URL for framework repo> master


text:
Q: Gulp Error: File to import not found or unreadable I'm currently building an html only website using VS Code. I get the following error intermittently when saving sass files. Using browersync, the browser updates with the changes, when it works. The error only happens sometimes but it's hindering my work.
gulp-notify: [Gulp - Error] Error: sass\style.scss
Error: File to import not found or unreadable: pages/global.
        on line 2 of sass/style.scss
>> @import "pages/global";

I've installed the latest npm in the root of the website. I inherited the gulp file from a previous developer and it's worked fine in most cases.
// Defining requirements
var gulp         = require( 'gulp' );
var sass         = require( 'gulp-sass' );
var watch        = require( 'gulp-watch' );
var rename       = require( 'gulp-rename' );
var concat       = require( 'gulp-concat' );
var uglify       = require( 'gulp-uglify' );
var args         = require( 'yargs' ).argv;
var browserSync  = require( 'browser-sync' ).create();
var autoprefixer = require( 'gulp-autoprefixer' );
var cleanCSS     = require( 'gulp-clean-css' );
var sourcemaps   = require( 'gulp-sourcemaps' );
var notify       = require( 'gulp-notify' );
var svgstore     = require( 'gulp-svgstore' );
var cheerio      = require( 'gulp-cheerio' );
var fs           = require( 'fs' );
var gulpif       = require( 'gulp-if' );

// Site Variables
var websiteURL = 'http://devsite.local.com';

// Get args object as a string
var getTask = JSON.stringify(args);

// If task is not production
if ( getTask.indexOf( 'production' ) !== -1 ) {
    // Define "dev" variable
    var dev = false;
} else {
    var dev = true;
}

/**
 * [handleErrors If Sass error]
 * @return [Don't Kill Watch]
 */
function handleErrors(err) {
    var args = Array.prototype.slice.call( arguments );

    // Ignore "untitled folder ENOENT" error (Gulp Watch Issue)
    if ( err.toString().indexOf('ENOENT') >= 0 ) {
        // Keep gulp from hanging on this task
        this.emit( 'end' );
    } else {
        // Send error to notification center with gulp-notify
        notify.onError({
            title: 'Gulp - Error',
            message: 'Error: <%= error.message %>'
        }).apply( this, args );

        // Keep gulp from hanging on this task
        this.emit( 'end' );
    }
}

// BrowserSync
gulp.task( 'browserSync' , function () {

    browserSync.init({
        proxy: websiteURL,
        https: websiteURL.includes('https'),
        notify: false
    });

    // Reload PHP files
    gulp.watch( '**/*.php' )
        .on( 'error', handleErrors )
        .on( 'change', browserSync.reload );
    gulp.watch( '**/*.html' )
        .on( 'error', handleErrors )
        .on( 'change', browserSync.reload );
});

// Compiles SCSS files in CSS
gulp.task( 'sass', function() {
    gulp.src( 'sass/**/*.scss' )
        .pipe( sourcemaps.init() )
        .pipe( sass().on( 'error', handleErrors ) )
        .pipe( sourcemaps.write() )
        .pipe( gulp.dest( './' ) )
        .pipe( browserSync.stream() );
});

// Build CSS
gulp.task( 'buildcss', function() {
    gulp.src( 'sass/**/*.scss' )
        .pipe( sourcemaps.init() )
        .pipe( sass().on( 'error', handleErrors ) )
        .pipe(autoprefixer({
            browsers: ['last 5 versions'],
            cascade: false
        }))
        .pipe(cleanCSS(
            {
                compatibility: 'ie10',
                level: 2
            }
        ))
        .pipe( sourcemaps.write() )
        .pipe( gulp.dest( './' ) )
        .pipe( browserSync.stream() );
});

// Clean CSS (Production only)
gulp.task('cleancss', function() {
    return gulp.src('sass/**/*.scss') // much faster
        .pipe( sass().on( 'error', handleErrors ) )
        .pipe(autoprefixer({
            browsers: ['last 5 versions'],
            cascade: false
        }))
        .pipe(cleanCSS(
            {
                compatibility: 'ie10',
                level: 2
            }
        ))
        .pipe(gulp.dest('./'));
});

// SVG Task
gulp.task( 'svgstore', function() {
    return gulp.src(['svg/*.svg'])
    .pipe( rename( { prefix: 'icon-' } ) )
    .pipe( svgstore( { inlineSvg: true } ) )
    .pipe( cheerio({
        run: function( $ ) {
            //$( '[fill]' ).removeAttr( 'fill' );
            $( 'svg' ).attr( 'style', 'display:none' ).attr( 'width', '0' ).attr( 'height', '0' );
        },
        parserOptions: { xmlMode: true }
    } ) )
    .pipe( rename({
        basename: 'svg-icons',
        extname: '.php'
    } ) )
    .pipe( gulp.dest( './' ) );
});

// Uglifies and concat all JS files into one
gulp.task('scripts', function() {

    var jsfiles = JSON.parse(fs.readFileSync('./js/scripts.json'));
    var scripts = jsfiles.scripts;

    return gulp.src(scripts)
    .pipe( gulpif(dev, sourcemaps.init()) )
        .pipe( concat('theme.min.js').on( 'error', handleErrors ) )
        .pipe( uglify().on( 'error', handleErrors ) )
    .pipe( gulpif(dev, sourcemaps.write()) )
    .pipe( gulp.dest('./js/') )
    .pipe( gulpif(dev, browserSync.stream()) );
});

// Build Task (Same as default but with css optimized)
gulp.task('build', ['browserSync'], function(){
    gulp.watch('sass/**/*.scss', ['buildcss']).on( 'error', handleErrors );
    gulp.watch(['svg/*.svg'], ['svgstore']).on( 'error', handleErrors );
    gulp.watch(['js/src/*.js'], ['scripts']).on( 'error', handleErrors );
});

// Production Task
gulp.task('production', ['cleancss', 'scripts']);

// Watch Task
gulp.task('default', ['browserSync'], function(){
    gulp.watch('sass/**/*.scss', ['sass']).on( 'error', handleErrors );
    gulp.watch(['svg/*.svg'], ['svgstore']).on( 'error', handleErrors );
    gulp.watch(['js/src/*.js'], ['scripts']).on( 'error', handleErrors );
    gulp.watch(['js/scripts.json'], ['scripts']).on( 'error', handleErrors );
});

My sass files are stored in the /sass folder and it compiles to style.css in the root.
style.scss
/* Content */
@import "pages/global";
@import "pages/responsive";

A: This could be a permission issue. Try running permission according to your system.


text:
Q: Magento2 PWA images missing - development environment I have followed below URL.

https://webkul.com/blog/magento2-3-pwa-studio-setup/

Setup is successfully installed and my local environment is connected to PWA application, but all of my images went missing while browsing PWA. as it is taking images url something like below

https://my-pwa.com:8477/media/catalog/category/timeless.jpg

Any Configuration for changing this or any workaround.

A: Go to packages/venia-concept/.env and add pub directory, if still not works you can add whole project URL.
MAGENTO_BACKEND_MEDIA_PATH_PRODUCT="/pub/media/catalog/product"
MAGENTO_BACKEND_MEDIA_PATH_CATEGORY="/pub/media/catalog/category"


text:
Q: I upgraded to Ubuntu Bionic on our server but it asks me to upgrade to Xenial? This is when I login via SSH (no console - remote), this is Ubuntu 18.04 Bionic. I have rebooted many times, I did do-release-upgrade, and it says I should upgrade to Xenial? How come? 2-3 years ago, I upgraded from 14.04 to 16.04, then from 16.04 to 18.04, so now, I am on 18.04, and then it still says I should upgrade to Xenial as sudo apt-get install linux-generic-lts-xenial
My output is like this:
Welcome to Ubuntu 18.04 LTS (GNU/Linux 4.15.0-20-generic x86_64)

 * Documentation:  https://help.ubuntu.com
 * Management:     https://landscape.canonical.com
 * Support:        https://ubuntu.com/advantage

  System information as of Tue May  8 16:31:20 CEST 2018

  System load:                    0.0
  Usage of /:                     42.8% of 109.88GB
  Memory usage:                   39%
  Swap usage:                     1%
  Processes:                      264
  Users logged in:                0
  IP address for br0:             a.b.c.d
  IP address for br-123456789012: 1.2.3.4
  IP address for br-123456789012: 1.2.3.4
  IP address for dockerZ:         1.2.3.4

 * Meltdown, Spectre and Ubuntu: What are the attack vectors,
   how the fixes work, and everything else you need to know
   - https://ubu.one/u2Know

 * Canonical Livepatch is enabled.
   - All available patches applied.

0 packages can be updated.
0 updates are security updates.

You have packages from the Hardware Enablement Stack (HWE) installed that
are going out of support on 2016-08-04.

To upgrade to a supported (or longer-supported) configuration:

* Upgrade from Ubuntu 14.04 LTS to Ubuntu 16.04 LTS by running:
sudo do-release-upgrade

OR

* Switch to the current security-supported stack by running:
sudo apt-get install linux-generic-lts-xenial

and reboot your system.

How come?

A: The script to detect HWE support seems to get confused with leftover kernel packages.
You can run "hwe-support-status --show-all-unsupported" as root to determine which leftover packages are present in your system, then run "apt --purge remove" on each package to get rid of them.
After that you should no longer see this message.


text:
Q: Scheduling algorithm in Racket (ASL) I need to blend aspects of an arbitrary arity tree with generative recursion and backtracking in order to come up with a simple valid schedule.
So far I have two structures, one that identifies the individual with her availability slots and maximum number of slots that she can work: (define-struct ta [name max avail]) and an assignment structure as an ordered pair: (define-struct assignment [ta slot]) where slot is simply a natural number. So for instance I have the following unit tests with the following dummies:
(define SOBA (make-ta "Soba" 2 (list 1 3)))
(define UDON (make-ta "Udon" 1 (list 3 4)))
(define RAMEN (make-ta "Ramen" 1 (list 2)))

(define NOODLE-TAs (list SOBA UDON RAMEN))

(check-expect (schedule-tas empty empty) empty)
(check-expect (schedule-tas empty (list 1 2)) false)
(check-expect (schedule-tas (list SOBA) empty) empty)
(check-expect (schedule-tas NOODLE-TAs (list 1 2 3 4))
              (list
               (make-assignment UDON 4)
               (make-assignment SOBA 3)
               (make-assignment RAMEN 2)
               (make-assignment SOBA 1)))

So my main function right now looks like this:
;; (listof TA) (listof Slot) -> Schedule or false
;; produces valid schedule given TAs and Slots; false if impossible;
;; Schedule is (listof Assignment), Assigment is (make-assignment TA Slot)
(define (schedule-tas tas slots)
  (local [(define (fn-for-tas tas)
            (cond [(empty? slots) empty]
                  [(and (empty? tas)(cons? slots)) #f]                    ;From two 'One-Of' type analysis
                  [else
                   (if (all-assigned? (next-assignments tas slots) slots) ;Generative-recursion through 'next-assignments'
                       (next-assignments tas slots)                       ;I know about the duplication of the computation here.
                       (fn-for-loa (next-assignments tas slots)))]))      ;just waiting to have a working version before I make it less readable

          (define (fn-for-loa loa)
            (cond [(empty? loa) #f]
                  [else
                   (local [(define try (fn-for-tas (first loa)))]
                     (if (not (false? try))
                         try
                         (fn-for-loa (rest loa))))]))]
    (fn-for-tas tas)))

So to produce the data through generative recursion I wished for (next-assignments tas slots) as a composition of what I need: make all assignments and filter by availabity and maximum number of workable slots:
;; (listof TA) (listof Slot) -> (listof Assignment)
;; creates next list of possible valid assignments
(define (next-assignments tas slots)
  (filter-by-max (filter-by-availability (all-assignments tas slots))))

(define (all-assignments tas slots)
  (local [(define (assign-ta ta)
            (map (λ (s) (make-assignment ta s)) slots))

          (define (all-assignments tas)
            (cond [(empty? tas) empty]
                  [else
                   (append (assign-ta (first tas))
                           (all-assignments (rest tas)))]))]
    (all-assignments tas)))

However I am not convinced that this is what I need since it rather creating the whole searchable space in one go instead of the branch-and-prune strategy that I need to implement. Anyways, the rest of the auxiliary functions are here, for completeness:
(define (filter-by-availability loa)
  (cond [(empty? loa) empty]
        [else
         (if (member? (assignment-slot (first loa))
                      (ta-avail (assignment-ta (first loa))))
             (cons (first loa) (filter-by-availability (rest loa)))
             (filter-by-availability (rest loa)))]))

(define (filter-by-max loa)
  (cond [(empty? loa) empty]
        [else
         (if (> (length loa) (ta-max (assignment-ta (first loa))))
             (filter-by-max (rest loa))
             loa)]))

I am also not very happy with these filtering functions as they seem too 'dumb' somehow; they just drop whichever ta they happen to find in order to satisfy the conditions.
And finally, I have the base case of the generative recursion:
(define (all-assigned? loa slots)
  (= (length loa)
     (length slots)))

which is somehow the 'dumbest' one of all, I think. Anyways, as you can see I am not happy with my code. But the main problem that I see with it is, again, that I don't think I am generating a bone-fide tree. So if you could just let know how to do that I would be immensely grateful!
N.B. This is for a course I am taking but I think you can tell that I have really tried. Please help!


text:
Q: How to strip last bits from ip address How do I zero out the last n digits of an IP address in Python? I'd prefer solutions using the standard library, most likely ipaddress.
Some strip_addr testcases would look like:
assert strip_addr(u'1.2.3.4', 24) == u'1.2.3.0'
assert strip_addr(u'2001:1234:f678::9', 33) == u'2001:1234:8000::'

A: How about using interface network objects?
import ipaddress

def strip_addr(ip, bits):
    nwif = ipaddress.ip_interface(u'%s/%s' % (ip, bits))
    return str(nwif.network.network_address)

assert strip_addr(u'1.2.3.4', 24) == u'1.2.3.0'
assert strip_addr(u'2001:1234:f678::9', 33) == u'2001:1234:8000::'


text:
Q: newline-ignoring diff / diff across multiple lines / reflow-ignoring diff Does anybody know of a diff-like tool that can show me the changes between two text files, but ignore changes in whitespace including newlines?
Here's an example:

the quick brown fox jumped over the lazy bear.  the quick brown fox
jumped over the lazy bear.  the quick brown fox jumped over the lazy
bear.  the quick brown fox jumped over the lazy bear.

quick brown fox jumped over the lazy bear.  the quick brown fox jumped
over the lazy bear.  the quick brown fox jumped over the lazy bear.
the quick brown fox jumped over the lazy bear.

All I did was delete one word and reflow it, but "diff -b" detects a change on every line (as it should; I'm not saying this is a bug in diff).  But for large LaTeX files this is a major problem; change one word in a long paragraph and the diff you get back is basically useless.
By the way, I'm aware that this requires way more computational power than the usual lines-are-atomic diff.  I'm only doing this on small human-generated files and am happy to wait a long time if I have to.

A: wdiff does word-by-word alignment.
For an easy-to-read display in a terminal, run
 wdiff -al <file1> <file2> | less

This will show (at least on my system) insertions in <file2>boldfaced and deletions from <file2> underlined.

A: One option is to do this by splitting the entire file into words. Not 100% the same result in terns of knowing the context but very fine-tuned to the type of change you care about.
Example :
cat file1 | perl5.8 -e '{s/\s+/\n/g;}' > file1.split_words
cat file2 | perl5.8 -e '{s/\s+/\n/g;}' > file2.split_words
diff file1.split_words file2.split_words

You can do even better if the text has special properies, to be more specific, the reflow only happens within the bounds of a paragraph which is defined as 2 newlines in a row - simply replace all the single newlines with spaces and run regular diff -w on results.


text:
Q: Загрузка изображений.BitmapFactory.decodeResource Есть класс DrawingImageView :
class DrawingImageView extends View {
    Initialization init;
    private PointF point;
    private Paint paint = new Paint();

    public DrawingImageView(Context context) {
        super(context);
        init = new Initialization(getContext());
    }

    public DrawingImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public DrawingImageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(init.b01,10,10,paint);
    }
}

И Класс Initialization:
public class Initialization extends View {
    Bitmap b01;
    public Initialization(Context context) {
        super(context);
        b01 = BitmapFactory.decodeResource(getResources(), R.raw.t02);
    }
}

Когда пытаюсь нарисовать через обьект класса init.b01 app крашиться. когда описываешь в самом классе DrawingImageView все нормально. Как это исправить?
Ошибка:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at android.view.GLES20Canvas.drawBitmap(GLES20Canvas.java:758)
at android.view.GLES20RecordingCanvas.drawBitmap(GLES20RecordingCanvas.java:104)
at com.example.itsgonnabeme.simpledraw.DrawingImageView.onDraw(Dview.java:46)
at android.view.View.draw(View.java:13807)
at android.view.View.getDisplayList(View.java:12742)
at android.view.View.getDisplayList(View.java:12786)
at android.view.View.draw(View.java:13520)
at android.view.ViewGroup.drawChild(ViewGroup.java:3019)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2883)
at android.view.View.getDisplayList(View.java:12740)
at android.view.View.getDisplayList(View.java:12786)
at android.view.View.draw(View.java:13520)
at android.view.ViewGroup.drawChild(ViewGroup.java:3019)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2883)
at android.view.View.getDisplayList(View.java:12740)
at android.view.View.getDisplayList(View.java:12786)
at android.view.View.draw(View.java:13520)
at android.view.ViewGroup.drawChild(ViewGroup.java:3019)
at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2883)
at android.view.View.draw(View.java:13815)
at android.widget.FrameLayout.draw(FrameLayout.java:467)
at com.android.internal.policy.impl.PhoneWindow$DecorView.draw(PhoneWindow.java:2235)
at android.view.View.getDisplayList(View.java:12742)
at android.view.View.getDisplayList(View.java:12786)
at android.view.HardwareRenderer$GlRenderer.draw(HardwareRenderer.java:1249)
at android.view.ViewRootImpl.draw(ViewRootImpl.java:2473)
at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2340)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2142)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
at android.view.Choreographer.doCallbacks(Choreographer.java:579)
at android.view.Choreographer.doFrame(Choreographer.java:548)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
at android.os.Handler.handleCallback(Handler.java:800)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5371)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
at dalvik.system.NativeStart.main(Native Method)

A: В андроиде нельзя ничего делать в конструкторах фрагментов и активити. Это нужно просто запомнить и никогда их не трогать. Вместо конструктора этих классов используйте их методы onCreate(Bundle savedInstanceState)
В данном случае у вас NPE при попытке взять ресурсы не подсоединённой к контексту приложения активити

A: MainActivity:
public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new DrawView(MainActivity.this));
    }
}

class DrawView:
public class DrawView extends View {
    Paint paint;
    Initialization init;
    public DrawView(Context context) {
        super(context);
        init = new Initialization(getContext());
        paint  = new Paint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawBitmap(init.t01,0,0,paint);
    }
}

class Initialization:
public class Initialization  extends View  {
    Bitmap t01;
        public Initialization(Context context) {
        super(context);
        t01 = BitmapFactory.decodeResource(getResources(), R.raw.t02);
    }
}


text:
Q: How to Make Forgot Password in Codeigniter, Password send in email Hello guyz i have create small kind of application in codeigniter,in this application i am doing forgot password module, i have created a function but dont know why its not working, i need random password have to been send in mail which will be autogenerated , but email method does not work, so give me some suggestion.
Here is My view:
<form action="<?php echo base_url() . "welcome/forgotpassword" ?>" method="POST">

                    <input type="email" class="form-control" placeholder="Email" name="user_email" />

                     <input type="submit"  class="btn btn-primary btn-block btn-flat"  value="Send">

    </form>

Here is my Controller:
public function forgotpassword(){

    $email = $this->input->post('user_email');
    $findemail = $this->main_model->ForgotPassword($email);
    $this->load->view('forgotpassword');
    if ($findemail) {
        $this->main_model->sendpassword($findemail);
    } else {

          $this->session->set_flashdata('msg', 'Email not found!');

    }
}

Here is My model:
 public function sendpassword($data) {
    $email = $data['user_email'];
    print_r($data);
    $query1 = $this->db->query("SELECT *  from user_registration where user_email = '" . $email . "'");
    $row = $query1->result_array();

    if ($query1->num_rows() > 0) {

        $passwordplain = "";
        $passwordplain = rand(999999999, 9999999999);
        $newpass['user_password'] = md5($passwordplain);
        $this->db->where('user_email', $email);
        $this->db->update('user_registration', $newpass);
        $mail_message = 'Dear ' . $row[0]['full_name'] . ',' . "\r\n";
        $mail_message .= 'Thanks for contacting regarding to forgot password,
 Your Password is ' . $passwordplain . '' . "\r\n";
        $mail_message .= '
Please Update your password.';
        $mail_message .= '
Thanks & Regards';
        $mail_message .= '
Your company name';
        require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->isSMTP();
        $mail->SMTPSecure = "tls";
        $mail->Debugoutput = 'html';
        $mail->Host = "ssl://smtp.googlemail.com";
        $mail->Port = 465;
        $mail->SMTPAuth = true;
        $mail->Username = "xxxxxxxxx@gmail.com";
        $mail->Password = "xxxxxxxx";
        $mail->setFrom('xxxxxxx@gmail.com', 'admin');
        $mail->IsHTML(true);
        $mail->addAddress('user_email', $email);
        $mail->Subject = 'OTP from company';
        $mail->Body = $mail_message;
        $mail->AltBody = $mail_message;

        if (!$mail->send()) {

            $this->session->set_flashdata('msg', 'Failed to send password, please try again!');
        } else {

            echo $this->email->print_debugger();
            $this->session->set_flashdata('msg', 'Password sent to your email!');
        }

    }
}

A: This function may have something to do with it... can you show us that?
$findemail = $this->main_model->ForgotPassword($email);

When you use print_r($data) is anything returned?
If not, $query1 will be 0 or null and everything will break.
// core function
public function sendpassword($data) {
    // include your libary at the top
    require FCPATH . 'assets/PHPMailer/PHPMailerAutoload.php';
    // email retrieved from the ForgotPassword() method.
    $email = $data['user_email'];
    // get the user_info array row
    $query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
    $row = $query1->result_array();
    if ($query1->num_rows() > 0) {
        // assign users name to a variable
        $full_name = $row['full_name'];
        // generate password from a random integer
        $passwordplain = rand(999999999, 9999999999);
        // encrypt password
        $encrypted_pass = $this->pass_gen($passwordplain);
        $newpass['user_password'] = $encrypted_pass;
        // update password in db
        $this->db->where('user_email', $email);
        $this->db->update('user_registration', $newpass);
    // begin email functions
    $result = $this->email_user($full_name, $email, $passwordplain);
    echo $result;
    }
}

// email sending
public function email_user($full_name, $email, $passwordplain) {
    // compose message
    $mail_message = 'Dear ' . $full_name. ',' . "\r\n";
    $mail_message .= 'Thanks for contacting regarding to forgot password,
 Your Password is ' . $passwordplain . '' . "\r\n";
    $mail_message .= '
Please Update your password.';
    $mail_message .= '
Thanks & Regards';
    $mail_message .= '
Your company name';
    // email config
    $mail = new PHPMailer;
    $mail->isSMTP();
    $mail->SMTPSecure = "tls";
    $mail->Debugoutput = 'html';
    $mail->Host = "ssl://smtp.googlemail.com";
    $mail->Port = 465;
    $mail->SMTPAuth = true;
    $mail->Username = "xxxxxxxxx@gmail.com";
    $mail->Password = "xxxxxxxx";
    $mail->setFrom('xxxxxxx@gmail.com', 'admin');
    $mail->IsHTML(true);
    $mail->addAddress('user_email', $email);
    $mail->Subject = 'OTP from company';
    $mail->Body = $mail_message;
    $mail->AltBody = $mail_message;
    // send the mail
    if (!$mail->send()) {
        return $this->email->print_debugger();
        $this->session->set_flashdata('msg', 'Failed to send password, please try again!');
    } else {
        return $this->email->print_debugger();
        $this->session->set_flashdata('msg', 'Password sent to your email!');
    }
}

// Password encryption
public function pass_gen($password) {
    $encrypted_pass = md5($password);
    return $encrypted_pass;
}

A: $query1 = $this->db->query("SELECT * from user_registration where user_email = '" . $email . "'");
it is has sql injection!


text:
Q: how to change some words color real time while accepting input in python I'm trying to write a piece of code which will accept a string as input and if the user has entered an specific word it will change the word's color to red but all in real time I mean as the user is entering the string not after he pressed the Enter .
I know it should be done by threading but the problem is I don't know how to make the threads works Real-time.
Could anybody help me please?

A: Here is the method for reading one char at a time from stdin, taken from this answer:
class _Getch:
    """Gets a single character from standard input.  Does not echo to the
screen."""
    def __init__(self):
        try:
            self.impl = _GetchWindows()
        except ImportError:
            self.impl = _GetchUnix()

    def __call__(self): return self.impl()

class _GetchUnix:
    def __init__(self):
        import tty, sys

    def __call__(self):
        import sys, tty, termios
        fd = sys.stdin.fileno()
        old_settings = termios.tcgetattr(fd)
        try:
            tty.setraw(sys.stdin.fileno())
            ch = sys.stdin.read(1)
        finally:
            termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)
        return ch

class _GetchWindows:
    def __init__(self):
        import msvcrt

    def __call__(self):
        import msvcrt
        return msvcrt.getch()

getch = _Getch()

One possible usage of this code could be like below. You read characters and store them in a variable. Then you print this to the stdout and color it by colorama. This code is just an example, and it still has one thing not working properly: the handling of the "space". But if you try it out you will see that the words are being colored in real time. Additional tweaks are needed to properly output all the letters in real time, including space. But I leave that up to you, this is more than enough to get you started.
import sys
from colorama import Fore

special_words = ['bannanas', 'eggs', 'ham']
my_text = ''
while True:
    c = getch()
    if ord(c) == 13:  # newline, stop
        break
    my_text += c

    sys.stdout.write("\r")  # move to the line beginning
    for word in my_text.split():
        if word in special_words:
            sys.stdout.write(Fore.RED + word + " ")
        else:
            sys.stdout.write(Fore.RESET + word + " ")
    sys.stdout.flush()

# reset the color when done
print(Fore.RESET)


text:
Q: How to write Azure storage table queries for non-existent columns We have a storage table where we want to add a new integer column (It is in fact an enum of 3 values converted to int). We want a row to be required when:

*

*It is an older row and the column does not exist

*It is a new row and the column exists and does not match a particular value

When I just use a not equal operator on the column the old rows do not get returned. How can this be handled?
Update
Assuming a comparison always returns false for the non-existent column I tried somethinglike below (the value of the property will be always > 0 when it exists), which does not work either:

If the (Prop GreaterThanOrEqual -1) condition returns false I assume the value is null.

If not then, the actual comparison happens.

string propNullCondition = TableQuery.GenerateFilterConditionForInt(
                    "Prop",
                    QueryComparisons.GreaterThanOrEqual,
                    -1);

propNullCondition = $"{TableOperators.Not}({propNullCondition})";

string propNotEqualValueCondition = TableQuery.CombineFilters(
            propNullCondition,
            TableOperators.Or,
            TableQuery.GenerateFilterConditionForInt(
                "Prop",
                QueryComparisons.NotEqual,
                XXXX));

Note: The table rows written so far do not have "Prop" and only new rows will have this column. And expectation is the query should return all old rows and the new ones only when Prop != XXXX.

A: It seems that your code is correct, maybe there is a minor error there. You can follow my code below, which works fine as per my test:
Note: in the filter, the column name is case-sensitive.
        CloudTableClient tableClient = storageAccount.CreateCloudTableClient();
        CloudTable table = tableClient.GetTableReference("test1");

        string propNullCondition = TableQuery.GenerateFilterConditionForInt(
                "prop1", //note the column name shoud be case-sensitive here.
                QueryComparisons.GreaterThanOrEqual,
                -1);

        propNullCondition = $"{TableOperators.Not}({propNullCondition})";

        TableQuery<DynamicTableEntity> propNotEqualValueCondition = new TableQuery<DynamicTableEntity>()
            .Where(
             TableQuery.CombineFilters(
                propNullCondition,
                TableOperators.Or,
                TableQuery.GenerateFilterConditionForInt(
                "prop1",//note the column name shoud be case-sensitive here.
                QueryComparisons.NotEqual,
                2)));

        var query = table.ExecuteQuery(propNotEqualValueCondition);

        foreach (var q in query)
        {
            Console.WriteLine(q.PartitionKey);
        }

The test result:

Here is my table in azure:


text:
Q: Short name for Autosys MAchine Hi Can any one advice how to make aliases for AutoSys machine name
something like -1045_VM_AMDGC_APP_DEV2 i am using the whole name and unable to find how to make  aliases.
As a work around i insert a machine that points to a random dns and then update command to point to an existing agent machine to create an alias. is okay or is there a simpler way to do it.
I tried to use insert alias with node name pointing to the real machine but does not allow like that and gives machine already exists error even if the machine name is different.
insert_machine:ALiasname
type:a
nodename:vmsometjing..network.network

A: You can achieve that with virtual machines:
insert_machine: aliasname
type: v
machine: 1045_VM_AMDGC_APP_DEV2

Then you just need to update the job to point to the aliasname and all will be good, make sure when you delete the machine to update the definition of the virtual as well.


text:
Q: Assigning a domain name to an AWS Fargate task I have an AWS Fargate task running a web app in a public subnet so it has a public address. My question is how to I connect a domain (through Route 53) to that task, so that nothing breaks when I deploy a new version of it.

*

*I know I can use ALB/NLB but I want to save on costs.

*I don't want to use the public IP directly as it may change.

*I assume the solution has to do something with the ENI but I'm not sure how to point to it through Route 53.

Any help would be much appreciated.
Thanks

A: I don't believe @m-glatki's answer is correct - you cannot use Service Discovery for public IP addresses, as mentioned by @andreas-pasch.
The only way I've found to implement this was to create a Lambda function triggered by a Cloudwatch Event for when the container reaches the 'RUNNING' state. My first attempt was to fetch the container metadata and update Route 53 on launch via a startup script but this was a dead-end.
There's a good guide here for JavaScript (I re-wrote in Python & Terraform). Something I thought missing was adding the ECS cluster ARN to the Cloudwatch Event pattern under 'detail'; the function may trigger on every container launch otherwise. The ECS event docs might be useful for specifics.
AWS have a guide for EC2 but I didn't bother wading through their code; might be handy to refer to if you also prefer Python.
NB: Service Discovery works well for private IP addresses.

A: As stated in the ECS developer guide:

Amazon ECS does not support registering services into public DNS namespaces

So no chance for out-of-the-box public domain registration via ECS Service Discovery. But what you can do, is to use AWS SKD to fetch the public IP address of your container after deployment and register it in your public Route 53 hosted zone.
This article shows an approach using a lambda function to do exactly that whenever your container is redeployed.

A: I tried to.
The problem is the public ip that fargate uses is attached to the TASK so if the task is restarted then a new ip address is given and the dns record needs to be updated.  Thats why the alb/nlb is used.
In theory you could use something else to manage the dns host records, perhaps a lambda function or something
Service Discovery Considerations:
The DNS records created for a service discovery service always register with the private IP address for the task, rather than the public IP address, even when public namespaces are used.
https://forums.aws.amazon.com/thread.jspa?threadID=270599

A: For most cases, you most likely want to use an ALB/NLB for service discovery. While there are some costs, you also get a lot of benefits: Some DoS protection, scaling metrics, logging, SSL/TLS
However, you can use ECS service discovery.

Service discovery uses Amazon Route 53 auto naming API actions to manage DNS entries for your service's tasks, making them discoverable within your VPC

and

Public namespaces are supported but you must have an existing public hosted zone registered with Route 53 before creating your service discovery service.
Service discovery requires that tasks use either the awsvpc, bridge, or host network mode.

Here is a Blog entry detailing how to use Service discovery with fargate: https://aws.amazon.com/blogs/aws/amazon-ecs-service-discovery/


text:
Q: Problems with paging in vuex store/actions [this.paginator is not a function] I am trying to solve a problem when I call the paginator function in [ACTYPE.GET_MOVIES].
It shows me the error that says the following:

TypeError: _this.paginator is not a function at eval (actions.js?
  63e0: 13)

Store/Actions.js
import {ACTYPE} from './types/actions_types';
import {MUTYPE} from './types/mutations_types';
import {BASE_URL , TOP_MOVIES , QUERY_URL} from '../API_URLs/index';
import axios from 'axios';

const A = axios.create({ baseURL: String(BASE_URL) });

export const actions = {
  [ACTYPE.GET_MOVIES]({commit} , page){
  A.get(TOP_MOVIES).then((res) =>{
    console.log(res);
    const dataPaginated = this.paginator(res.data , page)
    commit(MUTYPE.SET_MOVIES_DATA , dataPaginated);
    commit(MUTYPE.IS_LOADING , false);
  }).catch((err) =>{
      console.log(err);
  });
},

paginator(items, page, per_page){
  var page = page || 1,
  per_page = per_page || 10,
  offset = (page - 1) * per_page,

  paginatedItems = items.slice(offset).slice(0, per_page),

  total_pages = Math.ceil(items.length / per_page),

  paginContent = {
    page: page,
    per_page: per_page,
    pre_page: page - 1 ? page - 1 : null,
    next_page: (total_pages > page) ? page + 1 : null,
    total: items.length,
    total_pages: total_pages,
    data: paginatedItems
  };
  console.log("Paginate Item: " , paginatedItems);
  console.log("Pagin Content: " , paginContent);
  return paginContent.data;
 },

A: you should change your paginator(items, page, per_page){ ...
to function paginator(items, page, per_page){
That way the declaration gets hoisted. If not paginator is not declared.
then you can remove the this in this.paginator(res.data , page)
After doing that it should work


text:
Q: React test state change after timeout say I have a Card element that flips when clicked upon. After 2 seconds, it must automatically flip back. In CSS terms, after clicking, the transform style is set to rotateY(180deg), after 2 seconds it should becom Initial
I want to write unit tests for this back-flip (currently the test passes even though I expect the transform prop to equal initial):
it( 'flips', () => {
        const testedCard = shallow( <Card /> )
        testedCard.setState( { faceUp: true } )

        setTimeout(
            () => {
                const cardFlipper = testedCard.node.props.children
                expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
            },
            2500
        );
    } )

A: If you are using mocha or jasmine, you can pass a done callback in the it:
it( 'flips', (done) => {
        const testedCard = shallow( <Card /> )
        testedCard.setState( { faceUp: true } )

        setTimeout(
            () => {
                const cardFlipper = testedCard.node.props.children
                expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
                done();
            },
            2500
        );
    } )

However, depending on your test runner (settings), the done timeout might occur before 2500 mills.  You might have to configure a different timeout value.
As a side note, unit tests based on timing are not usually a good idea.  Consider designing the component so that you can test more deterministically.


text:
Q: Getting the same row multiple times out of a MultiIndexed DataFrame Presume I have a MultiIndexed Dataframe and a regular one, for example
index = [['foo','foo','bar','bar'],['spam','eggs','spam','eggs']]
arr = np.arange(1,13).reshape((4,3))

df_multi = pd.DataFrame(arr, index = index)
df = pd.DataFrame(arr)

If I were to require multiple rows from the regular DataFrame, I would do it as follows:
request = [0,0,1,0,1,2]
rows = df.loc[request]

The rows object is a new DataFrame, where each row comes from df in the order defined by request, the key part for me here is that the order of request remains and I can get the same row as many times as I require by requesting it multiple times.
But if I were to do the same thing with MultiIndexed DataFrame:
request = (['foo','foo', 'foo'], ['spam', 'eggs', 'spam'])
rows    = df_multi.loc(axis=0)[request]

I would get only the unique rows from my request and they would be sorted.
Where as what I expect is that the situation would be just like in the previous case, unsorted and repeated as requested.
How could I achieve this?

A: Pass an iterable of tuples defining each row's MultiIndex value, e.g. using zip(*request):
rows = df_multi.loc[zip(*request)]
rows

Out[51]:
          0  1  2
foo spam  1  2  3
    eggs  4  5  6
    spam  1  2  3

Note: list(zip(*request)) evaluates to
[('foo', 'spam'), ('foo', 'eggs'), ('foo', 'spam')]


text:
Q: How do 3d engines decide where polygons go in a model? I am trying to build my own 3d engine from a 2d one. so far everything works fine but its very inefficient due to the fact that the wire frame model has lines between every point on the shape. I've been doing some research but haven't been able to find anything regarding what dictates where polygons go for the most optimal rendering.
Here is what a cube looks like in my program:

Is there some mathematical way to remove all the extra geometry?
Any advice really helps, thanks.

A: Ok so after longer than I'd like to to admit I figured out that you don't need to order faces by their z coordinate, instead just take the surface normal of the shape and render only render it if it's above a value (most of the time 0) (also you'll want to use premade triangles from object files instead of assigning them to the faces yourself)


text:
Q: How declare two prompt variables for hosts in ansible playbook How declare two prompt variables for hosts in ansible playbook, I tried below Playbook but without luck.
............................................................................................................................................................
Thank you in advance.
---
- name: MD5 File Check
  gather_facts: false
  hosts: "{{ cluster_host_1 }}", "{{cluster_host_2 }}"
  hosts: localhost
  remote_user: sv_operator
  vars_prompt:
    - name: "file_1"
      prompt: "File name"
      private: no
    - name: "cluster_host_1"
      prompt: "Enter 1st Host name"
      private: no
    - name: "cluster_host_2"
      prompt: "Enter 2nd Host Name"
      private: no
  tasks:
    - stat:
        path: "/tmp/{{ file_1 }}"
        checksum_algorithm: sha256
      register: output
      delegate_to: "{{ cluster_host_1 }}"
    - debug:
        msg: "{{ output.stat.checksum }}"
    - stat:
        path: "/tmp/{{ file_2 }}"
        checksum_algorithm: sha256
      register: output_
      delegate_to: "{{ cluster_host_2 }}"
    - debug:
        msg: "{{ output_.stat.checksum }}"

A: Given the remote hosts and /tmp/file1
shell> ssh admin@test_01 sha256 /tmp/file1
SHA256 (/tmp/file1) = e2611a1fac7fc2ab99d2e792ad84f34e66740d6a3d77b97b4da39a3758357da0

shell> ssh admin@test_02 sha256 /tmp/file1
SHA256 (/tmp/file1) = 109f60103192b5c8f4e33c26b4f9c7b94489bf8de0325497b7f5a0668dc1a402

The playbook below
shell> cat playbook.yml
- name: SHA256 File Check
  hosts: localhost
  gather_facts: false
  vars_prompt:
    - name: "file_1"
      prompt: "File name"
      private: no
    - name: "cluster_host_1"
      prompt: "Enter 1st Host name"
      private: no
    - name: "cluster_host_2"
      prompt: "Enter 2nd Host Name"
      private: no
  tasks:
    - stat:
        path: "/tmp/{{ file_1 }}"
        checksum_algorithm: sha256
      register: output
      delegate_to: "{{ cluster_host_1 }}"
    - debug:
        msg: "{{ output.stat.checksum }}"
    - stat:
        path: "/tmp/{{ file_1 }}"
        checksum_algorithm: sha256
      register: output_
      delegate_to: "{{ cluster_host_2 }}"
    - debug:
        msg: "{{ output_.stat.checksum }}"

works as expected
shell> ansible-playbook playbook.yml
File name: file1
Enter 1st Host name: test_01
Enter 2nd Host Name: test_02

PLAY [SHA256 File Check] ****

TASK [stat] ****
ok: [localhost -> test_01]

TASK [debug] ****
ok: [localhost] =>
  msg: e2611a1fac7fc2ab99d2e792ad84f34e66740d6a3d77b97b4da39a3758357da0

TASK [stat] ****
ok: [localhost -> test_02]

TASK [debug] ****
ok: [localhost] =>
  msg: 109f60103192b5c8f4e33c26b4f9c7b94489bf8de0325497b7f5a0668dc1a402

PLAY RECAP ****
localhost: ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0

A: If you want your play to run on two hosts, declared through variables. You have two options.
Option 1:
Since your target hosts are comma separated, you might as well input them that way.
- hosts: '{{ my_hosts }}'
  gather_facts: false
  remote_user: 'sv_operator'

  vars_prompt:
    - name: 'my_hosts'
      prompt: 'Comma separated list of hosts'
      private: no

Then when prompted:
Comma separated list of hosts: host1.local,host2.local

Option 2:
Capture each host in individual variable like host_1 and host_2, then call it as a list in a play.
- hosts:
    - '{{ host_1 }}'
    - '{{ host_2 }}'
  gather_facts: false
  remote_user: 'sv_operator'

  vars_prompt:
    - name: 'host_1'
      prompt: 'First host'
      private: no
    - name: 'host_2'
      prompt: 'Second host'
      private: no

Then when prompted:
First host: host1.local
Second host: host2.local


text:
Q: Formulario en dos pasos, Mostrar imagen en tiempo real entre Campos necesidades y Campos de contacto y Submit estoy armando un formulario, con detalles sobre preferencias que determinan un producto recomendado , eso ya se define al completar los primeros campos de formulario, y quisiera que cuando se completen esos campos se resuelva mostrando una imagen del producto recomendado, en tiempo real, (segùn las selecciones que se hayan hecho) sin necesidad de presionar ningún botón, y y luego mas campos de contacto y el Submit/envío del formulario.
Gracias,
Saludos
cree un archivo aqui .
https://jsfiddle.net/b6a2mou8/29/#&togetherjs=iGN7kRJmvd
<form>

Manten presionada la tecla Ctrl (windows) / Command (Mac) para seleccionar mas de una opcion.

<select multiple>
<option value="Opcion1">Opcion1</option>
<option value="Opcion2">Opcion2</option>
<option value="Opcion3">Opcion3</option>
<option value="Opcion4">Opcion4</option>
<option value="Opcion5">Opcion5</option>
</select>

<fieldset>

<legend>Elige una Opcion</legend>

        <input type="radio" id="Opcion1" name="Opcion1" checked />Opcion1
        <input type="radio" id="Opcion2" name="Opcion2" />Opcion2
        <input type="radio" id="OPcion3" name="OPcion3" />OPcion3

</fieldset>

<fieldset>
<legend>Elige un caso</legend>

        <input type="radio" id="Caso1" name="Caso1" checked />
        Caso1
        <input type="radio" id="Caso2" name="Caso2" />
        Caso2
        <input type="radio" id="Caso3" name="Caso3" />
        Caso3

</fieldset>

<fieldset>
    <legend>Elige una Situacion</legend>

        <input type="radio" id="Situacion1" name="Situacion1" checked />
        Situacion1
        <input type="radio" id="Situacion2" name="Situacion2" />
        Situacion2
        <input type="radio" id="Situacion3" name="Situacion3" />
        Situacion3

</fieldset>

Nuestra recomendacion para usted es:  Aqui Quiero que aparezca una imagen del producto. Lo ideal seria que que fuera en tiempo real , sin necesidad de accionar un boton, como respuesta por completar los campos:

Una vez que vio el producto Se completa el formulario con los datos de contacto y otras necesarias y se procede al envia con la informacion

 Los siguientes datos son necesarios para cotizarle:

2Flota

Coches<select/><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option></select>

barcos
<select/>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

Motos<select/><option value="1">1</option><option value="2">2</option><option value="3">3</option>    <option value="4">4</option><option value="5">5</option></select>

<fieldset>
<legend>Tipo de Factura</legend>

<input type="radio" id="facturaA" name="facturaA" checked />
facturaA

<input type="radio" id="facturaB" name="facturaB" />
facturaB

        <input type="radio" id="facturaC" name="facturaC" />
        facturaC

</fieldset>

2datos de contacto

    Nombre<input type="text" name="nombre" />
    Telefono<input type="phone" name="telefono" />
    email<input type="email" name="email" />

<button class="btn btn-submit" name="submitform" style="background-color: rgba(100, 100, 100, 0.0);" type="submit">        enviar</button>

</form>


text:
Q: Multiple CSS Selectors with Prototype I'm refactoring some code that currently looks like this:
$$('#wrapper > div').each(function(e){
    if((e.id!='header') && (e.id!='footer') && (e.id!='content')){
        // various other stuff here
    }
});

I want to switch the initial selector and check for ID to a single line, something along these lines:
$$('#wrapper > div[id!=header]', '#wrapper > div[id!=content]', '#wrapper > div[id!=footer]')

The multiple selectors aren't working though, each selector on its own works fine though. Not sure if this is a syntax issue or what as the Prototype docs say this should work but as soon as i add extra selectors then none work.
To confirm this works:
$$('#wrapper > div[id!=header]')

And this works:
$$('#wrapper > div[id!=footer]')

but this fails to select either (without throwing an error)
$$('#wrapper > div[id!=header]', '#wrapper > div[id!=footer]')

A: You can just append the selectors to each other div[attr selector 1][attr selector 2]
Please see the following example fiddle.
The problem with your initial attempt. i.e. using commas to separate the selectors, are that they are OR-ing. so even though you specify all three, each of the others will return what the others attempt to exclude.

A: The two code snippets do radically different things. The equivalent to the top snippet should be this:
$$('#wrapper > div[id!=header][id!=footer][id!=content]')

Your selectors would select all divs that have id, since those that are "footer" will be selected under "not header".


text:
Q: $\det(\varphi + \psi)$ of 2 A-endomormphisms $\varphi,\psi: M \to M$ with A: commutative ring with unit, M: free A-module or rank 2 As is said in the title, we consider A to be a commutative ring with unit, M a free A-module of a finite rank r = 2, and $\varphi$,$\psi: M \to M$ A-endomorphisms. With this data I would like to show that
$$det(φ+ψ) + det(φ−ψ) = 2(det(φ) + det(ψ))$$
However the only thing related to this that came to my mind was the fact that $det(λφ) =λ^2det(φ)$ for $\lambda \in A$, but I'am not sure it could be usefull here.
Also, after some research I think that this problem can be shown using external product, but I have not seen it. Is there another way to show this? I just want to find where to starts, and know wether I have seen enough in class to solve this problem or not.
Thanks for your help!

A: Let $u_1,u_2$ be the free generators of $M$, then every element of $M$ can be uniquely expressed as $\alpha_1u_1+\alpha_2u_2$ with $\alpha_1,\alpha_2\in A$.
Also, any homomorphism from $M$ is determined by the images of $u_1$ and $u_2$ which can be arbitrary.
So, an endomorphism $\varphi:M\to M$ can be encoded in a $2\times 2$ matrix with entries in $A$, namely let
$$[\varphi]=\pmatrix{\alpha&\beta\\ \gamma&\delta}$$
mean that $\varphi(u_1)=\alpha u_1+\gamma u_2$ and $\varphi(u_2)=\beta u_1+\delta u_2$.
Then $\det\varphi=\alpha\delta-\beta\gamma$, and addition of endomorphisms simply correspond to addition of matrices.

 We simply open up the brackets here:
 $$\det\pmatrix{\alpha+\alpha'&\beta+\beta'\\ \gamma+\gamma'&\delta+\delta'}\ +\ \det\pmatrix{\alpha-\alpha'&\beta-\beta'\\ \gamma-\gamma'&\delta-\delta'}\ = $$
$$=\ (\alpha+\alpha')(\delta+\delta')-(\beta+\beta')(\gamma+\gamma')\ +\ (\alpha-\alpha')(\delta-\delta')-(\beta-\beta')(\gamma-\gamma')\ =\ \dots $$


text:
Q: Fortran IO files I am writing some procedures for IO in fortran.
Am getting a bit confused regarding formatted, unformatted, sequential and direct.
As I understand formatted files are human readable (normal txt files), whereas unformatted ones are machine readable.
For unformatted files, I can use either sequential or direct access.
Can I have direct access of formatted files.

A: Yes, you can have direct access of formatted files.
From the Fortran 2008 Standard, Cl. 9.3.3.3 "Direct access":

2 When connected for direct access, an external file has the following
  properties.

*

*[...]

*The records of the file are either all formatted or all unformatted.
  If the sequential access method is also a member of the set of allowed
  access methods for the file, its endfile record, if any, is not
  considered to be part of the file while it is connected for direct
  access. If the sequential access method is not a member of the set of
  allowed access methods for the file, the file shall not contain an
  endfile record.


text:
Q: Modifying X-Forwarded-For HTTP Header in Python I am trying to make a request on my  website using modified headers but there is a header part called "X-Forwarded-For:"
they all having the same IP's Can I modify the X-Forwarded-for header
this were my code for the http request
import urllib2,cookielib

cj = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
opener.addheaders = [('X-Forwarded-For','1.2.3.4'),]
resp=opener.open('http://example.com')

the result I am getting is
HTTP headers:
Accept-Encoding: identity
Host: example.com
X-Forwarded-For: 182.19.2.180
X-Remote-Addr: 1.2.3.4
X-Forwarded-Proto: https
X-Https: on

but I am expecting
HTTP headers:
Accept-Encoding: identity
Host: la-developers.pro
X-Forwarded-For: 1.2.3.4
X-Remote-Addr: 1.2.3.4
X-Forwarded-Proto: https
X-Https: on


text:
Q: how to get UserController.CreateUser(userinfo) procedure in dnn? I have 2 DNN sites. I need to synchronize user table while registering user in one.
ie. if a user register at site 1, that user will be available in site 2.
 So I need to use the query behind

UserController.CreateUser(userInfo).

A: You have to create entries in UserProtal table, so for example, you have two portals with id 0 and 1. If user registers to portal 0, UserController.CreateUser will create entry in UserPortal table with portal 0 and new userid. Once user is created, you have to create same kind of entry for portal 1 and new userid in same table.
Let me know if you have any other question on this


text:
Q: How to set Visual Studio Code Terminal output to English My environment is:

*

*Visual Studio Code: English

*Windows 10: Japanese

When I try to use Terminal to add package, it output messages in Japanese.
But I would like it to output them in English.

A: For Windows

*

*go to visual studio code

*Press Ctrl+Shift+P to bring up the Command Palette then start typing "display"
to filter and display the Configure Display Language command.

*open local.json file

*You can use IntelliSense (Ctrl+Space) to select a different supported language locale.

*Change to en

*Restart Visual Studio Code

A: I have found the solution.
Because the terminal uses PowerShell, we should set the powershell's output.
Here it is:

*

*execute the command "set-culture -cultureinfo en-US" in terminal

*restart vscode

*execute "get-culture" in the terminal and confirm the output just like this:

LCID             Name             DisplayName
----             ----             -----------
1033             en-US            英語 (米国)

A: For ubuntu / Linux
Edit two files:

*

*sudoedit /etc/default/locale
LANG="en_US"

LANGUAGE="en_US:en"

*sudoedit ~/.pam_environment
LANG=en_US

LANGUAGE=en_US

Logout and Login or Reboot.

A: I'm on linux but having the same problem.
What works for me is to check terminal > integrated: inherit env in vscode.

A: I had the same issue.
I found the solution here https://github.com/dotnet/sdk/issues/8686
It was fixed by setting the environmental variable "DOTNET_CLI_UI_LANGUAGE" to "en"


text:
Q: How to make url that open in Safari for iOS Facebook Messenger app instead of in-app web browser [iOS] I'd like to make facebook messenger bot that sends a URL. Once the URL is tapped, I want it to open the URL in native safari.app instead of an in-app browser in Messenger.app. I tried Safari-search URL scheme, but it doesn't work. Is there any way to open native safari by modifying URL without modifying iOS native source code because, you know, I can't make any change for FB messenger native app?
Typical scenario:

*

*I am managing bot and send FB message with amazon product URL, let's say, https://www.amazon.com/gp/product/B00T85PMWY/.

*The receiver tap the url.

*Safari will open and show the page.

A: Open Facebook url in Safari instead of native app     go get your answer


text:
Q: How to copy a file from one HDFS folder to another HDFS folder using Java API? Using the HDFS java API I can rename (move) a file in HDFS.  Is there a way to copy the file?  I'm not interested in distcp, I'm going to copy a single file.

A: As per documentation page, you can use org.apache.hadoop.fs.FileUtil API
public static boolean copy(FileSystem srcFS,
           Path src,
           FileSystem dstFS,
           Path dst,
           boolean deleteSource,
           boolean overwrite,
           Configuration conf)
                    throws IOException

Copy files between FileSystems.

You can get FileSystem with below API
final FileSystem fs = FileSystem.get(conf);

and pass it ti above api


text:
Q: Package libdw was not found in the pkg-config search path I'm trying to build a Rust based gstreamer plugin. but I got these errors:
The following warnings were emitted during compilation:

warning: `"pkg-config" "--libs" "--cflags" "gstreamer-1.0" "gstreamer-1.0 >= 1.14"` did not exit successfully: exit status: 1

error: failed to run custom build command for `gstreamer-sys v0.17.0 (https://gitlab.freedesktop.org/gstreamer/gstreamer-rs#d203745c)`

Caused by:
  process didn't exit successfully: `/home/saeed/clean/media-plugins/target/release/build/gstreamer-sys-ce7fd93e56356a79/build-script-build` (exit status: 1)
  --- stdout
  cargo:rerun-if-env-changed=GSTREAMER_1.0_NO_PKG_CONFIG
  cargo:rerun-if-env-changed=PKG_CONFIG
  cargo:rerun-if-env-changed=GSTREAMER_1.0_STATIC
  cargo:rerun-if-env-changed=GSTREAMER_1.0_DYNAMIC
  cargo:rerun-if-env-changed=PKG_CONFIG_ALL_STATIC
  cargo:rerun-if-env-changed=PKG_CONFIG_ALL_DYNAMIC
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_PATH
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_LIBDIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64-unknown-linux-gnu
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR_x86_64_unknown_linux_gnu
  cargo:rerun-if-env-changed=HOST_PKG_CONFIG_SYSROOT_DIR
  cargo:rerun-if-env-changed=PKG_CONFIG_SYSROOT_DIR
  cargo:warning=`"pkg-config" "--libs" "--cflags" "gstreamer-1.0" "gstreamer-1.0 >= 1.14"` did not exit successfully: exit status: 1
  --- stdout

  --- stderr
  Package libdw was not found in the pkg-config search path.
  Perhaps you should add the directory containing `libdw.pc'
  to the PKG_CONFIG_PATH environment variable
  Package 'libdw', required by 'gstreamer-1.0', not found
  Package 'libdw', required by 'gstreamer-1.0', not found

warning: build failed, waiting for other jobs to finish...
error: build failed

The last lines say I need to install libdw, but I couldn't find any library like libdw. My box is Red Hat Enterprise Linux release 8.4

A: On Red Hat Enterprise I had to install this package:
sudo yum install elfutils-devel


text:
Q: How can I update my XAML while a database operation is ongoing and then update it again after it's finished? My intention is that when a button is pressed an activity indicator will display on the screen immediately and then a database query will happen. Once the query is completed a XAML grid is created, the activity indicator will be removed and the new XAML grid added. In practice this is all working but often the activity indicator does not show so I am wondering if I have the way I coded this wrong.
I have a button that causes an UpdateDetails method to fire:
    private async Task UpdateDetails()
    {
        details.Children.Clear();
        details.Children.Add(Helpers.Activity.Create());

        var newGrid = doLongRunningDatabaseTaskandCreateXAML();

        details.Children.Clear();
        details.Children.Add(Helpers.Activity.Create(newGrid);
    }

Can someone advise me How I can make the activity indicator display first until the database operation has completed and then have the newGrid appear? Note that what's most important is for the activity indicator to show while the database operation and creation of newGrid is ongoing.
If possible can you please include the code above in your answer so as to make it as clear as possible.  Thank you

A: Well, its simple:

*

*Make your method synchronous

*Add the code that you don't want on UI thread in an async Task.Run
   Task.Run(async () =>
            {
               //Your piece of code
            }

*Now when you want to update the UI just write that part of the code in MainThread using the following
 Device.BeginInvokeOnMainThread(() => { //UI updation });

Update
Your code should look something like this:
 private async Task UpdateDetails()
{
       Task.Run(async () =>
        {
         Device.BeginInvokeOnMainThread(() => { details.Children.Clear();
         details.Children.Add(Helpers.Activity.Create());});

         var newGrid = await doLongRunningDatabaseTaskandCreateXAML();

         Device.BeginInvokeOnMainThread(() => {  details.Children.Clear();
         details.Children.Add(Helpers.Activity.Create(newGrid);});
       }
}

Note that if doLongRunningDatabaseTaskandCreateXAML is of the type async task then you do not need to use the Task.Run method at all.


text:
Q: try/except not catching future's TimeoutError Could someone pls explain to me what's going on here ?
I wanted to add a message to the timeout error:
future = asyncio.run_coroutine_threadsafe(do_stuff(), loop=loop)
try:
    return future.result(timeout=3)
except TimeoutError:
    raise TimeoutError("Time out occurred while doing stuff")

future.results() (concurrent.futures._base.py) looks like this :
def result(self, timeout=None):
    # bla bla bla
    else:
        raise TimeoutError()

However when the timeout occurs my try/except clause doesn't catch the Timeout. In fact
future = asyncio.run_coroutine_threadsafe(do_stuff(), loop=loop)
try:
    return future.result(timeout=3)
except Exception as e:
    log.error(str(e))

shows empty e. WTH?

A: OK. I know. I should be using except asyncio.TimeoutError:, not the base TimeoutError.


text:
Q: Are there any hotkeys in dash for choosing among search term matches? Are there any hotkeys for dash, once a search term has been entered?
For example, if I would like to go to a folder very quickly I would want to press super+f to open the dash and then type the name...
I then must type tab ↓ ↓ so that folders are chosen. Then I must hit tab again to get focus on the folder list!
Is there a hotkey for this searching only folders for example?

A: You can hit Enter after typing your query to launch the first match, you can also hit Enter Enter in quick succession to launch the first thing it matches whether it renders it in the dash or not (sort of like "I'm feeling lucky").
As far as I can tell, that's currently the only shortcut.

A: It's not a hotkey, but you could script searching for folders with xdotool .
# invoke the files lens
xdotool key Super+f
# wait for the dash to show
sleep 0.5s
# navigate the menu
xdotool key Tab Down Down Shift+Tab

You could save that as a bash script and then set a custom keyboard shortcut in CompizConfig Settings Manager. (See the Commands plugin.)


text:
Q: Netty cuts off received WebSocket message at 4096 bytes I have a WebSocket client in netty, and I receive a large frame from the server (~90kb). When doing this with OkHttp everything works, while receiving with netty (4.1.11.Final) the message always gets cut off at 4096 no matter my options.
Here is the code to setup the client:
SslContext sslCtx = SslContextBuilder.forClient().build();

final WebSocketClientHandler handler = getWebSocketClientHandler(WebSocketClientHandshakerFactory.newHandshaker(
                    uri, WebSocketVersion.V13, null, true, new DefaultHttpHeaders()),
                    this::messageHandler);

Bootstrap b = new Bootstrap();
b.group(eventLoopGroup)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, Math.toIntExact(connectionTimeout.toMillis()))
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(sslCtx.newHandler(ch.alloc(), host, port));

                            WebSocketClientExtensionHandler clientExtensionHandler = getWebSocketClientExtensionHandler();
                            List<ChannelHandler> handlers = new ArrayList<>(4);
                            handlers.add(new HttpClientCodec(500_000, 504_000, 504_000, false, false, 504_000));
                            handlers.add(new HttpObjectAggregator(500_000));
                            handlers.add(handler);
                            handlers.add(WebSocketClientCompressionHandler.INSTANCE);
                            p.addLast(handlers.toArray(new ChannelHandler[handlers.size()]));
                        }
                    });

Am I forgetting something obvious?

A: Your WebSocketClientHandler is before the compression handler in the pipeline. If the server is sending you compressed messages, you're probably seeing smaller frame sizes (compared to the original, uncompressed message) in your handler. Put the compression handler before your WebSocketClientHandler.