text:
Q: Is there any possible way to take image option from R.drawable. instead of my xml file? i am working on a flipper image and in this app image is taking from xml file, i want to take image from R.drawable recourse folder and also in this app has to button "Play" and "Pause" that are working from xml, is there any way to make this slide show from resource folder? Any help will be appreciated.
My java code:
Public class MainActivity extends Activity {
private static final int SWIPE_MIN_DISTANCE = 120;
private static final int SWIPE_THRESHOLD_VELOCITY = 200;
private ViewFlipper mViewFlipper;
private AnimationListener mAnimationListener;
private Context mContext;
  @SuppressWarnings("deprecation")
  private final GestureDetector detector = new GestureDetector(new SwipeGestureDetector());
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

 mContext = this;
 mViewFlipper = (ViewFlipper) this.findViewById(R.id.view_flipper);
 mViewFlipper.setOnTouchListener(new OnTouchListener() {
    @Override
 public boolean onTouch(final View view, final MotionEvent event) {
        detector.onTouchEvent(event);
        return true;
    }

 findViewById(R.id.play).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        //sets auto flipping
        mViewFlipper.setAutoStart(true);
        mViewFlipper.setFlipInterval(4000);
        mViewFlipper.startFlipping();
    }
});

findViewById(R.id.stop).setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        //stop auto flipping
        mViewFlipper.stopFlipping();
    }
});

//animation listener
mAnimationListener = new Animation.AnimationListener() {
    public void onAnimationStart(Animation animation) {
        //animation started event
    }

    public void onAnimationRepeat(Animation animation) {
    }

    public void onAnimationEnd(Animation animation) {
        //TODO animation stopped event
    }
 };
}
   class SwipeGestureDetector extends SimpleOnGestureListener {
  @Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
    try {
        // right to left swipe
        if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_in));
            mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext, R.anim.left_out));
            // controlling animation
            mViewFlipper.getInAnimation().setAnimationListener(mAnimationListener);
            mViewFlipper.showNext();
            return true;
        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            mViewFlipper.setInAnimation(AnimationUtils.loadAnimation(mContext, R.anim.right_in));
            mViewFlipper.setOutAnimation(AnimationUtils.loadAnimation(mContext,R.anim.right_out));
            // controlling animation
            mViewFlipper.getInAnimation().setAnimationListener(mAnimationListener);
            mViewFlipper.showPrevious();
            return true;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return false;
  }
 }
}

My XML:
 <?xml version="1.0" encoding="utf-8"?>
 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="fill_parent"
 android:layout_height="fill_parent"
 android:orientation="vertical" >

<ViewFlipper
android:id="@+id/view_flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >

 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
 <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:src="@drawable/p1" />
    <TextView
        android:id="@+id/textView1"
        style="@style/ImageTitle"
        android:text="@string/text1" />
</RelativeLayout>

 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:src="@drawable/p2" />
    <TextView
        style="@style/ImageTitle"
        android:text="@string/text2" />
 </RelativeLayout>

 <RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <ImageView
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_gravity="center"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"
        android:src="@drawable/p3" />
    <TextView
        style="@style/ImageTitle"
        android:text="@string/text3" />
  </RelativeLayout>
 </ViewFlipper>

  <LinearLayout
style="@style/ButtonContainer"
android:orientation="horizontal" >

<Button
    android:id="@+id/play"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginRight="10dp"
    android:background="@android:drawable/ic_media_play" />
<Button
    android:id="@+id/stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:drawable/ic_media_pause" />
</LinearLayout>

<ImageView
android:id="@+id/swipe_left"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="@drawable/back" />

<ImageView
android:id="@+id/swipe_right"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="@drawable/next" />
</RelativeLayout>

A: i think i could do something like this:
public class Level1ScreenView extends SurfaceView implements Runnable {

SurfaceHolder holder;
Bitmap flipper2;
Paint paint = new Paint();

public Level1ScreenView(Context context){
super(context);

    flipper2= BitmapFactory.decodeResource(getResources(),R.drawable.p2);

    @SuppressLint("DrawAllocation")
        protected void onDraw(Canvas canvas){

            canvas.drawBitmap(flipper2, 0, 0, paint);  // first 0 is x, second 0 is y
    }

    @SuppressLint("WrongCall")
    public void run() {
        while (ok == true){
            //perform canvas drawing
            if(!holder.getSurface().isValid()){//if surface is not valid
                continue;//skip anything below it
            }

            Canvas c = holder.lockCanvas(); //Lock canvas, paint canvas, unlock canvas
            this.onDraw(c);
            holder.unlockCanvasAndPost(c);}

}}

by the way, programmatic or by xml, the images are coming from the same folder drawable.


text:
Q: pycharm: How do I import pyspark to pycharm I have done quite some spark job in Java/Scala, where I can run some test spark job directly from main() program, as long as I add the required spark jar in the maven pom.xml.
Now I am starting to work with pyspark. I am wondering if I could do something similar? For example, I am using pycharm to run a the wordCount job:

If I just run the main() program, I got the following error:
Traceback (most recent call last):
  File "/Applications/PyCharm.app/Contents/helpers/profiler/run_profiler.py", line 145, in <module>
    profiler.run(file)
  File "/Applications/PyCharm.app/Contents/helpers/profiler/run_profiler.py", line 84, in run
    pydev_imports.execfile(file, globals, globals)  # execute the script
  File "/Users/edamame/PycharmProjects/myWordCount/myWordCount.py", line 6, in <module>
    from pyspark import SparkContext
ImportError: No module named pyspark

Process finished with exit code 1

I am wondering how do I import pyspark here? so I could run some test job from the main() program like I did in Java/Scala.
I also tried to edit the interpreter path:

and my screenshot from Run -> Edit Configuration:

Last is my project structure screen shot:

Did I miss anything here? Thanks!

A: I finally got it work following the steps in this post. It is really helpful!
https://medium.com/data-science-cafe/pycharm-and-apache-spark-on-mac-os-x-990af6dc6f38#.jk5hl4kz0

A: I added the py4j-x.x.x-src.zip and pyspark.zip under $SPARK_HOME/python/lib to the project structure (preferences > Project> Project Structure and then do "+ Add Content Root") and it worked fine.
PS: Pycharm already had $PYTHONPATH and $SPARK_HOME read from the os env, which was set in .bashrc/.bash_profile

redpajama_set_name: RedPajamaStackExchange


text:
Q: Invalid header name in HTTP request I'm manually making the following request using sockets in C++.
struct addrinfo hints, *res;
int sockfd;

char buf[2056];
int byte_count;

//get host info, make socket and connect it
memset(&hints, 0,sizeof hints);
hints.ai_family=AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
getaddrinfo("some_web_service.azurewebsites.net","80", &hints, &res);
sockfd = socket(res->ai_family,res->ai_socktype,res->ai_protocol);

char *header = "POST /api/factura HTTP/1.1\n"
"Host: some_web_service.azurewebsites.net\n"
"Content-Type: application/json\n"
"Accept: */*\n"
"Cache-Control: no-cache\n"
"Content-Length: 1188\n"
"{\"IdTransaccion\": \"6828836174244758\",\"InstitucionFinanciera\": \"Banco Azteca\",\"NumTarjeta\": \"0077\",\"Fecha\":\"2019-10-06T17:00:00\",\"SubTotal\": \"2000.00\",\"Moneda\": \"MXN\",\"Total\": \"2320.00\",\"TipoDeComprobante\": \"I\",\"FormaPago\": \"01\",\"MetodoPago\": \"PUE\",\"LugarExpedicion\": \"06300\",\"Emisor\": {\"Rfc\": \"LAN8507268IA\",\"Nombre\": \"Banco Azteca, S.A de C.V.\",\"RegimenFiscal\": \"601\"},\"Receptor\": {\"Rfc\": \"VEV0603275K9\",\"Nombre\": \"Test Receptor\",\"UsoCFDI\": \"G03\"},\"Conceptos\":{\"Concepto\":[{\"ClaveProdServ\":\"84111506\",\"ClaveUnidad\":\"E48\",\"Cantidad\":\"1\",\"Descripcion\":\"Producto1\",\"ValorUnitario\":\"1000.00\",\"Importe\":\"1000.00\",\"Impuestos\":{\"Traslados\":{\"Traslado\":{\"Base\":\"1000.00\",\"Impuesto\":\"002\",\"TipoFactor\":\"Tasa\",\"TasaOCuota\":\"0.160000\",\"Importe\":\"160.00\"}}}},{\"ClaveProdServ\":\"01010101\",\"ClaveUnidad\":\"E48\",\"Cantidad\":\"1\",\"Descripcion\":\"Producto2\",\"ValorUnitario\":\"1000.00\",\"Importe\":\"1000.00\",\"Impuestos\":{\"Traslados\":{\"Traslado\":{\"Base\":\"1000.00\",\"Impuesto\":\"002\",\"TipoFactor\":\"Tasa\",\"TasaOCuota\":\"0.160000\",\"Importe\":\"160.00\"}}}}]},\"Impuestos\":{\"TotalImpuestosTrasladados\":\"320.00\",\"Traslados\": {\"Traslado\": {\"Impuesto\": \"002\",\"TipoFactor\": \"Tasa\",\"TasaOCuota\": \"0.160000\",\"Importe\": \"320.00\"}}}}\n";

send(sockfd,header,strlen(header),0);

//all right ! now that we're connected, we can receive some data!
byte_count = recv(sockfd,buf,sizeof(buf),0);
byte_count = recv(sockfd,buf,sizeof(buf),0);

But the message received is:
HTTP/1.1 400 Bad Request
Content-Type: text/html; charset=us-ascii
Date: Mon, 07 Oct 2019 21:34:20 GMT
Connection: close
Content-Length: 339

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd">
<TITLE>Bad Request</TITLE>
<META HTTP-EQUIV="Content-Type" Content="text/html; charset=us-ascii">

Bad Request - Invalid Header

HTTP Error 400. The request has an invalid header name.

Can anyone tell me what I'm doing wrong with my headers? I already tried using \r\n instead of \n but that doesn't seem to do nothing.

A: I believe you're missing an empty line between your headers and message body. Per the RFC (https://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4):

Request (section 5) and Response (section 6) messages use the generic
  message format of RFC 822 [9] for transferring entities (the payload
  of the message). Both types of message consist of a start-line, zero
  or more header fields (also known as "headers"), an empty line (i.e.,
  a line with nothing preceding the CRLF) indicating the end of the
  header fields, and possibly a message-body.

Try adding an extra \n after your last header line:
"Content-Length: 1188\n\n"

To ensure compatibility with applications that adhere strictly to the RFC, you should use \r\n (CRLF) as mentioned in the quote!


text:
Q: Word or expression for "someone using fake kindness to hide something or his true nature" It's someone who tends to be a nice person but hides something or there is something off about him. Sometimes, you meet this kind of people and you know that his/her kindness hides a darker side.
I thought about sly or shady but they seem a bit too much, however I might be wrong. Is deceitful the correct term or is there a more specific one?

Example :
"I don't like the new boss, his kindness hides something"
" I don't like the new boss, he is _____"

A: As an adjective, I would like to use
hypocrite
hypocritical
insincere
double
double-faced
two-faced
double-tongued
On the other hand, as a noun , I would use
dissembler
prig
pharisee
double-dealer

A: How about "two-faced"?
two-faced is an adjective you can use to someone who acts one way at a certain time/situation but acts differently at another time/situation.

A: Sometimes, the answer is right under our noses. At least in my case, I would refer to this person as fake.
It requires some understanding of connotation, but in this case it lends itself quite easily:

"I don't like the new boss, his kindness hides something. Does he not seem fake to you?"

A: The first word that I thought of was smarmy:

*

*smarmy - revealing or marked by a smug, ingratiating, or false earnestness
Also obsequious, although this implies that the speaker is a sycophant:

*

*obsequious - marked by or exhibiting a fawning attentiveness

A: "Dissembler" might fit your requirement. Though you might have to tweak the sentence a bit.
"I don't like the new boss, he seems to be a dissembler."
This is because "seems to be" adds the connotations of having picked up such vibes from the person. "Is" implies more of a certain pronouncement on the character of the person.

A: The entire thinking error goes kinda like this..."hides behind acts of kindness to commit atrocities." Now this is not exactly the way I saw it written which is why I'm asking.

A: When the thing the person is hiding is an intent to do you harm, we have the specific phrase:

wolf in sheep's clothing.


text:
Q: How do you solve a system of equations in the form $x+y=3, xy=4$? I am trying to factor this polynomial:
$x^2+3x+4$.
and couldn't think of any integer solution (I don't think there is a real solution either) so I created this system of equations.
$x+y=3$ and $xy=4$.
The only problem is, I have no idea how to solve a system of this form. Please use terms that an Algebra 1 student would understand.

A: Let $s$ be the sum and $p$ the product.
Then write $x=\dfrac s2+z$ and $y=\dfrac s2-z$, so that $x+y=s$, and from $xy=p=\dfrac{s^2}4-z^2$ you can draw $z$.


text:
Q: Cancel events from a legacy form I have a main form that has buttons, the role of one of them in disabling all controls of the form in general.
I also have a child form that inherits the buttons and the actions of them, as I could prevent the events of the parent form at a certain point from running that is, temporarily remove the event, for example if the user has a text and does not fill it out and gives the button I do not want anything to be disabled
I think there is a way in c# that like the "eventname"=- I don't remember well
This is an example of my base or parent form, with a button that does actions
Parent Form
namespace WindowsFormsApp1
{
    public partial class BaseMantenimiento1 : DevExpress.XtraEditors.XtraForm
    {
        public BaseMantenimiento1()
        {
            InitializeComponent();
        }

        private void BaseMantenimiento1_Load(object sender, EventArgs e)
        {
            Guardar.Enabled = false;
            Cancelar.Enabled = false;
            controles.habilitarcontroles(false, xtraTabControl1);
        }

        private void Nuevo_Click(object sender, EventArgs e)
        {
            Guardar.Enabled = true;
            Cancelar.Enabled = true;
            Editar.Enabled = false;
            Buscar.Enabled = false;
            Nuevo.Enabled = false;

            controles.habilitarcontroles(true, xtraTabControl1);

        }

This is my child form with its basic code
child form
 public partial class Mantenimiento_Empresas : BaseMantenimiento1
    {
        public Mantenimiento_Empresas()
        {
            InitializeComponent();
        }

What I wanted was that if in the child form I gave the button save, but they did not fill the textbox well, then the event that this inherits from its parent form is not executed, so I took the event and then below if everything is fine I trigger the event of the parent with
base.Save_Click(null, null);

A: I found what I was looking for, in the same space where the components are initialized I must place the following
public Mantenimineto_Bicicletas()
{
    InitializeComponent();
   Save.Click -= base.Save_Click;
}


text:
Q: How to limit choices to Foreign keys in Django admin I run into a problem when using the Django admin. I'm building a small ScrumBoard. It has projects, with statuses, stories and tasks.
Consider the following model:
@python_2_unicode_compatible
class Project(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name = _('Project')
        verbose_name_plural = _('Projects')

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Status(models.Model):
    name = models.CharField(max_length=64) # e.g. Todo, In progress, Testing Done
    project = models.ForeignKey(Project)

    class Meta:
        verbose_name = _('Status')
        verbose_name_plural = _('Statuses')

    def __str__(self):
        return self.name

@python_2_unicode_compatible
class Story(models.Model):
    """Unit of work to be done for the sprint. Can consist out of smaller tasks"""
    project = models.ForeignKey(Project)
    name=models.CharField(max_length=200)
    description=models.TextField()
    status = models.ForeignKey(Status)

    class Meta:
        verbose_name = _('Story')
        verbose_name_plural = _('Stories')

    # represent a story with it's title
    def __str__(self):
        return self.name

The problem: when an admin user creates a story he will see statuses from all the projects instead of the status from one project.

A: To filter statuses by project, you need your story to already exist so django know which project we are talking about. If you set status nullalble, you can do like this (implying, you do save and continue on first save to set status)
class StatusAdmin(admin.ModelAdmin):
    def get_form(self, request, obj=None, **kwargs):
        form = super(StatusAdmin, self).get_form(request, obj, **kwargs)
        if obj and obj.project:
            form.base_fields['status'].queryset = \
                form.base_fields['status'].queryset.filter(project=obj.project)
        elif obj is None and 'status' in form.base_fields: # on creation
            del form.base_fields['status']
        return form

A: You will need something like django-smart-selects


text:
Q: Determine if the data is new before running (Compare an array with JSON) Alright, I've got an interesting issue.  My page makes a JSON request every once in a while.  If the data hasn't changed, it doesn't need to do anything.  The problem is, I can't figure out a way to prove if it has changed or not.
I tried something like this to no avail:
var stations = null;
function parseDynamicData(ard) {
    //this was something that gave me problems for days
    //nice little hack to fix it
    if (ard['details']['enabled'] == 'true' && ard['song']['art'] != 'undefined');
    {
        //turns off the 'server offline' page
        if (document.location.toString().indexOf('#offline') != -1)
            document.location = '/#tracks';
        //update UI
        $('#track-title').html(htmlDecode(ard['song']['title']));
        $('#track-artist').html(htmlDecode(ard['song']['artist']));
        $('#track-album').html(htmlDecode(ard['song']['album']));
        $('#track-art').attr('src', htmlDecode(ard['song']['art']));
        //set if it's play or pause visible
        if (htmlDecode(ard['details']['playing']) == 'true') {
            $('#control-pauseplay').html('Pause');
            $('#control-pauseplay').attr('href', '/track?proc=2');
        } else {
            $('#control-pauseplay').html('Play');
            $('#control-pauseplay').attr('href', '/track?proc=3');
        }
        //Now update all of the stations
        if (stations == null || stations != ard['stations']) {
            $.each(ard['stations'], function (key, value) {
                alert(key);
            });
            stations = ard['stations'];
        }
    }
}

Here is what a normal JSON response looks like:
{
    "song": {
        "art": "http://cont-sjl-1.pandora.com/images/public/amz/6/2/3/3/886978533326_500W_500H.jpg",
        "title": "Hold It Against Me",
        "artist": "Britney Spears",
        "album": "Femme Fatale Deluxe"
    },
    "details": {
        "playing": "true",
        "enabled": "true"
    },
    "stations": {
        "undefined": "False",
        "Alex Clare Radio": "False",
        "Rap Strength Training Radio": "False",
        "Drops Of Jupiter Radio": "False",
        "Tween Radio": "False",
        "Today's Hits Radio": "True"
    }
}

No matter what I do, however, it still goes through the JSON making an alert for every key.  Does anybody know what I should do?

A: You could try using JSON.Stringify? Obviously what you get back from the JSON request is JSON, and I assume that you've converted the last request into an actual Object. So just call:
JSON.Stringify(Object) === JSONresult

and compare the two strings.

A: I suspect that stations and ard['stations'] are different objects that are identical in structure.  If you are rebuilding ard after each JSON request while stations holds the array from the previous ard, then the two objects are not the same object, so an exact match will fail, regardless whether the objects have identical key-value pairs.
What I would do is keep a exact string copy of the last JSON message and compare it with the current JSON string message before you parse it.  Otherwise, you'll need to compare every single key-value pair of the current object against the prospective new one -- and if some of those values are objects themselves, things could get a little (needlessly) hairy.
If you can be certain that the server will always stringify a given object O the same way (and assming you don't need to worry about checking if an object on the client has mutated), then you can simply compare the JSON string versions of the object from the server.


text:
Q: Obtaining a vector of words within a string beginning with a pattern - R I want to get a vector of the words within a string in R that begins with $`GPE.
This is what I tried:
grep(pattern = "$`GPE", x = GPE_string, value = TRUE)

However it returned: character(0)

A: You can do this using str_extract_all in stringr:
library(stringr)
str_extract_all(GPE_string, "(\\$`GPE.+?)\\b")

Explanation:

*

*The $ in the pattern needs to be escaped with \\

*The part enclosed in (...) will be extracted

*\\b means word boundary, and .+? means one or more characters

The result of str_extract_all is a list of vectors,
for each string in the input vector.

A: You need escape characters.
Try
grep(pattern="\$\`GPE", x=GPE_string, value=TRUE)

A: If you're only looking for the words that start with "$`GPE", you can do:
GPE_string[startsWith(GPE_string, "$`GPE")]

So for example,
> GPE_string<- c("$`GPE_Hello", "$`GPEWorld", "Hello", "World")
> GPE_string
[1] "$`GPE_Hello" "$`GPEWorld"  "Hello"       "World"
> GPE_string[startsWith(GPE_string, "$`GPE")]
[1] "$`GPE_Hello" "$`GPEWorld"


text:
Q: mongoose count() function with regex case insensitive matching sub string also I am trying to find out a simple solution to handle case sensitive email using regex, so far it works good when inserting/querying the document using Mongoose but when I'm validating if the user exists using the Model.count method, its not working as expected.
I have defined this static function in the schema, which takes the username and return the count of occurance in the collection.
userSchema.statics.exist = function(username, cb){
  this.count({ "username": new RegExp(username, "i") }, cb);
};

and I have a controller function which calls this static like this:
userExist: function (req, res) {
  UserModel.exist(req.body.username, function (err, count) {
      res.json({exist: count});
  });
}

if I pass user@example.com in the req.body.username field ( where user@example.com exist in the database), it returns 1
but its returning 1 even if I enter I enter user@examp or user@exampl or  user@example.c
Not sure what I'm doing wrong, I thought it may be issue with regex, so I tested this regex for validity:
var username = "user@example.com";
var pattern = new RegExp(username, "i");
pattern.match("user@examp");  // this returns false

Any help is appreciated. Thanks !

A: I was able to solve this issue by changing the regex a little bit like this:
userSchema.statics.exist = function(username, cb){
  this.count({ "username": new RegExp('^'+username+'$', 'i') }, cb);
};

Hope this helps someone. Any other suggestions are welcome


text:
Q: Sockets Vs. WCF I work on a chat-like application, where I use Silverlight on the client side and wpf on the server side. Right now the communication is based on Sockets: I have different Message-Classes which I serialize and send via TCP.
I start realizing that creating a seperate Message Class for each possibile communication scenario is quite an overhead and consider moving to WCF.
Therefore I need to know the following things:

*

*It seems that the whole communication using WCF is based on the clients callind exposed methods from my WCF service. Is there a way of knowing which client calls a certain method? This is quite important for my application.

*Does WCF notify my application, when a client disconnects (e.g. closes the browser window where the Silverlight client is running) from the server? This too is quite important.

*Are the method calls completely asynchronous? If so, do I have to reroute each method call to the main thread of the server application?

*Does every client connection has its own thread? How many simultaneous connections could the server (running on a reasonably powered PC) handle if the clients call methods say every 2 seconds? I just need a estimation (10, 100, 1000 or even more). "More" would be great ;)
Maybe I am completely wrong and WCF doesn't work connection-based at all. Then I would have to find a workaround to still manage a list of active connections.
Thanks for your help!
Andrej

A: *

*Since you are using a Silverlight application, you can implement a UserNamePassword Validator on the message layer, which adds some headers to the soap message, this could be used to uniquely identify clients, unless clients are anonymous. then you can use System.ServiceModel.OperationContext.Current, when you need to access the username elsewhere in the wcf service.

*The server is not notified when the client disconnets, since msgs are "PerCall" by default, there is a way, use a Singleton class as ur ServiceContract with InstanceContextMode.Single, then implement an OperationContract with a callback service, then when clients login to ur service they must register with the callback service, ur callback service can then cycle through connected clients and check the status of the callback, whether its still open or not, finally remove entries where the connections are closed, eventually you can get the functionality you require.

*Async calls, are from the client, ie. in Silverlight all webservice calls are async, like in ASP you have a choice, WCF handles the async functionality automatically, so you dont need to reroute anything, just code the ServiceContract like its a single thread, and everything will be fine

*Implement binary message encoding in silverlight 3, to get the most out of ur server and its bandwidth, silverlight does not support raw tcp connections, it has to be rapped in an http message for very good reasons. Each client can have many concurrent calls (async remember), so to keep things simple, just think of it as if the server assigns a separate thread to every message call. So to answer your question on what you just said, 1000.

A: For 3 i know You can call async.
And for 4 yes, they have their own threads. WCF is pretty "BIG" and complex, you should get a book to understand it better.

A: My answers:

*

*Yes. All communication is based on calling methods.

*In general - No.

*You can call methods synchronously or asynchronously. This is you choice.

*More. I case of right system design.


text:
Q: How to use async-await with WCF in VS 2010 for WP7? Async CTP is very nice to use.
I saw some examples for windows phone, all using:
(Assembly AsyncCtpLibrary_Phone.dll, v2.0.50727, AsyncCtpExtensions).
 var client = new WebClient();
 string data = await client.DownloadStringTaskAsync(new Uri(url));

or something like the above code.
How can I use methods with async / await for my services? (WCF)
Today all methods work this way:
  service.MyRequestCompleted += service_myRequestCompleted;
  service.MyRequestAsync();

I can not find a way to use extension methods for services.

A: Unfortunetly, I haven't found a good way to generalize this for any event, but it's easy enough to adapt this for a particular event:
public static Task WhenRequestCompleted(MyService service) //can make it an extension method if you want.
{
    TaskCompletionSource<object> tcs = new TaskCompletionSource<object>();

    service.MyRequestCompleted += () => //change parameter list to fit the event's delegate
        {
            tcs.SetResult(null);
        };
    service.MyRequestAsync();

    return tcs.Task;
}

Then you can do:
await WhenRequestCompleted(service);
//code that runs after the request is completed.

I assume you see the pattern here, so you could adapt this so that it would work with some other event on some other type.
Oh, and if the event has arguments that are particularly important to you then you could make this return a Task<T> instead of a Task and instead of using tcs.SetResult(null) you could use one of the parameters of the lambda to set the result.

A: It's been a while since I've worked on WP7, so I'm going to assume that the client proxy has both EAP endpoints (*Async + *Completed) and APM endpoints (Begin* + End*) for each contract method.
If that's correct, then you can use TaskFactory.FromAsync to wrap the Begin* / End* methods, as such:
[ServiceContract]
public interface ICalculator
{
  [OperationContract]
  uint Divide(uint numerator, uint denominator);
}

static class Program
{
  // Wrap those Begin/End methods into a Task-based API.
  public static Task<uint> DivideAsyncTask(this CalculatorClient client,
      uint numerator, uint denominator)
  {
    return Task<uint>.Factory.FromAsync(client.BeginDivide, client.EndDivide,
        numerator, denominator, null);
  }

  static async Task CallCalculator()
  {
    var proxy = new CalculatorClient();
    var task = proxy.DivideAsyncTask(10, 5);
    var result = await task;
    Console.WriteLine("Result: " + result);
  }

  static void Main(string[] args)
  {
    try
    {
      CallCalculator().Wait();
    }
    catch (Exception ex)
    {
      Console.Error.WriteLine(ex);
    }

    Console.ReadKey();
  }
}

You may be interested in one of my blog posts async WCF today and tomorrow - unfortunately, WP7 is still stuck in "today" mode. The Async CTP will probably be abandoned shortly now that VS2012 is out.


text:
Q: How to create content items/container programatically using dexterity? I have read the manual specifically on manipulating objects under dexterity. http://plone.org/products/dexterity/documentation/manual/developer-manual/reference/manipulating-content-objects/
What I want to do is programatically add contents (either item/container) to current container being created. To be more specific, I am creating a container/folder, once this container has been created it will automatically create items/folders under the parent folder (the one that is newly created manually).
I tried to use this similar code createContentInContainer(folder, 'content_type_name', title=u"title_here"), but i get an error on my instance that says "folder" is not defined. I would like to ask if how this snippet be inserted in the content type? Is it inside a defined function/method inside the class constructor, or how the "folder" should be initially declared/defined?
Thanks.

A: the answer seems pretty simple: your folder must be an existing instance of a folderish type. For instance:
new_id = plonesite.invokeFactory('Folder', 'some_id')
folder = plonesite[new_id]

from plone.dexterity.utils import createContentInContainer
createContentInContainer(folder, 'example.type', title=u"Foo")

HTH


text:
Q: Order jQuery Droppable Elements By Having Last Dropped Item First I did some searching and couldn't find an answer to this, plus did some messing around with the code to no avail. I have a standard jQuery UI draggable and droppable setup which works.
However when items (in this case shoes) are dragged into the droppable target area, they appear to be appended, so old items stay at the front and new items get added on the end and pushed out of view.
Is there a way of having the sortable items prepend to my target droppable as opposed to being appended?
 Edit **
var proto = $.ui.droppable.prototype;

proto._create = function() {

    console.log('Calling the create method');

    var o = this.options, accept = o.accept;
    this.isover = 0; this.isout = 1;

    this.accept = $.isFunction(accept) ? accept : function(d) {
    return d.is(accept);
    };

    //Store the droppable's proportions
    this.proportions = { width: this.element[0].offsetWidth, height: this.element[0].offsetHeight };

    // Add the reference and positions to the manager
    $.ui.ddmanager.droppables[o.scope] = $.ui.ddmanager.droppables[o.scope] || [];
    $.ui.ddmanager.droppables[o.scope].unshift(this);

    (o.addClasses && this.element.addClass("ui-droppable"));
};

A: Yes, though it's pretty complicated. You'll need to extend the JQueryUI ui.droppable object modifying the _create function. Currently it uses push to add your new item to the end of the array, like so:
$.ui.ddmanager.droppables[o.scope].push(this);
You'll want to use unshift:
$.ui.ddmanager.droppables[o.scope].unshift(this);
JQuery droppable source:
https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.droppable.js
JavaScript unshift() documentation:http://www.w3schools.com/jsref/jsref_unshift.asp
Tutorial for extending JQueryUI widgets: http://bililite.com/blog/extending-jquery-ui-widgets/


text:
Q: For every $H \subset \operatorname{Gal}(E / \mathbb{Q})$ find the fixed field $E^H$ Let $E$ be the splitting field of $x^3 - 2$ over $\mathbb{Q}$.
I proved that $E = \mathbb{Q}(\sqrt{2},\omega)$. Where $\omega$ is a primitive root of unity.
And I also know that $G := \operatorname{Gal}(E/ \mathbb{Q}) =S_3 $.
I find that
 $\mathbb{Q}(\sqrt{2},\omega)=\{a+b\sqrt{2}+c\omega+d\omega^2+e\sqrt{2}\omega+f\sqrt{2}\omega^2 : a,b,c,d,e,f \in \mathbb{Q}\}.$
A little intermediate question I have is if does that mean that the dimension of $\mathbb{Q}(\sqrt{2},\omega)$ over $\mathbb{Q}$ is $6$ right? (I also know this because [$E:\mathbb{Q}]=|\operatorname{Gal}(E/\mathbb{Q})|=|S_3|=6$).
So finding the dimension of $\mathbb{Q}(\alpha_1,\alpha_2,...,\alpha_n)$ over $\mathbb{Q}$ where $\alpha_i$ are specific and known, is as easy as count how many of the products of the $\alpha_i$ are in a different fields and express $\mathbb{Q}(\alpha_1,\alpha_2,...,\alpha_n)$ as a combination linear of these elements over $\mathbb{Q}$. Just as done with $\mathbb{Q}(\sqrt{2},\omega)$. Am I right?...
So let $H \subset G$ be, for example, the 3-cycle $\{\operatorname{id},(123),(132)\}$. In order to find  $E^H$ we see that if $x \in \mathbb{Q}(\sqrt{2},\omega)=\{a+b\sqrt{2}+c\omega+d\omega^2+e\sqrt{2}\omega+f\sqrt{2}\omega^2 : a,b,c,d,e,f \in \mathbb{Q}\}$ say
$x=a+b\sqrt{2}+c\omega+d\omega^2+e\sqrt{2}\omega+f\sqrt{2}\omega^2$ for specific $a,b,c,d,e,f \in \mathbb{Q}$
we must have $b=c=d$, $e=f$
since $(123)$ permutes every element of $\sqrt{2},\omega,\omega^2.$
So $E^H = \{a+b(\sqrt{2}+\omega+\omega^2)+e(\sqrt{2}\omega+\sqrt{2}\omega^2) : a,b,e \in \mathbb{Q}\} =\mathbb{Q}(\sqrt{2}+\omega+\omega^2,\sqrt{2}\omega+\sqrt{2}\omega^2)$
Is my reasoning correct?
Thank you very much in advance.

A: For a start, a $\Bbb Q$-basis of $E$ is $1$,
$\sqrt[3]2$, $\sqrt[3]4$, $\omega$, $\omega\sqrt[3]2$,
$\omega\sqrt[3]4$.
Let $H=\{\text{id},(123),(132)$. Then $E^H$ is the subset of $E$ fixed by $(123)$.
If we label the roots of $x^3-2=0$ as $\alpha_1=\sqrt[3]2$, $\alpha_2=\omega\sqrt[3]2$,
$\alpha_3=\omega^2\sqrt[3]2$, then $\sigma=(123)$ has $\sigma(\alpha_1)=\alpha_2$,
$\sigma(\alpha_2)=\alpha_3$ and $\sigma(\alpha_3)=\alpha_1$. This means that
$$\sigma(\sqrt[3]2)=\omega\sqrt[3]2$$
and
$$\sigma(\omega)=\sigma(\alpha_2/\alpha_1)=\alpha_3/\alpha_2=\omega.$$
Therefore
\begin{align}
&\sigma(a+b\sqrt[3]{2}+c\sqrt[3]{4}+d\omega+e\omega\sqrt[3]{2}+f\omega\sqrt[2]{4})\\
&=a+b\omega\sqrt[3]{2}+c\omega^2\sqrt[3]{4}+d\omega+e\omega^2\sqrt[3]{2}+f\sqrt[2]{4}\\
&=a+b\omega\sqrt[3]{2}+c(-1-\omega)\sqrt[3]{4}+d\omega+e(-1-\omega)\sqrt[3]{2}+f\sqrt[2]{4}\\
\end{align}
Therefore $\sigma$ fixes this element iff $b=-e$, $c=-c+f$, $e=b-e$ and $f=-c$.
These imply $b=c=e=f=0$ and so the element is $a+b\omega$. Thus
$E^H=\Bbb Q(\omega)$.
There are some obvious subfields of $E$, namely $E$, $\Bbb Q$ $\Bbb Q(\omega)$,
$\Bbb Q(\sqrt[3]2)$, $\Bbb Q(\omega\sqrt[3]2)$, $\Bbb Q(\omega^2\sqrt[3]2)$.
From Galois theory, do we expect any more?


text:
Q: Where is scanf() reading input from, if not from the keyboard? I'm a novice programmer getting introduced to C and I'm missing something fundamental about the way my scanf() works. I want to read a single int from the keyboard with code like this:
#include <stdio.h>
#include <stdlib.h>

int main(void) {
    int userBookSelection;
    scanf("%i", &userBookSelection);
    printf("Printing userBookSelection: %i", userBookSelection);

    return EXIT_SUCCESS;
}

When I run the code, the console stays black until I stop debugging. There is never a cursor waiting for keyboard input. When I stop debug I can see this output in the console, same every time:
Printing userBookSelection: 2130567168
I'm debugging in Eclipse with MinGW GCC compiler on Windows. The code syntax seems to be correct -- is it possible there's something wrong in my build path to make this happen? I need to know why scanf() isn't reading for keyboard input.

A: So I've gotten a line of code from my professor which takes care of this bug -- whether it's a necessary solution particular to Eclipse and/or MinGW I'm not sure. In any case, here's the code with the additional line:
int main(void) {
    int userBookSelection;
    setvbuf (stdout, NULL, _IONBF, 0);//<---The magic line

    scanf("%i", &userBookSelection);
    printf("Printing userBookSelection: %i", userBookSelection);

    return EXIT_SUCCESS;
}

I'd appreciate any additional wisdom on what's going on, what setvbuf() is doing and how scanf() works more fundamentally.


text:
Q: Method parameter must be obj of certain class that implements certain interface How to declare a method with parameter which must be same time a certain class which implements certain interface without declaring a special class for this?
Assume i have declared class ImageX and also declared interface Tagging. So I need to create some other class or method which has to receive only instances of ImageX which implements Tagging interface. How to declare such method? something like
private void someMethod (ImageX<Tagging> obj){}

but this is not correct of course. Yes I could check the obj if it implements needed interface but I want that check in parameters. And what if it is not some method but a constructor...
am I asking about generics maybe?

A: You can make the method generic and only accept objects that are both an ImageX and a Tagging by using a type intersection:
private <T extends ImageX & Tagging> void someMethod (T obj){}


text:
Q: String tokenizing to remove some data I have a string like this:
1 | 2 | 3 | 4 | 5 | 6 | 7 |  |  |  |  |  |  |  |

The string might have more/less data also.
I need to remove | and get only numbers one by one.

A: Guava's Splitter Rocks!
String input = "1 | 2 | 3 | 4 | 5 | 6 | 7 | | | | | | | |";
Iterable<String> entries = Splitter.on("|")
        .trimResults()
        .omitEmptyStrings()
        .split(input);

And if you really want to get fancy:
Iterable<Integer> ints = Iterables.transform(entries,
     new Function<String, Integer>(){
        Integer apply(String input){
           return Integer.parseInt(input);
        }
 });

Although you definitely could use a regex method or String.split, I feel that using Splitter is less likely to be error-prone and is more readable and maintainable. You could argue that String.split might be more efficient but since you are going to have to do all the trimming and checking for empty strings anyway, I think it will probably even out.
One comment about transform, it does the calculation on an as-needed basis which can be great but also means that the transform may be done multiple times on the same element. Therefore I recommend something like this to perform all the calculations once.
Function<String, Integer> toInt = new Function...
Iterable<Integer> values = Iterables.transform(entries, toInt);
List<Integer> valueList = Lists.newArrayList(values);

A: You can try using a Scanner:
Scanner sc = new Scanner(myString);
sc.useDelimiter("|");
List<Integer> numbers = new LinkedList<Integer>();
while(sc.hasNext()) {
    if(sc.hasNextInt()) {
        numbers.add(sc.nextInt());
    } else {
        sc.next();
    }
}

A: Here you go:
String str = "1 | 2 | 3 | 4 | 5 | 6 | 7 | | | | | | | |".replaceAll("\\|", "").replaceAll("\\s+", "");

A: Do you mean like?
String s = "1 | 2 | 3 | 4 | 5 | 6 | 7 | | | | | | | |";
for(String n : s.split(" ?\\| ?")) {
    int i = Integer.parseInt(n);
    System.out.println(i);
}

prints
1
2
3
4
5
6
7

A: inputString.split("\\s*\\|\\s*") will give you an array of the numbers as strings. Then you need to parse the numbers:
final List<Integer> ns = new ArrayList<>();
for (String n : input.split("\\s*\\|\\s*"))
  ns.add(Integer.parseInt(n);

A: You can use split with the following regex (allows for extra spaces, tabs and empty buckets):
String input = "1 | 2 | 3 | 4 | 5 | 6 | 7 | | | | | | | | ";
String[] numbers = input.split("([\\s*\\|\\s*])+");
System.out.println(Arrays.toString(numbers));

outputs:

[1, 2, 3, 4, 5, 6, 7]

A: Or with Java onboard methods:
String[] data="1 | 2 | 3 | 4 | 5 | 6 | 7 | | | | | | | |".split("|");

for(String elem:data){
   elem=elem.trim();
   if(elem.length()>0){
      // do someting
   }
}

A: Split the string at its delimiter | and then parse the array.
Something like this should do:
String test = "|1|2|3";
String delimiter = "|";
String[] testArray = test.split(delimiter);
List<Integer> values = new ArrayList<Integer>();
for (String string : testArray) {
    int number = Integer.parseInt(string);
    values.add(number);
}


text:
Q: Shared mmap co-ordination using fcntl locks? When using mmap() for shared memory (from Linux, or other UNIX-like systems) is it possible (and portable) to use fcntl() (or flock() or lockf() functions) to co-ordinate access to the mapping?
Responses to this SO question seems to suggest that it should work.
The idea I have in mind would be to have the shared memory structured with a process/page map to minimize the locking contention.  Processes could each work with their pages concurrently, and a lock would only need to be acquired when updating the process/page mappings.  (Read access from unowned pages would involve checking a serial number, copying the desired data, then validating that the serial number of that block hadn't changed).
Conceptually each process sharing this file mapping would perform the mmap(), find a free block therein,  acquire a lock to the process/page area, update that with its own assignment, release the lock and then go on merrily with its work.  Any process could search for stale mappings (using kill() with zero as the signal) and clean up the process/page table mapping.
(In rough, generic terms, I'm toying with a producer/consumer processing engine using shared memory from Python over Linux; I'd like the solution to be portable to BSD and to other programming languages --- so long as the support mmap() and the necessary interfaces to fcntl(), flock() or lockf().  I'd also be interested in psuedo-code showing how one would measure lock contention and detect any synchronization failures.  I am aware that the threading and multiprocessing with their respective Queue() objects are the most straightforward way to implement a Python producer/consumer processing model).

A: I'm sure the locks will provide mutual exclusion, but I don't know if they will give you a memory barrier.  It seems like jumping into the kernel (which fcntl, flock, and lockf will do) is likely to do something that forces out of order memory reads and writes to commit, but I doubt you'll get a hard guarantee.  I think this is one of those things where it probably works, and testing will show that it does work, but you won't know that it always works unless you find a reference saying as much.
I've done something similar to this from C, but I used atomic spinlocks in the shared memory itself.  It used to be that you had to do a little bit of inline assembly, but gcc now has some intrinsic operations that you can use:
http://gcc.gnu.org/onlinedocs/gcc/Atomic-Builtins.html
If you're willing to write a very simple Python extension, you could wrap __sync_lock_test_and_set(...) and __sync_lock_release(...) to do what you need.  Those should be pretty portable.
I believe there is a way to put pthread mutexes into shared memory too, but I don't have any experience with that.  Again, you'd have to write a simple C extension to get access to that from Python.


text:
Q: Is there anything I can do to get my split() function working? I just want to ask if how can I get my split function working properly
x_value = "7383 + 4536"

i used pytesseract to extract that string
if '+' in x_value is not None:
    x_value = re.split('[+`]', x_value)
    try:
        x_value = int(x_value[0]), int(x_value[1])
    except:
        x_value = int(x_value[0]), int(x_value[2])
print(x_value)

but my problem is it print outs
['7383 + 4536\n\x0c']

so...guys i really need your help guys...im just a 14 years old boy who wants to learn programming..its been 3 weeks since i started learning... this is my first project...i hope you can help me improve...

A: The + in a regular expression means "one or more" of the previous item.
You should escape it with \ in your pattern to be treated as the + character.
(Also, beware the \ must be escaped, or string prefixed by r.)
x_value = re.split( r'[\+`]', x_value )

A: Let's go through your code line-by-line.
if '+' in x_value is not None:
    x_value = re.split('[+`]', x_value)
    try:
        x_value = int(x_value[0]), int(x_value[1])
    except:
        x_value = int(x_value[0]), int(x_value[2])
print(x_value)

if '+' in x_value is not None:
This line is incorrect. '+' in x_value will be evaluated to either True or False, so therefore the is not None is not your intention. Say + is inside x_value, then the if statement evaluates to:
if True is not None

Which is of course True. Say + is not inside x_value, then:
if False is not None

This also evaluates to True. The correct way is simply:
if '+' in x_value:

x_value = re.split('[+.]', x_value)
This was covered by @Didier Trosset.
try block
try:
    x_value = int(x_value[0]), int(x_value[1])
except:
    x_value = int(x_value[0]), int(x_value[2])

If your input is say 1 + 2, then the correct regex line should return to you a list with two objects [1, 2]. In this case, the try statement is catching (if an error is thrown) in the case the regex line does not return 2 numbers, but when catching the error, it attempts to add a third number x_value[2], which would also throw an error.

A: Why don't you try something more simple, like this:
x_value = "7383 + 4536"

if "+" in x_value:
    values = [int(value.strip()) for value in x_value.split("+")]
    print(values)

It prints [7383, 4536].
The nice thing is that you don't need any regexp to make work.


text:
Q: Xcode 7 try to archive an ios app with library When I try to archive my project which include a library I get only generic archive type instead of IOS type.
I manage the scheme so my library would be in my main project container, I changed the skip install in the library to "YES".(in the main project set to NO but tried also to YES).
Why this keep happening?

A: Maybe this will work?
Go to Xcode preferences and make sure to download all provisional profiles. Quit Xcode & restart your computer then try deleting (backup if you want) your library - developer - Xcode - Archives folder and DerivedData folder. Archive
Try this if the above doesn't work:
Xcode 7 GM created generic archive instead of iOS app archive


text:
Q: Is there a better way to give elements knowlege of their parents and xpath in xml.etree.ElementTree I have the following code which works:
import xml.etree.ElementTree as etree

def get_path(self):
    parent =  ''
    path = self.tag
    sibs = self.parent.findall(self.tag)
    if len(sibs) > 1:
        path = path + '[%s]'%(sibs.index(self)+1)
    current_node = self
    while True:
        parent = current_node.parent
        if not parent:
            break
        ptag = parent.tag
        path = ptag + '/' + path
        current_node = parent
    return path

etree._Element.get_path = get_path
etree._Element.parent = None

class XmlDoc(object):
    def __init__(self):
        self.root = etree.Element('root')
        self.doc = etree.ElementTree(self.root)

    def SubElement(self, parent, tag):
        new_node = etree.SubElement(parent, tag)
        new_node.parent = parent
        return new_node

doc = XmlDoc()
a1 = doc.SubElement(doc.root, 'a')
a2 = doc.SubElement(doc.root, 'a')
b = doc.SubElement(a2, 'b')
print etree.tostring(doc.root), '\n'
print 'element:'.ljust(15), a1
print 'path:'.ljust(15), a1.get_path()
print 'parent:'.ljust(15), a1.parent, '\n'
print 'element:'.ljust(15), a2
print 'path:'.ljust(15), a2.get_path()
print 'parent:'.ljust(15), a2.parent, '\n'
print 'element:'.ljust(15), b
print 'path:'.ljust(15), b.get_path()
print 'parent:'.ljust(15), b.parent

Which results in this output:
<root></root>

element:        <Element a at 87e3d6c>
path:           root/a[1]
parent:         <Element root at 87e3cec>

element:        <Element a at 87e3fac>
path:           root/a[2]
parent:         <Element root at 87e3cec>

element:        <Element b at 87e758c>
path:           root/a/b
parent:         <Element a at 87e3fac>

Now this is drastically changed from the original code, but I'm not allowed to share that.
The functions aren't too inefficient but there is a dramatic performance decrease when switching from cElementTree to ElementTree which I expected, but from my experiments it seems like monkey patching cElementTree is impossible so I had to switch.
What I need to know is whether there is either a way to add a method to cElementTree or if there is a more efficient way of doing this so I can gain some of my performance back.
Just to let you know I am thinking of as a last resort implementing selected static typing and to compile with cython, but for certain reasons I really don't want to do that.
Thanks for taking a look.
EDIT: Sorry for the wrong use of the term late binding. Sometimes my vocabulary leaves something to be desired. What I meant was "monkey patching."
EDIT: @Corley Brigman, Guy: Thank you very much for your answers which do address the question, however (and I should have stated this in the original post) I had completed this project before using lxml which is a wonderful library that made coding a breeze but due to new requirements (This needs to be implemented as an addon to a product called Splunk) which ties me to the python 2.7 interpreter shipped with Splunk and eliminates the possibility of adding third party libraries with the exception of django.

A: If you need parents, use lxml instead - it tracks parents internally, and is still C behind the scenes so it's very fast.
However... be aware that there is a tradeoff in tracking parents, in that a given node can only have a single parent. This isn't usually a problem, however, if you do something like the following, you will get different results in cElementTree vs. lxml:
p = Element('x')
q = Element('y')
r = SubElement(p, 'z')
q.append(r)

cElementTree:
dump(p)
<x><z /></x>
dump(q)
<y><z /></y>

lxml:
dump(p)
<x/>
dump(q)
<y>
  <z/>
</y>

Since parents are tracked, a node can only have one parent, obviously. As you can see, the element r is copied to both trees in cElementTree, and reparented/moved in lxml.
There are probably only a small number of use cases where this matters, but something to keep in mind.

A: you can just use xpath, for example:
import lxml.html

def get_path():
    for e in doc.xpath("//b//*"):
        print e

should work, didn't test it though...


text:
Q: How to remove item from onsen list? i use onsen list in mobile application.now i need remove item of list in js. but i do not know?
can help me?
Thanks and sorry for my poor English.

A: Here's an example you could remove an element...
http://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_elementremove
Maybe it'll help?


text:
Q: "WITH" clause Query not working in android this is my rawQuery
WITH authorRating(aname, rating) AS SELECT aname, AVG(quantity) FROM book GROUP BY aname

error is in Logcate
   android.database.sqlite.SQLiteException: near "WITH": syntax error (code 1):

A: WITH is supported since SQLite 3.8.3, and that is not shipped with all Android versions.
Anyway, this query is not a valid WITH clause, and lacks the actual query.


text:
Q: Android/Java: detect if device has a BACK Camera How do I detect if the device has a camera on the BACK?
This is my code to detect if the device has a Flashlight:
if (context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)
    || (_camera.getParameters().getSupportedFlashModes() != null)) hasFlashlight = true;
else hasFlashlight = false;

But it is TRUE even if the device only has a Front Camera without the flashlight.

A: For API >= 9 : you can use Camera.getCameraInfo with something like this :
int backCameraId = -1;
for(int i=0;i<Camera.getNumberOfCameras();i++){
    CameraInfo cameraInfo = new CameraInfo();
    Camera.getCameraInfo(i,cameraInfo);
    if(cameraInfo.facing==CameraInfo.CAMERA_FACING_BACK) {
        backCameraId = i;
        break;
    }
}
Log.d(TAG, "back camera exists ? "+(backCameraId>-1));
Log.d(TAG, "back camera id  :"+backCameraId);

For API >= 21, you are advised to use the Camera2 API :
String backCameraId = null;
CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
for(String cameraId:manager.getCameraIdList()){
    CameraCharacteristics cameraCharacteristics = manager.getCameraCharacteristics(cameraId);
    Integer facing = cameraCharacteristics.get(CameraCharacteristics.LENS_FACING);
    if(facing==CameraMetadata.LENS_FACING_BACK) {
        backCameraId = cameraId;
        break;
    }
}
Log.d(TAG, "back camera exists ? "+(backCameraId!=null));
Log.d(TAG, "back camera id  :"+backCameraId);

A: Try check the number of Cameras:
import android.hardware.Camera;

int numberOfCameras = Camera.getNumberOfCameras();

If it is greater than 1, pretty sure got a rear camera.

A: public boolean isRearCameraAvailable(Context context) {
    return context.getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA);
}

Checks if the device has a camera facing away from the device user

A: CameraManager mCameraManager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);

 /** Which way the camera is facing. */
    public static enum Facing {
        FRONT, BACK;
    }

 /** Returns the ID of the first camera facing the given direction. */
    private String findCameraId(Facing facing) {
        if (facing == Facing.FRONT) {
            return findFirstFrontCameraId();
        } else {
            return findFirstBackCameraId();
        }
    }

    /** Returns the ID of the first back-facing camera. */
    private String findFirstBackCameraId() {
        Log.d(TAG, "Getting First BACK Camera");
        String cameraId = findFirstCameraIdFacing(CameraCharacteristics.LENS_FACING_BACK);
        if (cameraId == null) {
            Log.w(TAG, "No back-facing camera found.");
        }
        return cameraId;
    }

    /** Returns the ID of the first front-facing camera. */
    private String findFirstFrontCameraId() {
        Log.d(TAG, "Getting First FRONT Camera");
        String cameraId = findFirstCameraIdFacing(CameraCharacteristics.LENS_FACING_FRONT);
        if (cameraId == null) {
            Log.w(TAG, "No front-facing camera found.");
        }
        return cameraId;
    }

    /** Returns the ID of the first camera facing the given direction. */
    private String findFirstCameraIdFacing(int facing) {
        try {
            String[] cameraIds = mCameraManager.getCameraIdList();
            for (String cameraId : cameraIds) {
                CameraCharacteristics characteristics = mCameraManager
                      .getCameraCharacteristics(cameraId);
                if (characteristics.get(CameraCharacteristics.LENS_FACING) == facing) {
                    return cameraId;
                }
            }
        } catch (CameraAccessException ex) {
            Log.w(TAG, "Unable to get camera ID", ex);
        }
        return null;
    }


text:
Q: Prove $\|x-y\|\|x+y\|\le\|x\|^2+\|y\|^2$ for all $x,y\in\mathbb{R}^n$ Prove $\|x-y\|\|x+y\|\le\|x\|^2+\|y\|^2$  for all $x,y\in\mathbb{R}^n$
I've been struggling with this for a while and haven't figured out a way to do it either geometrically or algebraically.

A: \begin{align}
\|x-y\|^2\|x+y\|^2 &=(x-y,x-y)(x+y,x+y)\\
&=(\|x\|^2-2(x, y) + \|y\|^2)(\|x\|^2+2(x,y) + \|y\|^2)\\
&=(\|x\|^2+\|y\|^2)^2-4(x, y)^2\\
&\le(\|x\|^2+\|y\|^2)^2
\end{align}


text:
Q: php make dollar optional Is there any reason the PHP language could not be updated in a future version to make the $ prefix on variable names optional? Reasons that would break existing code?
I'm thinking it would still be required for string interpolation, like "Hello $name", but most of the time it would be optional.
For example,
$name = 'Bob';
echo "Hello $name";

would still be valid, but so would
name = 'Bob';
echo "Hello $name";

A: It would probably break tons of existing code. Using the sigil means variables may use the same names as keywords, functions (built-in or user-defined), classes, etc.

A: The sigil for a variable in php is part of how the system works.  It conveys some information for the parser about what the thing actually is.  By keeping the variables and the functions in completely different name spaces, it allows one to have variable names that are function names without collision.
The without collision bit is kind of important in php, since it has been known to have quite a few standard functions.  This is further complicated but he fact that parentheses for functions are optional.  The parentheses are part of how other languages without sigils often separate if the identifier is a value or a function.
int foo() { return 42; }

int foo = 42;
int bar;

bar = foo;
bar = foo();

In Java, (the code above) there is no ambiguity about which foo is being used in each line because the () are required on function calls.
This is not the case in php.
$echo = "foo";
echo $echo;
echo($echo);

Both of those are perfectly valid.  It is the sigil that says that one echo is a function call and the other is a variable.
So, no, the sigil for a variable cannot be made optional in php.  It is part of the type system and identifier lookup and parser.  It conveys necessary information that allows other things to be optional (like parentheses).
For fun, consider the following code (ideone) and the impact that sigils have on first class functions:
function greet($arg) { return "Hello $arg\n"; }

$greet = function($arg) { return "Greetings $arg\n"; };

echo $greet("Everyone");
echo greet("World");

And while there are ways of working around this in other languages that lack sigils that have first class functions, the combination of sigils and anonymous functions can be seen as making things a bit easier on the programmer and on the language designer at the same time.


text:
Q: MySQL injection penetration I'm new here so I'll try to make my post as clear and readable as possible.
While browsing some site's log I came across some hacking attempts that I want to recreate/test in a closed server. I made a simple PHP web page that gets a variable named 'id' and without any filtering/validation use it in a query.
Relevant PHP code
$var = $_GET['id'];

echo $_GET['id'] . "<br>\n";

include ( "/var/www/dbconnect.php" );
$mysqli = new mysqli ( $db_host, $db_user, $db_password, "news" );
if ( $mysqli->connect_errno ) { echo "Failed to connect to MySQL: (" . $mysqli-   >connect_errno . ") " . $mysqli->connect_error; }

$query = "SELECT id, date, subject FROM news_table WHERE id=" . $var;
//$query = "SELECT id, date, subject FROM news_table WHERE id=250; DROP TABLE test;"; // This won't work because in PHP's implementation multiple statements are not allowed
if ( ! $result = $mysqli->query ( $query ) ) { echo "CALL failed: (" . $mysqli->errno . ") " . $mysqli->error; } else { }

Then I load the page using the following
testserver/test-files/test-mysql-vulnerability.php?id=362099999.1
union select unhex(hex(version())) -- 1=1

and get this result:
 CALL failed: (1222) The used SELECT statements have a different number
of columns

The hacker spent 5 minutes sending numerous combinations trying to break into our production server. My production server does not give any indication of success/failure like the error above.
My question is: Can the above hack work when the number of columns don't match? If so how?
tnx

A: As noted in the comments, don't do this.
To answer your question, though, union is useful in injections because it allows you to use an unrelated table in the output.  The error you're seeing is because the original database query wanted a certain number and type of columns, and the injected query wanted only one.  In this case we know that we need three columns (from the code), so we want the resultant SQL statement to be
SELECT id, date, subject FROM news_table WHERE id=3 union select 0, 0, unhex(hex(version())) --

(This may not work exactly depending on your data types and my ability to do this off the top of my head).

A: SELECT id,
       date,
       subject
FROM   news_table
WHERE  id = 3
UNION
SELECT NULL                  AS id,
       NULL                  AS date,
       Unhex(Hex(Version())) AS subject

also use mysql instead of mysqli as it is more prone to injections


text:
Q: How can I add to bookmarks without using section or chapter? This is what I'm trying to fix on bookmarks, I want to add the TEST on my bookmarks and under the TEST I want to add LOREM

TEST
>LOREM

    \documentclass{article}
    \usepackage[utf8]{inputenc}
    \usepackage{lipsum}

    \title{DotFill}
    \author{jasond.worked }
    \date{September 2022}

    \begin{document}

    \maketitle

    \section{Introduction}

    \textbf{TEST} \newline

    \noindent\textbf{LOREM}\\
    \indent\lipsum[]

    \end{document}

A: With the package bookmark you can use the command \pdfbookmark[level]{text}{name} to add a manual link.
name is used for
the internal anchor name   in conjunction with level. Therefore the name must be unique.

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{lipsum}

\usepackage{bookmark}

\title{DotFill}
\author{jasond.worked }
\date{September 2022}

\begin{document}

    \maketitle

    \section{Introduction}

    \pdfbookmark[subsection]{TEST}{test}
    \textbf{TEST}
     \newline

    \pdfbookmark[subsection]{LOREM}{lorem}
    \noindent\textbf{LOREM}

    \indent\lipsum[]

\end{document}

Comment The command \pdfbookmark can also be used loading the package hyperref.  However this is a hint found in the hyperref   manual (both packages share the same author):

Package bookmark replaces hyperref's bookmark organization by a
new algorithm:
• Usually only one LATEX run is needed.
• More control over the bookmark appearance (color, font).
• Different bookmark actions are supported.
Therefore I recommend using this package


text:
Q: if $\alpha$ $\beta$ and $\gamma$ are the roots of a equation than find the value of . if $\alpha$, $\beta$ and $\gamma$ are the roots of equation $x^3-3x^2+3x+7=0$ ($\omega$ is the cube root of unity),then
$\frac{{\alpha}-1}{{\beta}-1}$+$\frac{{\beta}-1}{{\gamma}-1}$+$\frac{{\gamma}-1}{{\alpha}-1}$  is
(a)$\frac{3}{{\omega}}$ (b) ${\omega}^2$ (c) 2${\omega}^2$  (d) 3${\omega}^2$
The question is from the IIT entrance Exam practice material. The Answer marked in the solution booklet is (a) but I am unable to find the way to get it. Please help me out.
Thanks in Advance.

A: Hint: If $\alpha,\beta,\gamma$ are the roots of $(x-1)^3+8=0$, what are
$\alpha-1,\beta-1$ and $\gamma-1$ the roots of?


text:
Q: The action 'NAVIGATE' with payload {"name":"CoursesPlaylistScreen"} was not handled by any navigator in React native I have tried nesting the naviagtors so I don't have to face this issue but still I am getting this error as I have main navigator which is contains the first screen BootcampWeeksScreen.js then I can easily navigating through it new screen which contains const tab= createMaterialTopTabNavigator().
BootcampWeeksScreen.js:
import React from "react";
import { NavigationContainer } from "@react-navigation/native";
import { createMaterialTopTabNavigator } from "@react-navigation/material-top-tabs";
import Courses from "./BootcampAdditionalScreens/Courses";
import Tests from "./BootcampAdditionalScreens/Test";
import Roadmap from "./BootcampAdditionalScreens/Roadmap";
import CoursesPlaylistScreen from "../screens/BootcampAdditionalScreens/CoursesPlaylistScreen.js";
import { createStackNavigator } from '@react-navigation/stack';

const Stack = createStackNavigator();
const Tab = createMaterialTopTabNavigator();
const BootcampWeeksScreen=()=>{
  return (

    <NavigationContainer>

      <Tab.Navigator tabBarOptions={{ scrollEnabled: true }}>
      <Tab.Screen name="Course" component={Courses} />
      <Tab.Screen name="Tests" component={Tests} />
        <Tab.Screen name="Roadmap" component={Roadmap} />
      </Tab.Navigator>
    </NavigationContainer>
  );
}
 function App() {
    return (
      <NavigationContainer>
        <Stack.Navigator screenOptions={{ headerShown: false }}>
          <Stack.Screen name="BootcampWeeksScreen" component={BootcampWeeksScreen} />
          <Stack.Screen name="CoursesPlaylistScreen" component={CoursesPlaylistScreen} />
        </Stack.Navigator>
      </NavigationContainer>
    );
  }

  export default BootcampWeeksScreen;

Now I want to navigate through the screen CoursesPlaylistScreen from the Course screen but I am getting this error and also I have tried nesting the navigators.
I have tried this also to navigate though the screen: ```onPress={() =>navigation.navigate("BootcampStack",{screen:"CoursesPlaylistScreen"})}  ````
Still, I am getting this error.
 ERROR  The action 'NAVIGATE' with payload {"name":"CoursesPlaylistScreen"} was not handled by any navigator.

Do you have a screen named 'CoursesPlaylistScreen'?

If you're trying to navigate to a screen in a nested navigator, see https://reactnavigation.org/docs/nesting-navigators#navigating-to-a-screen-in-a-nested-navigator.

I don't know How can I do this?

A: You can only have one NavigationContainer. Try removing NavigationContainer from BootcampWeeksScreen.

A: The NavigationContainer is responsible for managing your app state and linking your top-level navigator to the app environment. By giving two navigators, you're resetting the whole navigator and hence unable to find the other stack.
You should only wrap your stacks in NavigationContainer on the root/top level of your navigation, i.e. function App in your situation.


text:
Q: Crystal lang how to get binary file from http In Ruby:
require 'open-uri'
download = open('http://example.com/download.pdf')
IO.copy_stream(download, '~/my_file.pdf')

How to do the same in Crystal?

A: We can do the following:
require "http/client"

HTTP::Client.get("http://example.org") do |response|
  File.write("example.com.html", response.body_io)
end

This writes just the response without any HTTP headers to the file. File.write is also smart enough to not download the entire file into memory first, but to write to the file as it reads chunks from the given IO.

A: I found something that works:
require "http/request"
require "file"
res = HTTP::Client.get "https://ya.ru"
fl=File.open("ya.html","wb")
res.to_io(fl)
fl.close


text:
Q: Media Css for Iphone6 & Iphone6 plus I'm making this website & I made the media settings for mobile, tablet, laptop, desktop. It looked good in all other phones. I havent' checked yet on actual tablet, but its fine on the chrome browser emulator.
However, my friend checked out the site in his Iphone6 Plus and the navbar settings were messed up. Btw, I'm using Bootstrap 3 for the framework.
I'm confused why my code is working on other phones but not on Iphone6 Plus.
Maybe even Iphone6 have the same problem?
Here is my media css:
    /* Tablet (Portrait) */
@media only screen and (max-width : 768px) and (orientation: portrait) {
}
/* Phones (Portrait) */
@media only screen and (max-width : 480px) and (orientation: portrait) {
}
/* Phones (Landscape) */
@media only screen and (max-width : 480px) and (orientation: landscape){
}
/* Tablet (Landscape)*/
@media only screen and (max-width :1100px) and (orientation: landscape) {
}
/* Medium Devices, Desktops and tablet landscape*/
@media only screen and (min-width : 992px) {
}
/* Large Screens, Large Desktops */
@media only screen and (min-width : 1601px) {
}

I already checked online that the pixel density & resolution is quite different for Iphone6 Plus. We've tried the solution from here : iPhone 6 and 6 Plus Media Queries
So far, even those queries didn't fix our problem. It seems like there were no changes. I hope this problem could be resolved quickly, I appreciate your help.

A: Everything comes down to device-pixel-ratio which used to be 2x for iphones. New iphone 6 plus has 3x retina display
/* iPhone 6 landscape */
@media only screen and (min-device-width: 375px)
  and (max-device-width: 667px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 2)
  {
  /* Your CSS */
  }

/* iPhone 6 portrait */
@media only screen
  and (min-device-width: 375px)
  and (max-device-width: 667px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 2)
  {
  /* Your CSS */
  }

/* iPhone 6 Plus landscape */
@media only screen
  and (min-device-width: 414px)
  and (max-device-width: 736px)
  and (orientation: landscape)
  and (-webkit-min-device-pixel-ratio: 3)
  {
  /* Your CSS */
  }

/* iPhone 6 Plus portrait */
@media only screen
  and (min-device-width: 414px)
  and (max-device-width: 736px)
  and (orientation: portrait)
  and (-webkit-min-device-pixel-ratio: 3)
  {
  /* Your CSS */
  }

/* iPhone 6 and 6 Plus */
@media only screen
  and (max-device-width: 640px),
  only screen and (max-device-width: 667px),
  only screen and (max-width: 480px)
  {
  /* Your CSS */
  }

Further more, an article from CSS | MDN to add more browsers support and a fallback.
link : https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries/Using_media_queries
@media (-webkit-min-device-pixel-ratio: 2), /* Webkit-based browsers */
       (min--moz-device-pixel-ratio: 2),    /* Older Firefox browsers (prior to Firefox 16) */
       (min-resolution: 2dppx),             /* The standard way */
       (min-resolution: 192dpi)             /* dppx fallback */

A list of devices with their respective device-pixel-ratio.
link : https://bjango.com/articles/min-device-pixel-ratio/


text:
Q: init.d script ignored in yocto based distro I'm modifying an embedded distro that is built using the yocto project. I need to add cron to it and have the cron daemon start on startup. I have created the symlink /etc/rc5.d/S98cronstart that points to the cron start script included in the standard yocto metalayer.
It seems to be ignored completely when the system boots though, but if I execute the symlink manually everything is fine. I tried to modify it so the script creates a file when ran, and sure enough it is not created on sytem startup but it is created if I run it manually.
Any ideas on what's wrong or how I would go about debugging this?


text:
Q: How to minimize to tray Thunderbird in KDE Plasma 5.2? I just tried Kubuntu 15.04. I installed Thunderbird with minimizetotray addon. But window disappears instead of minimize to tray. How can I fix it?

A: In KDE5 the usual minimize-to-tray plugin works except you can't see icon but notification popup does appear so workaround is to add thunderbird app icon to panel to simulate its notification icon when minimized.  The only difference is the app icon is a little bigger than the one which appears after minimizing.  This way the behavior is exactly the same, in fact better since to open Thunderbird you click on the app icon just once.  Fire-tray plugin never worked for me in KDE5.

A: Firetray does not work in current/newer versions of KDE's plasmashell, since the indicator rewrite.  The author of Firetray was working on actual indicator support, but unfortunately has decided to discontinue the project (https://foudil.fr/blog/209/the-web-is-not-the-platform/).  This is a shame, because I've not found any better option that works with thunderbird myself.
The only workaround I've found is to continue using the last release (0.6.0.1) of firetry and also install stalonetray.  If you configure stalonetray correctly, it can displaying the firetray icon (and any other legacy apps without real indicator support).

A: This thread is a little old, but the problem regarding minimizing Thunderbird to system tray still remains, at least for me having Debian 10 along with KDE Plasma desktop.
My today's workaround was successful! The firetray does not work the past years and finally I found the replacement.
https://github.com/Ximi1970/systray-x
They provide a lot of information in their README file, containing useful doc about installing in the most used Linux distributions (Ubuntu, Debian, Arch, Fedora, OpenSuse, CentOS).


text:
Q: Delete empty rows in jTable I am trying to remove empty rows in table. I am detecting empty rows by checking  first field(Register number - primary). But on clicking the button it removes only half of the empty rows and on next click another half rows of empty rows are deleted and it produces ArrayIndexOutOfBoundException.  I don't know whats wrong in my code. Thanks in advance.
DefaultTableModel dtm=(DefaultTableModel) jTable4.getModel();
    int i=dtm.getRowCount();
    for(int j=0;j<i;j++)
         {

         if(!(jTable4.getValueAt(j, 0) != null
         && jTable4.getValueAt(j, 0).toString().trim().length() != 0) )
         {
               dtm.removeRow(j);
         }

         }


text:
Q: Beamerposter 36" x 48" I seek to make a poster on Beamerposter that is printable on a 36" high x 48" wide laminated poster. I found samples on previous discussions in the site but I would like to be able to verify that they are indeed in the right dimensions.
Specifically, consider this template. Is this 36" x 48". It sure looks like it to me but I don't know how to verify. Also, can I make the two middle columns into one column instead (so 3 columns instead of 4)? Thanks!


text:
Q: Why are changes in my RSS feed not picked up by RSS readers? I am trying to add an RSS feed to my website embeetle.com. I am doing this "the hard way" by manually creating an XML file for the RSS feed.  You can find it here: https://embeetle.com/rss.xml. The file has been validated using the W3 feed validator at https://validator.w3.org/feed/check.cgi?url=embeetle.com
The problem I have is that the RSS readers I tried are not displaying the most recent content of my RSS feed.  I tried Feedly, Inoreader and NewsBlur.  All of them are showing older versions of the feed,  as if these are cached somewhere, and the cache is not updating (I waited 24 hours to make sure).
I guess I am doing something wrong here, but I have no clue what.  I have been trying to find hints searching the web for hours. Any hints are welcome.
If you want to check: there should be two posts in the feed,  one announcing our new RSS feed and one announcing the latest version of Embeetle.  In the readers,  I get only the second post, sometimes with out-of-date content.


text:
Q: find the curve $y = ax + bx^2$ that best fits the data using method of least squares? There's a problem in curve fitting section,
Q) By the method of least squares, find the curve $y = ax + bx^2$ that best fits the following data.
x   1    2    3    4     5
y  1.8  5.1  8.9  14.1  19.8

I try to solve it by using  this fitting a straight line formula,
$\sum_{i=1}^n y_i = na * b\sum_{i=1}^nx_i$
$\sum_{i=1}^nx_iy_i = a\sum_{i=1}^nx_i+b\sum_{i=1}^nx_i^2$
I got $a = 3.56, b = 4.5$ which seems to be wrong? which formula should I use to solve this?

A: In least square method for polynomials multiply both sides of equation  with $x_i$ and sum up.
Solve $(a,b)$ from:
$$\sum_{i=1}^ny_i = a\sum_{i=1}^nx_i+b\sum_{i=1}^nx_i^2$$
$$ \sum_{i=1}^nx_i y_i = a\sum_{i=1}^nx_i^2+b\sum_{i=1}^nx_i^3$$
$\sum_{i=1}^nx_i^3$ should be tabulated and summed in addition.

A: You should use
$$\sum_{i=1}^n x_i y_i = a\sum_{i=1}^n x_i^2 +b\sum_{i=1}^nx_i^3$$
$$\sum_{i=1}^n x_i^2 y_i = a\sum_{i=1}^n x_i^3 +b\sum_{i=1}^nx_i^4$$
This is derived by starting with an expression for the Sum of the Squared Errors
$$SSE = \sum_{i=1}^n (y_i - \hat{y}_i)^2$$
$$SSE = \sum_{i=1}^n (y_i - (ax_i+bx_i^2))^2$$
Take partial derivatives with respect to $a$ and $b$ and set each to $0$:
$$\frac{\partial SSE}{\partial a} = \sum_{i=1}^n \left[2(y_i - (ax_i+bx_i^2))(-x_i)\right] \equiv 0$$
$$\frac{\partial SSE}{\partial b} = \sum_{i=1}^n \left[2(y_i - (ax_i+bx_i^2))(-x_i^2)\right] \equiv 0$$
Then with some rearranging and simplification you get
$$-\sum_{i=1}^n x_i y_i + a\sum_{i=1}^n x_i^2 + b\sum_{i=1}^n x_i^3 = 0$$
$$-\sum_{i=1}^n x_i^2 y_i + a\sum_{i=1}^n x_i^3 + b\sum_{i=1}^n x_i^4 = 0$$
Solving the equations gives you:
$$a = \frac{\sum x_i^4 \sum x_i y_i - \sum x_i^3 \sum x_i^2 y_i}{\sum x_i^4 \sum x_i^2 - \sum x_i^3 \sum x_i^3}$$
$$b = \frac{\sum x_i^2 \sum x_i^2 y_i - \sum x_i^3 \sum x_i y_i}{\sum x_i^4 \sum x_i^2 - \sum x_i^3 \sum x_i^3}$$
Hope that helps


text:
Q: Invalid window and invalid renderer error SDL c++ Here is my code
#include <iostream>
#include "SDL.h"

namespace engine {

    class SDL_UI
    {
    protected:
        SDL_Renderer* renderer;
        SDL_Window* window;
        SDL_Event event;

        bool initialised = true;
        bool quit = false;

    public:

        SDL_UI(const char* name, int x, int y, int w = SDL_WINDOWPOS_CENTERED, int h = SDL_WINDOWPOS_CENTERED, bool fullscreen = false)
        {
            if (SDL_Init(SDL_INIT_EVERYTHING) != 0)
            {
                throw std::runtime_error(SDL_GetError());
            }
            window = SDL_CreateWindow(name, x, y, w, h, fullscreen);
            renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED);
            if (renderer == nullptr)
            {
                std::cout << SDL_GetError() << std::endl;
                //throw std::runtime_error("Renderer creation failed");
                initialised = false;
            }
            if (window == nullptr)
            {
                std::cout << SDL_GetError() << std::endl;
                //throw std::runtime_error("Window creation failed");
                initialised = false;
            }

        }

        ~SDL_UI()
        {
            SDL_DestroyWindow(window);
            SDL_DestroyRenderer(renderer);
        }

        void handleEvents()
        {
            while (SDL_PollEvent(&event))
            {
                if (event.type == SDL_QUIT)
                {
                    quit = true;
                }
            }
        }

        void setColor(int r, int g, int b, int a = 255)
        {
            SDL_SetRenderDrawColor(renderer, r, g, b, a);
        }

        void clear(int r, int g, int b, int a = 255)
        {
            SDL_SetRenderDrawColor(renderer, r, g, b, a);
            SDL_RenderClear(renderer);
        }

        void flip()
        {
            SDL_RenderPresent(renderer);
        }

        virtual void update()
        {

        }

        virtual void render()
        {

        }

        void start()
        {
            if (initialised && !quit)
            {
                handleEvents();
                update();
                render();
                flip();

            }
        }
    };

    class Engine : public SDL_UI
    {
    public:
        Engine(const char* name, int width, int height) : SDL_UI(name, width, height){}

    public:

        void drawLine(int x1, int y1, int x2, int y2)
        {
            SDL_RenderDrawLine(renderer, x1, y1, x2, y2);
        }
    };

}

class Game : public engine::Engine
{
private:
    //engine::Draw renderer;

public:
    Game() : engine::Engine{ "engine", 1200, 600 }{}

    void update() override
    {

    }

    void render() override
    {
        clear(10, 10, 10);
    }
};

int main(int argc, char* argv[])
{
    Game game;
    game.start();
    return 0;
}

I don't get any error message and "invalid window" and "invalid renderer" are printed to the console which are the messages from 'SDL_GetError()'. Window and renderer are created in SDL_UI class's constructor. It checks if renderer and window are nullptr aftet they are created and prints the error if they are still nullptr are creation.

A: According to this: https://wiki.libsdl.org/SDL_CreateWindow

Function Parameters
title
the title of the window, in UTF-8 encoding
x
the x position of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED
y
the y position of the window, SDL_WINDOWPOS_CENTERED, or SDL_WINDOWPOS_UNDEFINED
w
the width of the window, in screen coordinates
h
the height of the window, in screen coordinates
flags
0, or one or more SDL_WindowFlags OR'd together; see Remarks for details
while in your code you have:

int x, int y, int w = SDL_WINDOWPOS_CENTERED, int h = SDL_WINDOWPOS_CENTERED

Try
int x = SDL_WINDOWPOS_CENTERED, int y = SDL_WINDOWPOS_CENTERED, int w, int h


text:
Q: Which preposition is to be used before "participation" -- in or on? I read a sentence in Word by Word by Kory Stamper which was:

I had one social studies teacher who proclaimed to us on the first day of class that everyone was expected to speak "correct and proper English" in class and  failure to do so would mean marks off on participation.

I don't know what sort of "participation" is he talking about here? Is it class participation of a student? And what should be the preposition before it? In or on?

A: You are correct. The teacher is talking about class participation. And the preposition is already correct.
You mark students on their class participation, not in their class participation.


text:
Q: How allow vertical scroll and disable horizontal swipe with Flutter? I've the following page:

With a bottombar and three pages.
I want to enable vertical scrolling, but disable the swipe.
I used the suggestion physics: NeverScrollableScrollPhysics() in a SingleChildScrollView, but then the vertical scrolling is disabled, but I still can swipe.
A part of my code:
...
    return SingleChildScrollView(
      scrollDirection: Axis.vertical,
      controller: ScrollController(),
      physics: NeverScrollableScrollPhysics(),
      child: Container(
        child: Column(
          children: <Widget>[
            Text('AAA'),
            Text('AAA'),
            Text('AAA'),
            Text('AAA'),
...

I build the 'tabs' with PageViews:
  Widget buildPageView() {
    return PageView(
      controller: pageController,
      onPageChanged: (index) {
        pageChanged(index);
      },
      children: <Widget>[
        Page1Screen(),
        Page2Screen(),
        Page3Screen(),
      ],
    );
  }

Any suggestions would be very welcome.

A: Simply add NeverScrollableScrollPhysics() to - PageView
PageView(
        physics: NeverScrollableScrollPhysics(), // add this
        controller: pageController,
        onPageChanged: (index) {
           pageChanged(index);
        },
        children: <Widget>[
          Page1Screen(),
          Page2Screen(),
          Page3Screen(),
        ],
      ),


text:
Q: NodeJS Express enumerate files in a folder Sorry, I'm new with NodeJS Express. I want to get all files from a folder. I tried the following but don't work, test is always empty string:
var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
      test = files[0];
    })

    res.render('index', { title: 'Express', file: test });
});

Basically, I want to get all filenames from public images folder.

A: Problem here is res.render() will be executed before test is assigned to files[0], because the fs.readdir is asynchronous process. Before your callback is called res.render is excuted. And also, if you are trying to get all files from the folder you should pass files array. Please take a look at this for more info. You might wanna try the below code.
var express = require('express');
var router = express.Router();
var fs = require('fs');

router.get('/', function(req, res, next) {
    var test = '';

    const testFolder = './public/images';

    fs.readdir(testFolder, (err, files) => {
       // test = files[0]; this will assign test to the first element of the array of file
       test = files;
       res.render('index', { title: 'Express', file: test });
    })

});


text:
Q: Concatenating two text columns in dplyr My data looks like this:
round <- c(rep("A", 3), rep("B", 3))
experiment <- rep(c("V1", "V2", "V3"), 2)
results <- rnorm(mean = 10, n = 6)

df <- data.frame(round, experiment, results)

> df
  round experiment   results
1     A         V1  9.782025
2     A         V2  8.973996
3     A         V3  9.271109
4     B         V1  9.374961
5     B         V2  8.313307
6     B         V3 10.837787

I have a different dataset that will be merged with this one where each combo of round and experiment is a unique row value, ie, "A_V1". So what I really want is a variable name that concatenates the two columns together. However, this is tougher to do in dplyr than I expected. I tried:
name_mix <- paste0(df$round, "_", df$experiment)
new_df <- df %>%
  mutate(name = name_mix) %>%
  select(name, results)

But I got the error, Column name must be length 1 (the group size), not 6. I also tried the simple base-R approach of cbind(df, name_mix) but received a similar error telling me that df and name_mix were of different sizes. What am I doing wrong?

A: You could also try this:
library(tidyr)
library(dplyr)
df = df %>%
   unite(combined, round, experiment, sep = "_", remove = FALSE)

The output will be:
combined round experiment   results
 A_V1     A         V1      10.152329
 A_V2     A         V2      10.863128
 A_V3     A         V3      10.975773
 B_V1     B         V1       9.964696
 B_V2     B         V2       9.876675
 B_V3     B         V3       9.252936

This will retain your original columns.

A: You can use the unite function from tidyr
require(tidyverse)

df %>%
  unite(round_experiment, c("round", "experiment"))

  round_experiment   results
1             A_V1  8.797624
2             A_V2  9.721078
3             A_V3 10.519000
4             B_V1  9.714066
5             B_V2  9.952211
6             B_V3  9.642900

A: Another solution could be to use the stri_join function in stringi package.
library(stringi)
df$new = stri_join(df$round,df$experiment,sep="_")

A: This should do the trick if you are looking for a new variable
library(tidyverse)

round <- c(rep("A", 3), rep("B", 3))
experiment <- rep(c("V1", "V2", "V3"), 2)
results <- rnorm(mean = 10, n = 6)

df <- data.frame(round, experiment, results)
df

df <- df %>% mutate(
  name = paste(round, experiment, sep = "_")
)


text:
Q: jquery Validate errorPlacement insert element + br + error I'm trying to use 'errorPlacement' from jQuery Validation DOCS, like that:
$("#myform").validate({
    errorPlacement: function(error, element) {
        error.insertAfter(element);
    }
});

So far so good, but what I really want is to insert a
 tag between the input and the error label in each case:
<input>
**
**

I have tried with:
error.insertAfter(element.append($('
'));

...but no luck. Is there a simple way of doing it?
Any help is much appreciated.

A: You wouldn't need to do that.
Just use the errorElement option to change the default error element from label (inline) to div (block), so that it automatically wraps to the next line.
$("#myform").validate({
    errorElement: "div", // default is 'label'
    errorPlacement: function(error, element) {
        error.insertAfter(element);
    }
});

Otherwise, your code...
error.insertAfter(element.append($('
'));

*

*is missing a closing parentheses, )

*is not the correct format... you do not put a string to append within a jQuery selector, $()
Would be...
error.insertAfter(element.append('
'));

However, that still does not work as intended because append() is trying to put the content inside of element.

This way works as you requested...
$("#myform").validate({
    errorPlacement: function(error, element) {
        element.after(error).after('
');
    }
});

DEMO:   http://jsfiddle.net/1pfvug7r/

A: Try this:
$("#myform").validate({
    errorPlacement: function(error, element) {
        error.insertAfter(element);
        $('
').insertAfter(element);
    }
});

But you can use css:
input,
label.error {float:left;clear:both;}


text:
Q: slick slider - syncing autoplay and active navigation I am trying to use the slick Slider to create a slider that allows a user to select the title of the section and see the slide for it but also give the option for it to autoplay.
The stuff works fine. But I need some way to correspond into make it so that when it autoplays, it corresponds to the active navigation and changes it color.
Right now it only show a new color for the active slide title if a user is clicking it. I want it to do so on autoplay also
how would I do that??
Here is the code I have working right now
Js Bin
The only thing I changed is that autoplay option that does not exist on the demo of slick slider
 $('.slider-for').slick({
 slidesToShow: 1,
 slidesToScroll: 1,
 arrows: false,
 fade: true,
 asNavFor: '.slider-nav',
 autoplay:true

  });
$('.slider-nav').slick({
slidesToShow: 3,
slidesToScroll: 1,
asNavFor: '.slider-for',
dots: true,
centerMode: true,
focusOnSelect: true
});

A: If you are using Slick Slider Version: 1.5.5
you will need to call afterChange on().

// function event,slick and index
// version 1.5+ uses slick-current stead of slick-active
$('.slider-for').on('afterChange', function(event,slick,i){
  $('.slider-nav .slick-slide').removeClass('slick-current');
  $('.slider-nav .slick-slide').eq(i).addClass('slick-current');
});

// remember document ready on this
$('.slider-nav .slick-slide').eq(0).addClass('slick-current');

A: http://jsfiddle.net/bpbaz10L/
$('.slider-for').slick({
    slidesToShow: 1,
    slidesToScroll: 1,
    arrows: false,
    fade: true,
    autoplay:true,
    //trigger after the slide appears
    // i is current slide index
    onAfterChange:function(slickSlider,i){
         //remove all active class
         $('.slider-nav .slick-slide').removeClass('slick-active');
         //set active class for current slide
         $('.slider-nav .slick-slide').eq(i).addClass('slick-active');
     }

});

//set active class to first slide
$('.slider-nav .slick-slide').eq(0).addClass('slick-active');

A: the dm4web answer is perfect if you are showing all the slides you have in your nav slider. If you have more slides that are hidden (say you have 12 slides, but show only 8 in your nav at once), you can do something similar, like
$('.slider-nav').on('afterChange', function(){

  $('.slider-nav .slick-slide').removeClass('current');
  $('.slider-nav .slick-active:first').addClass('current');
});

//set active class to first slide
$('.slider-nav .slick-active:first').addClass('current');

A: function _Slider(){
        $('#hm-slider ul').slick({
            dots: false,
            infinite: true,
            arrows:false,
            autoplay: true,
            autoplaySpeed: 5000,
            fade: true,
            slidesToShow: 1,
            slidesToScroll: 1,
            asNavFor: '#slider-dots',
        });
        $('#slider-dots').slick({
            slidesToShow: 5,
            slidesToScroll: 1,
            asNavFor: '#hm-slider ul',
            dots: false,
            centerMode: false,
            focusOnSelect: true,
            variableWidth: true,
            centerMode: true,
            useCSS:true
        });

        //set active class to first slide
        $('#slider-dots .slick-slide').removeClass('slick-active');
        $('#slider-dots .slick-slide').eq(0).addClass('slick-active');
        $('#hm-slider ul').on({
            beforeChange: function(event, slick, current_slide_index, next_slide_index) {
                //remove all active class
                $('#slider-dots .slick-slide').removeClass('slick-active');
                //set active class for current slide
                $('#slider-dots .slick-slide[data-slick-index='+next_slide_index+']').addClass('slick-active');
            }
        });

    }


text:
Q: How do I create custom routes in Ruby on Rails - 4.2 Right now I have the route as below;
resources :invoices do
  collection do
    match 'search' => 'invoices#search', via: [:get, :post], as: :search
  end
end

But I would like to get 'deliveries#search' instead of 'invoices#search'.
I successfully customized for the below routes;
get 'deliveries', to: 'invoices#index', as: :deliveries

get 'deliveries/new', to: 'invoices#new', as: :delivery

get 'deliveries/:id/edit', to: 'invoices#edit', :as => :del

I have tried but unable to customized for the 'deliveries#search'.
Any suggestions are most welcome.
Thank you in advance.

A: Change your routes as follows
resources :deliveries, controller: 'invoices', only: [:index, :new, :edit]
resources :deliveries, only: [] do
  collection do
    get :search
    post :search
  end
end

This will generate following routes for you:
        deliveries GET  /deliveries(.:format)           invoices#index
      new_delivery GET  /deliveries/new(.:format)       invoices#new
     edit_delivery GET  /deliveries/:id/edit(.:format)  invoices#edit
search_deliveries  GET  /deliveries/search(.:format)    deliveries#search
                   POST /deliveries/search(.:format)    deliveries#search

EDIT
According to your comment I think you just need to use different  controller
Try this
resources :deliveries, controller: 'invoices', only: [:index, :new, :edit] do
  collection do
    get :search
    post :search
  end
end

This will generate following routes:
search_deliveries  GET  /deliveries/search(.:format)    invoices#search
                   POST /deliveries/search(.:format)    invoices#search
        deliveries GET  /deliveries(.:format)           invoices#index
      new_delivery GET  /deliveries/new(.:format)       invoices#new
     edit_delivery GET  /deliveries/:id/edit(.:format)  invoices#edit

A: resources :invoices, path: 'deliveries' do
 collection do
  match 'search' => 'invoices#search', via: [:get, :post], as: :search
 end
end

it will generate route with prefix deliveries like /deliveries/your_action


text:
Q: Unable to connect to CRX repository using the JCR API from Felix environment I am trying to connect to CRX repository using JCR API. I followed the instruction at http://wiki.apache.org/jackrabbit/RemoteAccess. If I write a plain java class and try to access the crx repository using
JcrUtils.getRepository("http://localhost:7402/crx/server");

it works perfect.
If I create it as bundle and deploy it in Felix, it does not work. I have put all the required dependencies in there.

A: Use the Jackrabbit standalone jar, you would be able to modify the nodes in the repository


text:
Q: Github : Can I embed gist with comment? As we know, there is a Embed in gist.

Embed ——Embed this gist in your website.

If we want use it, we should input
<script src="https://gist.github.com/yourusername/yourgistid.js"></script>

but it doesn't have gist comments.
Can I ember gist with comment in my website (like github-pages and so on)?
Can I ember my project's issue comment in my website?


text:
Q: Secondary click does not register even though it is checked on (MacOS Big Sur) So I just updated to macOS Big Sur from Mojave. I had zero problems with right-clicking before the update, nor did I face them immediately after updating. However, after I shut down my iMac Pro, and started it after a while, I cannot right-click. So far, I have tried:

*

*Restarting(several times)

*Shutting down my mouse and powering it up again

*Deleting the mouse from  Bluetooth section of System preferences and reconnecting it with a USB.

So far, nothing has worked. I will appreciate all help!
Best regards
Edit: Re-installing the macOS Big Sur fixed the problem, but I would like to know if a more convenient method exists, should the problem repeat itself in future.

A: I re-installed Big Sur on my machine, by booting into the recovery mode. That seems to have solved the problem. However, if there are more convenient solutions than this, please let me know and I will select that as the accepted answer. Thanks!