text:
Q: Random number in time period How to solve a problem with Kotlin when I want to generate random numbers in time period (eg. 1 sec) and than than that numbers collect somehow and make Sum of that numbers.
Thanks

A: The routines of what you wanted are very simple. First, run a loop of how many random numbers that you want. Run a for loop that many times. Each time you generate a random number, add the value of that random number to a variable to keep track of the sum. Add that random number to a list. Then let the program go to sleep for a specific amount of time in milliseconds. The program below is a short example.
Note that, if the random number generated is a negative number, it will be flip back to its positive value. That will not work for integer.min value. However, this is just an example.
import java.util.Random
import kotlinx.coroutines.*

fun main() {
    val howManyNumber = 5
    val delayTime = 1000L  // ms
    val randomNumbers = mutableListOf<Int>()
    var sum = 0

    for (i in 1..howManyNumber){
        var randN = Random().nextInt()
        randN = if (randN > 0) randN else randN * -1
        sum += randN
        randomNumbers.add(randN)
        Thread.sleep(delayTime)
    }
    println(sum)
    println(randomNumbers)
}


text:
Q: Prove the square root of the absolute value of x squared equals the absolute value of x. $\sqrt{\lvert x^2\rvert}=\lvert x\rvert$ 2 attempts at a proof below, what do you think of them:
$$\sqrt{\lvert x^2\rvert}= \sqrt{\lvert xx\rvert} =\sqrt{\lvert x\rvert\lvert x\rvert}=\sqrt{\lvert x\rvert^2} = \lvert \lvert x\rvert \rvert = \lvert x\rvert$$
Alternatively, $\lvert x^2\rvert = x^2$ since $x^2$ is always >=0 this follows directly from the definition of absolute value. Now $\sqrt{x^2} = \lvert x\rvert$ by the alternate definition of absolute value.
Thus $\sqrt{x^2} = \sqrt{\lvert x^2\rvert} = \lvert x\rvert$

A: I think the second one is "more" correct, only in the sense that you are using the definition of absolute value to deduce a property of it. The first seems a bit redundant and be careful that you're using what you want to prove in the proof itself! Furthermore, be sure to define $x$ as a real number.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using dates in the "where" clause of HQL query I am using the SQLite database and have the following persistent class (simplified):
public class Project
{
    public virtual int Id { get; set; }
    public virtual DateTime StartDate { get; set; }
}

which is mapped to this table in the database:
CREATE TABLE projects (
    id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
    start_date DATETIME
)

Now I need to write a query that will select all the projects that have started in a given month.
In SQL I could use:
SELECT id FROM projects WHERE strftime('%m', start_date) = '12'

What I dislike about this query is that it uses the database specific function "strftime".
So the following HQL is dependent on the underlying database:
// Get all projects that started in December (no matter which year)
var projects = session
    .CreateQuery(
        "from Project p " +
        "where strftime('%m', p.StartDate) = :month")
    .SetParameter("month", "12")
    .List<Project>();

I have also tried "from Project p where p.StartDate.Month = 12" but it didn't work.
So using HQL or criteria API is it possible to write such a query in a database agnostic way?

A: If you're regularly querying against months, days, years, you shouldn't really be storing your date as a DateTime column - it makes the queries incredibly inefficient. You could easily create a "Month" column and query against that (and your DBA would love you again)

A: I would highly recommend you to write a custom function.
http://ayende.com/Blog/archive/2006/10/01/UsingSQLFunctionsInNHibernate.aspx
I don't mean the sql function, I mean the NHibernate function that is registered with RegisterFunction to enhance the NHibernate dialect.
Another probably better example:
http://ayende.com/Blog/archive/2007/04/27/Paged-data--Count-with-NHibernate-The-really-easy-way.aspx

A: from Project p where p.StartDate.ToString("M");


text:
Q: Annotating a Sum results in None rather than zero I'm making a QA site that is similar to the page you're on right now.  I'm attempting to order answers by their score, but answers which have no votes are having their score set to None rather than 0.  This results in answers with no votes being at the bottom of the page below negatively ranked answers.  How can I make the annotated score be zero when there are no votes for an answer?
Here's my model:
from django.contrib.auth.models import User

Answer(models.Model):
    //some fields here
    pass

VOTE_CHOICES = ((-1, Down), (1, Up))

Vote(models.Model):
    user = models.ForeignKey(User)
    answer = models.ForeignKey(Answer)
    type = models.IntegerField(choices = VOTE_CHOICES)

    class Meta:
        unique_together = (user, answer)

And here's my query:
answers = Answer.objects.filter(<something here>)
                        .annotate(score=Sum('vote__type'))
                        .order_by('-score')

edit: And to be clear, I'd like to do this in the query.  I know I could turn it into a list and then sort it in my python code, but I'd like to avoid that if possible.

A: You can use the Coalesce function from django.db.models.functions like:
answers = (Answer.objects
    .filter(<something here>)
    .annotate(score=Coalesce(Sum('vote__type'), 0))
    .order_by('-score'))

A: from django's documentation for Coalesce:

Prevent an aggregate Sum() from returning None.
The aggregate default argument uses Coalesce() under the hood.

So instead of using Coalesce, we can use the "default" argument:
answers = Answer.objects.filter(<something here>)
                    .annotate(score=Sum('vote__type', default=0))
                    .order_by('-score')

A: What about you use custom Manager? For example:
AnswerManager(models.Manager):
    def all_with_score(self):
       qs = self.get_query_set().annotate(score=Sum('vote__type'))
       # Here, you can do stuff with QuerySet, for example
       # iterate over all Answers and set 'score' to zero if None.

Answer(models.Model):
    //some fields here
    objects = AnswerManager()

Then, you can use:
>>> answers = Answer.objects.all_with_score().order_by('-score')


text:
Q: Can a user purchase multiple non-renewing Apple subscriptions to extend their expiration date? In the auto-renewable subscription system, it's not possible for a user to purchase a subscription more than one time.  You'd end up with a message that says like, "you're already subscribed."  However, with non-renewing subscriptions, my understanding is that it is entirely up to us how we want to handle it.
So let's say our subscription length is one year.  If a user purchases a subscription, and 6 months later (even though he/she still has 6 months remaining) decides to purchase another subscription, should we:

*

*Allow this, and add one year on top of his/her current expiration date, or

*Do not allow this with our own "you're already subscribed" message

Their documentation makes it super clear that implementation is entirely on us in the case of non-renewable subscriptions, but I can't find any rules for those implementations.  Is option 1) above even allowed, or are we supposed to follow suit with the auto-renewable system with option 2) ?
EDIT: The primary concern and reason I thought to ask this question is, if we allow multiple purchases, and say we have some crazy guy who buys like 50 subscriptions (50 years), and we stop our service before 50 years are up --- what happens?  Not a very realistic example, but we need to take such cases into account anyway.

A: Yes.
My app uses Non-Renewing Subscriptions and if a user purchases a 1-Month subscription twice, iOS will allow it and I've chosen to allow it. In that case, I just add the durations together to give the user 2 months.  Typically, iOS will pop up an alert (image below) telling the user "You've Already Purchased This Subscription. Tap Buy to renew or extend it."

I think it would be a good idea to limit the cumulative length of a subscription. You'd have to check their account on your server and then hide or disable the purchase button in the app since once the user starts a purchase, I'm pretty sure you can't interrupt or cancel it from your server.


text:
Q: Удаление файлов по регулярке Бывают ситуации, когда из папки нужно удалить все файлы с определенным суффиксом. Как это сделать с помощью одной комманды в vifm?

A: Собственно обнаружил такую возможность с помощью поиского фильтра в vifm. Делается это примерно так:
=some_pattern

при наборе все неподходящие под этот паттерн файлы и папки будут скрыты, после чего вы можете выбрать все оставшиееся и удалить


text:
Q: on component re rendering in react does the objects defined inside the component also created new as functions do on component re rendering in react does the objects defined inside the component also created new as functions do , if yes then if we are passing it as props then the particular child component would also be called , so it is wise to use useMemo hook , for example
const selected = useMemo(() => selectedColumn, [selectedColumn]);
I am confused for the same

A: It depends on what kind of value it is. Some kinds of value will always give you a new reference when the code is run again (objects, arrays, functions, etc.), while others will always give you the same reference (booleans, numbers, strings, etc.)
{} === {}               // false
[] === []               // false
(() => 3) === (() => 3) // false

false === false         // true
42 === 42               // true
"hello" === "hello"     // true

In the first case you should use useMemo, or useCallback for functions, or just avoid passing such values to the children if possible.
In the second case there is no point in using useCallback at all, because the new value is already equal to the old value.
Edit:
To clarify a bit more, when a component rerenders then all of its children, grandchildren, etc. rerender as well. This has nothing to do with props or useMemo. You can prevent it by using React.memo or by moving your state down to avoid rerendering components high up in the tree. See also https://overreacted.io/before-you-memo/

A: Yes. When a component re-renders, any objects or variables inside the components will be recreated, and will cause the child component to re-render if these objects/variables were passed as props.
Using useMemo hook will let you "memoize" the object/variable and it will prevent unnecessary re-renders.
In the example you have given above, child component will not rerender unless selectedColumn has changed.
Please read docs below for more details.
https://beta.reactjs.org/reference/react/useMemo#skipping-re-rendering-of-components


text:
Q: PHP Form Script Security Issue I have a short php code to process a simple form. I want to make sure that the code is secure. I think it probably is secure but I am not 100% sure.
I am looking for some feedback so I can be sure the php is not vulnerable to attacks.
Here is the php:
<?php
if(!isset($_POST['submit']))
{
    //This page should not be accessed directly. Need to submit the form.
    echo "error; you need to submit the form!";
}
$name = $_POST['name'];
$visitor_email = $_POST['email'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($visitor_email))
{
    echo "Name and email are mandatory!";
    exit;
}

if(IsInjected($visitor_email))
{
    echo "Bad email value!";
    exit;
}

$email_from = 'someemail@some.com';//<== update the email address
$email_subject = "New Form submission";
$email_body = "You have received a new message from the user $name.\n".
    "Here is the message:\n $message".

$to = "someemail@some.com";//<== update the email address
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $visitor_email \r\n";
//Send the email!
mail($to,$email_subject,$email_body,$headers);
//done. redirect to thank-you page.
header('Location: thank-you.html');

// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
              '(\r+)',
              '(\t+)',
              '(%0A+)',
              '(%0D+)',
              '(%08+)',
              '(%09+)'
              );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
    {
    return true;
  }
  else
    {
    return false;
  }
}

?>

A: Here's a style that I like to use for forms. I use error collection that stores all errors in an array and only progresses if it is empty.And you should not only try to attempt to stop injection attempts in the email field, you should validate and clean up any data you receive from a user
 <?php
    if(($_SERVER['REQUEST_METHOD'] !="POST") || !isset($_POST['submit'])){
        //This page should not be accessed directly. Need to submit the form.
        $errors[]= "error; you need to submit the form!";
    }else{
        //Strip tags and slashes from the user input
        //If these fields are optional we will not produce an error if they're blank
        $name = strip_tags(stripslashes($_POST['name']));
        $visitor_email = strip_tags(stripslashes($_POST['email']));
        $message = strip_tags(stripslashes($_POST['message']));

        //Validate firs
        if(empty($name)||empty($visitor_email)){
            $errors[]= "Name and email are mandatory!";
        }

        if(empty($errors)){
            if(IsInjected($visitor_email)){
                errors[]= "Bad email value!";
            }
            $email_from = 'someemail@some.com';//<== update the email address
            $email_subject = "New Form submission";
            $email_body = "You have received a new message from the user $name.\n"."Here is the message:\n $message".

            $to = "someemail@some.com";//<== update the email address
            $headers = "From: $email_from \r\n";
            $headers .= "Reply-To: $visitor_email \r\n";

            //Send the email!
            if(mail($to,$email_subject,$email_body,$headers)){
                //done. redirect to thank-you page.
                header('Location: thank-you.html');
            }else{
                $errors[]="Unable to send email";
            }
      }

 }//End of main block

 if(!empty(errors)){
    //Display errors to user
 }

 // Function to validate against any email injection attempts
 function IsInjected($str){
    $injections = array('(\n+)',
          '(\r+)',
          '(\t+)',
          '(%0A+)',
          '(%0D+)',
          '(%08+)',
          '(%09+)'
          );
    $inject = join('|', $injections);
    $inject = "/$inject/i";
    if(preg_match($inject,$str)){
        return true;
    }else{
        return false;
    }
 }

?>


text:
Q: jQuery Animate Individual Elements I am trying to animate a few elements independently. As a start I have tried one such element whose class & id i have defined as "star". When the element moves 800 px from its original position I want it to stop. And I have correctly done that. But the issue is bringing it back to its original position. I want it to start going back once the element is visible on the screen. Currently it stops at 800px. If I keep on scrolling to further right it stays there at 800px. But when i start scrolling left it starts moving left immediately. So i can't see the desired effect. And please also tell me if there is a better way of doing the same thing. Because the way I am doing it, I am afraid it is going to get very complicated when I try to animate more elements
$(function() {
var lastmove = 0;
$("body").mousewheel(function(event, delta) {
    this.scrollLeft -= (delta * 30);
    var move = 0;
    var move1 = 0;
    if (lastmove == 0 && delta == 1) {
        //do nothing
    }
    else {
        move = (lastmove * delta * -1) + 30;
    }
    if ((lastmove-move) > 30) { move = move * -1; }
    if (move > 800) {
        move = 800;
    }
    var position = $("#star").position();
    if (position.left < 0) { move = 0; }
    if (position.left > 800) { move = 800; }
    lastmove = move;
    $(".star").stop().animate({left: move}, "slow");
    event.preventDefault();
            });
         });

jsfiddle link

A: See this: http://jsfiddle.net/MZUhh/1/
  if(this.scrollLeft > 800 && delta == 1) return false;

Simplified Code:
$(function () {
$("body").mousewheel(function (event, delta) {
  this.scrollLeft -= (delta * 30);
  if (this.scrollLeft > 800) return false;
  $(".star").stop().animate({left: this.scrollLeft}, "slow");
  event.preventDefault();
});
});

Demo


text:
Q: How to tell AutoMapper to use "pass by reference?" By default automapper creates a new object based on the destination's type:
public void Doit( Person personMissingStuff )
{
    PersonTemplate template = _personDao.GetPersonTemplate(1);
    Mapper.CreateMap<PersonTemplate, Person>();
    Person basePerson = Mapper.Map<Person>( template );
    Mapper.CreateMap<Person, Person>();
    Person completePerson =
       Mapper.Map<Person, Person>( basePerson, personMissingStuff );
    ...
}

Instead of getting a completePerson I just get a basePerson again.  How do I tell AutoMapper to run the mappings by reference instead of by value?

A: Mapper.Map(source, dest) actually returns the destination object, in your case it'll be personMissingStuff.
With that said, assuming that you want to fill in only the null properties in the destination, you need to configure the mapping properly, and not map when the destination property has value.
The following sample does exactly this for class properties. For value properties, probably you need to do additional configuration. The example uses NUnit and SharpTestsEx:
[TestFixture]
public class LoadIntoInstance
{
    public class Template
    {
        public string Name { get; set; }
    }

    public class Person
    {
        public string Name { get; set; }
        public string OtherData { get; set; }
    }

    [Test]
    public void Should_load_into_instance()
    {
        Mapper.CreateMap<Template, Person>()
            .ForMember(d=>d.OtherData, opt=>opt.Ignore());
        Mapper.CreateMap<Person, Person>()
            .ForAllMembers(opt=>opt.Condition(ctx=>ctx.DestinationValue==null));
        Mapper.AssertConfigurationIsValid();

        var template = new Template {Name = "template"};
        var basePerson = Mapper.Map<Person>(template);

        var noNamePerson = new Person {OtherData = "other"};

        var result = Mapper.Map(basePerson, noNamePerson);

        result.Should().Be.SameInstanceAs(noNamePerson);
        result.Satisfy(r =>
                       r.Name == "template" &&
                       r.OtherData == "other");
    }
}

A: Just use traditional shallow cloning...
Person completePerson = basePerson.MemberwiseClone();

This should keep the reference types and clone the value types.
MSDN Link


text:
Q: Support for basic datatypes in H5Attributes? I am trying out the beta hdf5 toolkit of ilnumerics.
Currently I see H5Attributes support only ilnumerics arrays. Is there any plan to extend it for basic datatypes (such as string) as part of the final release?
Does ilnumerics H5 wrappers provide provision for extending any functionality to a particular
datatype?

A: ILNumerics internally uses the official HDF5 libraries from the HDF Group, of course. H5Attributes in HDF5 correspond to datasets with the limitation of being  not capable of partial I/O. Besides that, H5Attributes are plain arrays! Support for basic (scalar) element types is given by assuming the array stored to be scalar.
Strings are a complete different story: strings in general are variable length datatypes. In terms of HDF5 strings are arrays of element type Char. The number of characters in the string determines the length of the array. In order to store a string into a dataset or attribute, you will have to store its individual characters as elements of the array. In ILNumerics, you can convert your string into ILArrray or ILArray (for ASCII data) and store that into the dataset/ attribute.
Please consult the following test case which stores a string as value into an attribute and reads the content back into a string.
Disclaimer: This is part of our internal test suite. You will not be able to compile the example directly, since it depends on the existence of several functions which may are not available. However, you will be able to understand how to store strings into datasets and attributes:
public void StringASCIAttribute() {
    string file = "deleteA0001.h5";
    string val = "This is a long string to be stored into an attribute.\r\n";
    // transfer string into ILArray<Char>
    ILArray<Char> A = ILMath.array<Char>(' ', 1, val.Length);
    for (int i = 0; i < val.Length; i++) {
        A.SetValue(val[i], 0, i);
    }
    // store the string as attribute of a group
    using (var f = new H5File(file)) {
        f.Add(new H5Group("grp1") {
            Attributes = {
                { "title", A }
            }
        });
    }
    // check by reading back
    // read back
    using (var f = new H5File(file)) {
        // must exist in the file
        Assert.IsTrue(f.Get<H5Group>("grp1").Attributes.ContainsKey("title"));
        // check size
        var attr = f.Get<H5Group>("grp1").Attributes["title"];
        Assert.IsTrue(attr.Size == ILMath.size(1, val.Length));
        // read back
        ILArray<Char> titleChar = attr.Get<Char>();
        ILArray<byte> titleByte = attr.Get<byte>();

        // compare byte values (sum)
        int origsum = 0;
        foreach (var c in val) origsum += (Byte)c;
        Assert.IsTrue(ILMath.sumall(ILMath.toint32(titleByte)) == origsum);

        StringBuilder title = new StringBuilder(attr.Size[1]);
        for (int i = 0; i < titleChar.Length; i++) {
            title.Append(titleChar.GetValue(i));
        }
        Assert.IsTrue(title.ToString() == val);
    }
}

This stores arbitrary strings as 'Char-array' into HDF5 attributes and would work just the same for H5Dataset.

A: As an alternative solution you may use HDF5DotNet (http://hdf5.net/default.aspx) wrapper to write attributes as strings:
H5.open()
Uri destination = new Uri(@"C:\yourFileLocation\FileName.h5");
//Create an HDF5 file
H5FileId fileId = H5F.create(destination.LocalPath, H5F.CreateMode.ACC_TRUNC);
//Add a group to the file
H5GroupId groupId = H5G.create(fileId, "groupName");

string myString = "String attribute";
byte[] attrData = Encoding.ASCII.GetBytes(myString);

//Create an attribute of type STRING attached to the group
H5AttributeId attrId = H5A.create(groupId, "attributeName", H5T.create(H5T.CreateClass.STRING, attrData.Length),
               H5S.create(H5S.H5SClass.SCALAR));
//Write the string into the attribute
H5A.write(attributeId, H5T.create(H5T.CreateClass.STRING, attrData.Length), new H5Array<byte>(attrData));

H5A.close(attributeId);
H5G.close(groupId);
H5F.close(fileId);
H5.close();


text:
Q: EF 6 calls INSERT instead of UPDATE This could be a duplicate question but a lot of searching for the words in the title only got me a lot of unrelated results.
I have an entity that's roughly set up like this:
public abstract class A
{
    public GUID AId { get; set; }

    public string SomeProperty { get; set; }
}

public class B : A
{
    public string SomeOtherProperty { get; set; }
}

The context has public DbSet<B> BInstances { get; set; } for B objects. In OnModelCreating, the mapping has A set to ignored and B is mapped to a table called TableB.
The AId field is not auto-generated (not an identity field) but it's set to be primary key, both in the database and in the mapping. In the database, the field is defined as a non-null uniqueidentifier with no default.
At runtime, I'm loading an instance of B using its key (_token is just a CancellationToken):
var b = await (dbCtx.BInstances.FirstOrDefaultAsync(e => e.AId), _token));

Then, a property of b is set and I try to save it back to database:
b.SomeOtherProperty = "some new text";
await (dbCtx.SaveChangesAsync(_token));

At this point, I'm getting a Violation of PRIMARY KEY constraint error from the database, stating that the value of AId cannot be inserted because it'd be a duplicate. Of course, the ID is already in the database, I loaded the entity from there, using the ID. For some reason, EF generates an INSERT statement, not an UPDATE and I don't understand why.
When I check dbCtx.Entry(b).State, it's already set to EntityState.Modified. I'm at a loss - can someone point out what I'm doing wrong? I never had issues with updating entities before but I haven't used EF with GUID primary keys (usually I use long primary keys).
I'm using EF 6 and .NET Framework 4.7.1.

A: Thank you all for the suggestions - this turned out to be a mapping problem that I caused.
In my OnModelCreating() call, I called MapInheritedProperties() on a type that didn't inherit from a base class (other than object, of course) - this seems to have triggered a problem. Other entities that do share a base class worked fine with the mapping call.
I also called ToTable() directly against the entity class - this broke my table mapping for reasons I do not understand. Once I moved that call inside Map(), it started working as expected.
So I went from this:
entity.ToTable("tablename");

to this:
entity.Map(m => m.ToTable("tablename"));

to solve the problem.
Hopefully this will be useful for future readers.

A: try this
b.SomeOtherProperty = "some new text";
dbCtx.BInstances.AddOrUpdate(b);
await (dbCtx.SaveChangesAsync(_token));

AddorUpdate will update your b instance if it is already added.


text:
Q: Buttonclick event based on DataGrid selected value I am making a small application for personal use to practice WPF and C#.  The application will launch games (or other applications) based on file paths which are stored in a SQL table.  My SQL connection works fine and the data is retrieved.
string query = "SELECT Title, [Path] FROM GOG.dbo.Games";

I am using a DataGrid control to display the list of games, and their paths.  I have a 'Launch Game' button which I would like to get the currently highlighted item in the DataGrid (i.e. the Path) and then take the path string and therefore run it using the Process.Start() method.
Here's what I have on my Button_Click but I can't get it to work:
private void LaunchButton_Click(object sender, RoutedEventArgs e)
{
    string gamePath = dataGrid1.SelectedItem.ToString();
    Process.Start(gamePath);
}

Debug says "gamePath "System.Data.DataRowView" string", and not the value of the actual path e.g: "C:\Windows\System32\calc.exe" which I think is why the application bugs out saying "The system cannot find the file specified" because "System.Data.DataRowView" is of course not a valid program.
How can I get it to put the correct string through instead of "System.Data.DataRowView"?

A: dataGrid1.SelectedItem gives you System.Data.DataRowView object. So you can use it directly as string. you must get path from it like following.
private void LaunchButton_Click(object sender, RoutedEventArgs e)
{
    var row=dataGrid1.SelectedItem as System.Data.DataRowView;
    if(row!=null)
    {
       string gamePath = row["Path"].ToString();
       Process.Start(gamePath);
    }
}

A: cast selected item of DataGrid to DataRowView
DataRowView row = (DataRowView)dataGrid1.SelectedItem;

then
row["ColumnName"];


text:
Q: The requested URL was not found on this server in cordova for the facebook plugin in react? i actually used the facebook login npm in react and i tried on my browser it works when i run on ios devices using cordova,it shows the following error
Failed to load webpage with error: The requested URL was not found on this server.
i don't know how to fix this? can anyone help me.here my samples
<FacebookLogin
                       appId="XXXXX682921631"
                       language="en_US"
                       scope="public_profile,email"
                       callback={this.responseFacebook}
                       xfbml={true}
                       fields="id,email,name"
                       cookie={true}
                       version="v2.10"
                       className="facebook-login"
                       textButton="Login With Facebook"/>

and i use my http://localhost:8080/ it works on browser and i ain't know about the mobile what to give and where to give


text:
Q: Why won't textbox validation within a custom window work? I am building a WPF application (abiding to the MVVM design pattern) and the validation I have applied to the properties of my models works fine (the code part) regardless of what type of window the textbox is within. However, regarding the default Validation.ErrorTemplate for a textbox which gives it a red outline if there is an error... well this only shows when the textbox is used with a standard Window, and doesn't if it is within my CustomWindow or CustomDialog. Both of these custom controls inherit from the Window class and only override aesthetical features of the base Window.
To re-iterate the point that the problem definitely lies within my custom windows - I can literally swap the xaml tags from CustomWindow to Window and all is well.
So, what I am thinking is that I need to specifically define a Validation.ErrorTemplate within the theme for the custom windows, i.e. like when you override a button template - if you don't define an on hover style it won't have one! BUT I have no idea how to go about doing this and/or if it is even possible and I can't find anything to help me via Google.
Any advice/guidance/help is greatly appreciated!

A: It is indeed possible. Take the following example (from the linked page at MSDN):
<TextBox Name="textBox1" Width="50" FontSize="15"
         Validation.ErrorTemplate="{StaticResource validationTemplate}"
         Style="{StaticResource textBoxInError}"
         Grid.Row="1" Grid.Column="1" Margin="2">
    <TextBox.Text>
        <Binding Path="Age" Source="{StaticResource ods}"
             UpdateSourceTrigger="PropertyChanged" >
            <Binding.ValidationRules>
                <c:AgeRangeRule Min="21" Max="130"/>
            </Binding.ValidationRules>
        </Binding>
    </TextBox.Text>
</TextBox>

Now we define the template:
<ControlTemplate x:Key="validationTemplate">
    <DockPanel>
        <TextBlock Foreground="Red" FontSize="20">!</TextBlock>
            <AdornedElementPlaceholder/>
    </DockPanel>
</ControlTemplate>

You can find out more from the Validation.ErrorTemplate Attached Property page at MSDN.

A: Finally found another question related to my problem and a solution that works!
I had left out the adorner layer in the control templates for my custom windows. I don't want to steal the solution so please see the original answer here - Error template not working when a ControlTemplate is applied to the window.


text:
Q: CoreData Cache Error with NSPredicate Why does this produce a caching error after adding the if statements to the NSPredicate? The error arrives after I attempt to filter the results based on the title of the UITABLEVIEW.
I get the following error:
CoreData: FATAL ERROR: The persistent cache of section information does not match the current configuration.  You have illegally mutated the NSFetchedResultsController's fetch request, its predicate, or its sort descriptor without either disabling caching or using +deleteCacheWithName

I have looked at other similar errors but can't relate them to my code.
- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"ExcerciseInfo" inManagedObjectContext:managedObjectContext];
    [fetchRequest setEntity:entity];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"details.muscle" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    [fetchRequest setFetchBatchSize:20];

// Sort Results
if ([self.title isEqual: @"Abdominals"]) {

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"details.muscle == %@", @"Back"];
    [fetchRequest setPredicate:predicate];

     }

else if ([self.title isEqual: @"Arms"]) {

        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"details.muscle == %@", @"Biceps"];
        [fetchRequest setPredicate:predicate ];

    }

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:managedObjectContext sectionNameKeyPath:nil
                                                   cacheName:@"Root"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}

A: When you leave the view, you need in the tableViewController:
 -(void)viewDidDisappear:(BOOL)animated{
     [super viewDidDisappear:animated];
     [NSFetchedResultsController deleteCacheWithName:@"Root"];
     self.fetchedResultsController = nil;

 }

And also:
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        [NSFetchedResultsController deleteCacheWithName:@"Root"];
    }
    return self;
}

or the best form is here (all together):
- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        // Custom initialization
        [NSFetchedResultsController deleteCacheWithName:@"Root"];
        self.fetchedResultsController = nil;
    }
    return self;
}

A: Basically, if you use a cacheName with a fetched results controller you shouldn't change the fetch request.
If you do change the fetch request you must delete the cache, otherwise you get errors related to the cache contents no longer matching your fetched results.
If you want to change the fetch request you generally don't gain any benefit from having a cache.


text:
Q: how to wait till a function to end to continue the code node js so i have a captcha harvester that i solve captcha manually to obtain the token of the captcha,
so what i want to do is to wait till I finish solving the captcha and get the token and send the token  and  call a function to finish the checkout, what happening here is the functions are being called before i finish solving the captcha for example in code(will not put the real code since it's really long)
SolvingCaptcha = function() {
  token = "1234"
  token_list.push(token)
}

final_token = token_list[0]

//puppeteer code.
await SolvingCaptcha();
document.getElementById("g-recaptcha-response").innerHTML = {
  final_token
}

checkoutJsonCall();

long story short I want the token variable to be declared before it continues to the next functions
the function that I want to execute after the captcha solving is completed
thank u in advance and sorry for the lack of skills in explanation  :p
EDIT: to be clear here it's a very time-sensitive operation so I cant do sleep or wait or anything I just need it to execute exactly after it finished.Thank u
EDIT 2 : the code wait till the captcha harvester to load the captcha, but don't wait until i solve it.

A: Hello,u can just do  while loop that check the variable if its defined or yet and set a timeout if it didnt.
const SolvingCaptcha = function() {

function waitForElement(){
    tokenn = TOKEN_LIST[0]

    console.log(tokenn)
   while(typeof tokenn !== "undefined"){
        //variable exists, do what you want

        setTimeout(waitForElement,1500);//so this refreash every 1.5sec to check if to recheck if the tokenn is defined or yer
    }
}
 waitForElement();
  }

const function2 = function(){

solvingcaptcha();

//what ever you want to do next
}

hope this helps out

A: You can use promise as a wrapper for your solvingCaptcha and once user indicate that it has solved the capcha or I guess you must have some way of knowing that user has solved the capcha so once you know it,  call resolve callback to execute later code
const SolvingCaptcha = function() {
   return new Promise((resolve, reject) => {
   //solving captcha
      if(captchaSolvedEvent) {
          token = "1234"
          token_list.push(token)
          resolve(); // this is the important part here, we are resolving means our work is done i.e captcha is solved, no need to call this until user solves the capcha
      }
   }
}

async function yourMainFunction() {
    await SolvingCaptcha();
    final_token=token_list[0]
    //puppeteer code.
    document.getElementById("g-recaptcha-response").innerHTML={final_token}
    checkoutJsonCall();
}

note that you have to make your function marked with async if you are using await , here await indicate that no code below it will passed as callback to be executed in js stack until promise is resolved from our solvingCapcha function


text:
Q: prevent user fom logging back in after logging out by hitting back button I am using a PHP login script that challenges user for username & password.
Once authenticated program stores a session value. On logout, session value is set to blanks.
Once logged out I want to avoid allowing user hitting the back button a few times and and betting allowed to see screen of data or accidentaly logging himself back in.
I am using sessions, a re-direct to send validated user to a new page. I am also using ob_start, ob_flush and ob_end_clean to prevent error or re-direct.
Questions:
Is this really secure?
Is this a common approach?
Is there alterternative to buffering?
below is a small proof-of-concept.
<?php
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Pragma: public");
session_cache_limiter('nocache');
// I'm not sure how effective any of the above seem to be.

session_start();

// start buffering because if we use header later we want to avoid error
ob_start();

echo "Type in or out to login/logout
";
?>

 <form action='' method='POST'>
 <input type='text' name='status' size='10' value="">

 <input type='submit' name='Login' value='Login' /></form>

<?php
 if ($_POST['status'] == 'in')
 {
  $_SESSION['logged_in'] = 'in';
  ob_end_clean();  // clean and erase buffer so far
        header('location:test2.php');
        exit;
 }

 if ($_POST['status'] == 'out')
 {
  $_SESSION['logged_in'] = 'no';
  echo "you are logged out
";

 }
 ob_flush();   // push output
 echo "login status = " . $_SESSION['logged_in']  ;

?>

file test2.php
<?php
echo "You have logged in";
?>

A: I would start with destroying the session with session_destroy() rather than just set the 'logged_in' value to 'no'.
Then just check to see if the session exists to see if the user is logged in.

A: What you need is a proper logout method rather than testing session data. You want the session to be wiped competely. Here is an example that logs the user in and logs the user out and also checks if the user is logged in. When you click the logout page you're automatically logged out and redirected. Clicking back won't change anything you still won't be logged in.
login.php
session_start();
$valid = someLoginFunctionHere();
if($valid) {
     $_SESSION['isLoggedIn'] = true;
     header("Location: homepage.php");
}

homepage.php
session_start();
// If they are not logged in, send them to login page
if(!isset($_SESSION['isLoggedIn'])) {
    header("Location: login.php");
}

// Normal homepage stuff
...

logout.php
session_start();
session_destroy();
header("Location: login.php");

Hope this helps demystify sessions a bit for you.


text:
Q: Why wont my onTap method work, How do I make my onTap method lead to another page? I am making an app with flutter and in my application I made an hidden drawer by putting 2 pages in a Stack widget and when I click on the menu icon, the homepage gets an offset and the drawer screen becomes visible. On the drawerscreen I have 2 selfmade buttons which are supposede to lead you to another page.
My drawer in my homepage is setup with an AnimatedContainer>Listview>Column>Container as in the code below.
import 'package:flutter/material.dart';
import 'package:paws_up/components/buttons/animated_button.dart';
import 'package:paws_up/components/buttons/category_button.dart';
import 'package:paws_up/pages/product_overview_page.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class HomeScreen extends StatefulWidget {
  const HomeScreen({super.key});

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  double xOffset = 0;
  double yOffset = 0;
  double scaleFactor = 1;
  bool isDrawerOpen = false;

  @override
  Widget build(BuildContext context) {
    return AnimatedContainer(
      decoration: BoxDecoration(
          color: Colors.white, borderRadius: BorderRadius.circular(40)),
      duration: const Duration(milliseconds: 250),
      transform: Matrix4.translationValues(xOffset, yOffset, 0)
        ..scale(scaleFactor),
      child: ListView(
        children: [
          Column(
            children: [
              Container(
                margin: const EdgeInsets.symmetric(
                  horizontal: 20,
                ),
                height: 70,
                color: Colors.white,
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    isDrawerOpen
                        ? IconButton(
                            onPressed: () {
                              setState(() {
                                xOffset = 0;
                                yOffset = 0;
                                scaleFactor = 1;
                                isDrawerOpen = false;
                              });
                            },
                            icon: const Icon(
                              Icons.chevron_left_rounded,
                              color: Color.fromARGB(255, 0, 0, 0),
                            ),
                          )
                        : IconButton(
                            onPressed: () {
                              setState(() {
                                xOffset = 230;
                                yOffset = 150;
                                scaleFactor = 0.6;
                                isDrawerOpen = true;
                              });
                            },
                            icon: const Icon(
                              Icons.menu,
                              color: Color.fromARGB(255, 0, 0, 0),
                            ),
                          ),
                    const Text(
                      'PawsUp',
                      style: TextStyle(
                          color: Color(0xff363636),
                          fontFamily: 'Ubuntu',
                          fontWeight: FontWeight.bold,
                          fontSize: 24),
                    ),
                    Row(
                      children: [
                        IconButton(
                          icon: const Icon(Icons.notifications_outlined,
                              color: Color(0xff363636)),
                          onPressed: () {
                            // do something
                          },
                        ),
                        IconButton(
                          icon: const Icon(Icons.person_outline_rounded,
                              color: Color(0xff363636)),
                          onPressed: () {
                            // do something
                          },
                        ),
                      ],
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(
                  vertical: 30,
                  horizontal: 20,
                ),
                decoration: BoxDecoration(
                    color: const Color.fromARGB(255, 247, 247, 247),
                    borderRadius: BorderRadius.circular(8)),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Row(
                      children: [
                        IconButton(
                          icon: const Icon(FontAwesomeIcons.filter,
                              color: Color(0xff5891AC)),
                          onPressed: () {},
                        ),
                        const Text(
                          'Search..',
                          style: TextStyle(
                              color: Color(0xffCAC9C9),
                              fontFamily: 'Poppins',
                              fontWeight: FontWeight.bold,
                              fontSize: 16),
                        ),
                      ],
                    ),
                    Container(
                      decoration: BoxDecoration(
                        color: const Color(0xff5891AC),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: IconButton(
                        onPressed: () {},
                        icon: const Icon(
                          FontAwesomeIcons.magnifyingGlass,
                          color: Colors.white,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                margin: EdgeInsets.symmetric(horizontal: 20),
                height: 140,
                decoration: BoxDecoration(
                  color: const Color(0xffD5E5F4),
                  borderRadius: BorderRadius.circular(15.0),
                ),
                child: Stack(
                  children: [
                    Positioned(
                      top: 50,
                      left: 135,
                      child: ClipRRect(
                        borderRadius: const BorderRadius.only(
                            topLeft: Radius.circular(0),
                            topRight: Radius.circular(0),
                            bottomLeft: Radius.circular(0),
                            bottomRight: Radius.circular(15)),
                        child: Image.asset(
                          'images/Banner_photo.jpg',
                          height: 90.0,
                          width: 190.0,
                          fit: BoxFit.cover,
                        ),
                      ),
                    ),
                    Positioned(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          const Padding(
                            padding: EdgeInsets.fromLTRB(15, 8, 0, 8),
                            child: Text(
                              'Join our animal loving community',
                              style: TextStyle(
                                  color: Colors.white,
                                  fontFamily: 'Poppins',
                                  fontWeight: FontWeight.bold,
                                  fontSize: 20),
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.fromLTRB(15, 0, 0, 0),
                            child: AnimatedButton(
                              height: 40,
                              width: 100,
                              text: 'Join Now',
                              textColor: const Color(0xffD5E5F4),
                              buttonColor: Colors.white,
                              onTap: () {
                                Navigator.push(
                                  context,
                                  MaterialPageRoute(
                                      builder: (context) =>
                                          const ProductOverviewPage()),
                                );
                              },
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(
                  vertical: 30,
                  horizontal: 20,
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        const Text(
                          'Pet Categories',
                          style: TextStyle(
                            color: Color(0xff363636),
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                        const Spacer(),
                        TextButton(
                          onPressed: () {},
                          child: const Text(
                            'More Categroies',
                            style: TextStyle(
                                color: Color(0xff5891AC), fontFamily: 'Ubuntu'),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 50,
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: const [
                          CategoryButton(
                            text: 'Cat',
                            buttonColor: Colors.white,
                            selectedButtonColor: Color(0xff5891AC),
                            contentColor: Color(0xff363636),
                            selectedContentColor: Colors.white,
                            isSelected: false,
                            icon: FontAwesomeIcons.cat,
                          ),
                          CategoryButton(
                            text: 'Dog',
                            buttonColor: Colors.white,
                            selectedButtonColor: Color(0xff5891AC),
                            contentColor: Color(0xff363636),
                            selectedContentColor: Colors.white,
                            isSelected: false,
                            icon: FontAwesomeIcons.dog,
                          ),
                          CategoryButton(
                            text: 'Fish',
                            buttonColor: Colors.white,
                            selectedButtonColor: Color(0xff5891AC),
                            contentColor: Color(0xff363636),
                            selectedContentColor: Colors.white,
                            isSelected: false,
                            icon: FontAwesomeIcons.fish,
                          ),
                          CategoryButton(
                            text: 'Bird',
                            buttonColor: Colors.white,
                            selectedButtonColor: Color(0xff5891AC),
                            contentColor: Color(0xff363636),
                            selectedContentColor: Colors.white,
                            isSelected: false,
                            icon: FontAwesomeIcons.dove,
                          ),
                        ],
                      ),
                    )
                  ],
                ),
              ),
              Container(
                margin: const EdgeInsets.symmetric(
                  vertical: 30,
                  horizontal: 20,
                ),
                child: Column(
                  children: [
                    Row(
                      children: [
                        const Text(
                          'Adopt Us',
                          style: TextStyle(
                            color: Color(0xff363636),
                            fontFamily: 'Poppins',
                            fontWeight: FontWeight.bold,
                            fontSize: 20,
                          ),
                        ),
                        const Spacer(),
                        TextButton(
                          onPressed: () {
                            Navigator.push(
                              context,
                              MaterialPageRoute(
                                  builder: (context) =>
                                      const ProductOverviewPage()),
                            );
                          },
                          child: const Text(
                            'See All',
                            style: TextStyle(
                                color: Color(0xff5891AC), fontFamily: 'Ubuntu'),
                          ),
                        ),
                      ],
                    ),
                    SizedBox(
                      height: 50,
                      child: ListView(
                        scrollDirection: Axis.horizontal,
                        children: const [],
                      ),
                    )
                  ],
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}

The drawerScreen code is as follows:
import 'package:flutter/material.dart';
import 'package:paws_up/components/buttons/drawer_button.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:paws_up/pages/home_page.dart';
import 'package:paws_up/pages/product_overview_page.dart';

class DrawerScreen extends StatefulWidget {
  const DrawerScreen({super.key});

  @override
  State<DrawerScreen> createState() => _DrawerScreenState();
}

class _DrawerScreenState extends State<DrawerScreen> {
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
        color: Color(0xffD5E5F4),
      ),
      child: SafeArea(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Container(
              padding: const EdgeInsets.symmetric(
                vertical: 20,
                horizontal: 20,
              ),
              child: Row(
                children: [
                  const CircleAvatar(),
                  Padding(
                    padding: const EdgeInsets.symmetric(horizontal: 20),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: const [
                        Text(
                          'Firstname Lastname',
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Ubuntu',
                              fontWeight: FontWeight.bold,
                              fontSize: 20),
                        ),
                        Text(
                          'Location',
                          style: TextStyle(
                              color: Colors.white,
                              fontFamily: 'Poppins',
                              fontSize: 16),
                        )
                      ],
                    ),
                  )
                ],
              ),
            ),
            Container(
              child: Column(
                children: [
                  DrawerButton(
                    text: 'Home',
                    icon: Icons.home,
                    onTap: () {
                      Navigator.push(
                        context,
                        MaterialPageRoute(builder: (context) => HomeScreen()),
                      );
                    },
                  ),
                  DrawerButton(
                    text: 'Adopt',
                    icon: FontAwesomeIcons.paw,
                    onTap: () {
                      Navigator.of(context).push(
                        MaterialPageRoute(
                            builder: (context) => ProductOverviewPage()),
                      );
                    },
                  ),
                  // DrawerButton(
                  //   text: 'Donate',
                  //   icon: FontAwesomeIcons.circleDollarToSlot,
                  // ),
                  // DrawerButton(
                  //   text: 'Favorites',
                  //   icon: FontAwesomeIcons.solidHeart,
                  // ),
                  // DrawerButton(
                  //   text: 'Messages',
                  //   icon: FontAwesomeIcons.solidEnvelope,
                  // ),
                  // DrawerButton(
                  //   text: 'Profile',
                  //   icon: FontAwesomeIcons.solidUser,
                  // ),
                ],
              ),
            ),
            Container(
              padding: const EdgeInsets.fromLTRB(0, 20, 0, 70),
              child: Row(
                children: [
                  // DrawerButton(
                  //   text: 'Settings',
                  //   icon: FontAwesomeIcons.gear,
                  // ),
                  // DrawerButton(
                  //   text: 'Log in',
                  //   icon: FontAwesomeIcons.arrowRightToBracket,
                  // ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }
}

I think the problem lies in the DrawerButton. It is supposed to lead you to different pages but it doesn't. This is my DrawerButton code:
import 'package:flutter/material.dart';

class DrawerButton extends StatefulWidget {
  final String text;
  final IconData icon;

  DrawerButton({
    super.key,
    required this.text,
    required this.icon,
    required Null Function() onTap,
  });

  @override
  _DrawerButtonState createState() => _DrawerButtonState();
}

class _DrawerButtonState extends State<DrawerButton>
    with SingleTickerProviderStateMixin {

  late AnimationController _controller;
  late double _scale;

  @override
  void initState() {
    super.initState();
    _controller = AnimationController(
      vsync: this,
      duration: const Duration(milliseconds: 200),
      lowerBound: 0.0,
      upperBound: 0.1,
    )..addListener(() {
        setState(() {});
      });
  }

@override
  Widget build(BuildContext context) {
    _scale = 1 - _controller.value;
    return GestureDetector(
      onTapDown: _onTapDown,
      onTapUp: _onTapUp,
      child: Stack(
        children: [
          Transform.scale(
            scale: _scale,
            child: _DrawerButtonUi,
          ),
        ],
      ),
    );
  }

  Widget get _DrawerButtonUi => Container(
        padding: const EdgeInsets.symmetric(horizontal: 20, vertical: 15),
        child: Row(
          children: [
            Icon(
              widget.icon,
              color: Colors.white,
            ),
            Padding(
              padding: const EdgeInsets.symmetric(horizontal: 20),
              child: Text(
                widget.text,
                style: const TextStyle(
                  color: Colors.white,
                  fontFamily: 'Poppins',
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                ),
              ),
            ),
          ],
        ),
      );

  void _onTapDown(TapDownDetails details) {
    _controller.forward();
  }

  void _onTapUp(TapUpDetails details) {
    _controller.reverse();
  }
}

I thought maybe it had something to do with the stack widget I have in the gesturedetector of my DrawerButton. I have tried navigator.of(context).push instead of navigator.push, but that does not seem to make a difference.
But I am not quite sure how I can build that widget differently, keep the animation and have the navigator push work.
Does anybody have a solution?

A: You need to create a widget variable in order to access on state class.
class DrawerButton extends StatefulWidget {
  final String text;
  final IconData icon;
  final VoidCallback onTap; //this will be used
  const DrawerButton({
    super.key,
    required this.onTap,

And will be called on
  void _onTapDown(TapDownDetails details) {
    _controller.forward();
    widget.onTap();
  }


text:
Q: ClassNotFoundException when deploying ear containing one ApplicationLifecycleListener I have a demo enterprise application (ear) defined in Netbeans 7.4 with one Java EE module (war).
When i deploy the war to the Weblogic server, deployment is successful and the ServletContextListener is executed.
The same war file contains a class which extends ApplicationLifecycleListener. This class is defined as a listener in the weblogic-application.xml
<listener>
  <listener-class>com.reddipped.sysstats.jmx.mbean.SysStatsMBeanLifeCycleListener</listener-class>
</listener>

On deployment of the ear i get the following exception;
Deploying /home/developer/NetBeansProjects/SysStats/dist/wldeploy/SysStats
Deployment failed. The message was: java.lang.ClassNotFoundException: com.reddipped.sysstats.jmx.mbean.SysStatsMBeanLifeCycleListener
/home/developer/NetBeansProjects/SysStats/nbproject/build-impl.xml:301: The module has not been deployed.
The war is included in the ear... what am i missing here?
Package and classname are correct in the listener-class, even copied and pasted the names from the war file..
Cheers Peter
[update 09/19/2014]
Now split up the project in an enterprise application, web application and one jar file.
On deployment now het a weblogic.management.DeploymentException: classloader-structure element in weblogic-application.xml is referencing the module-uri SysStatsMBean.jar which does not exist in this application
When build the ear file now has the following structure.
SysStats.ear
  - SysStats-war.war
      - META-INF
      - WEB-INF
        - classes
          - com
            - reddipped
              - sysstats
                - model
                  - SystemInfo.class
                  - SystemInfoCollector.class
                  - SystemInfoCollectorExecutor.class
  - SysStatsMBean.jar
          - com
            - reddipped
              - sysstats
                - model
                  - SysStats.class
                  - SysStatsMBeanLifeCycleListener.class
                  - SysStatsMXBean.class
  - META-INF
    application.xml
    MANIFEST.MF
    weblogic-application.xml

Weblogic-application.xml contains
<?xml version="1.0" encoding="UTF-8"?>
<weblogic-application xmlns="http://xmlns.oracle.com/weblogic/weblogic-application"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/javaee_5.xsd     http://xmlns.oracle.com/weblogic/weblogic-application http://xmlns.oracle.com/weblogic/weblogic-    application/1.0/weblogic-application.xsd">
      <listener>
        <listener-    class>com.reddipped.sysstats.jmx.mbean.SysStatsMBeanLifeCycleListener</listener-class>
    </listener>

<classloader-structure>
    <module-ref>
        <module-uri>SysStats-war.war</module-uri>
    </module-ref>

    <module-ref>
        <module-uri>SysStatsMBean.jar</module-uri>
    </module-ref>

</classloader-structure>

</weblogic-application>

A: Were able to resolve this issue by adding the listener-uri. Although the class is available in the default package it must be explicitly added to the listener element.
  <listener>
    <listener-class>com.reddipped.sysstats.jmx.mbean.SysStatsMBeanLifeCycleListener</listener-class>
    <listener-uri>SysStatsMBean.jar</listener-uri>
</listener>


text:
Q: Environment Hub in a Dev Org (without ISV partnership) Does Salesforce help in enabling Environment Hub in a standard Dev org (specifically without an ISV partnership)? Is this even possible with dev orgs? Or only available with Enterprise or any paid version/ partnership with SF? Most of my search results in this ref mentions about DE which can be interpreted as a partner dev edition. I'm unable to locate an actual credible information in this regard.
The reason I'm looking for this information is that I'm trying to do a test set-up in my dev org to demonstrate managed package publishing mechanism at a high level.
[Note that I'm not talking about partner dev editions here. I had previously dabbled with Env Hub & Dev Mgmt Org at my previous employer but they were an ISV partner with premium support.]

A: Per the documentation:

Available in: Enterprise, Performance, and Unlimited Editions

As such, you can't set it up in a DE (if you could, this page would include Developer as an available edition). You do not need to be an ISV to get Environment Hub, however, you just need a paid org of any of the aforementioned editions. You can always set up your test in production, as there are no settings that are "permanent" aside from enabling the feature itself.


text:
Q: GetFileInfo resulting in First-chance exception I have a try/catch block where I use a GetFileInfo to get the size of a specific file. I'm getting an exception shown in the output window of debugger (although the program still continues its run without reacting to the exception in any way).
The error message I get:

A first chance exception of type 'System.ArgumentException' occurred in mscorlib.dll

My question here is twofold:

*

*Why does the error occur / what can I do to avoid it?

*Why does the exception show up in the output despite try/catch? Is this because an external dll throws it?

Code:
try
{
    FileInfo fileInfo = new FileInfo(filePath);
    return fileInfo.Length;
}
catch
{
}
return 0;

The above code is in a method that is called and the filePath is c:\test\test.txt and the file exists at that location.

A: *

*It smells a lot like you forgot to escape the \s in your path ;-)

*As it is always interesting to see exceptions happening in your program, this is indeed the perfectly regular behaviour of the debuggers output window.

A: In VS you can choose Debug -> Exceptions and turn off automatic breaking when a particular type of exception is thrown.


text:
Q: Date Comparion in DMN - Decision Table Using jbpm version 7
DataModel :: Profile has two fields
( onboarding of type date , currentDate of type date)
When I am writing Decision Table : it keeps throwing Error Skipped Decision Table Analysis of table 'onBoardingDateDecision' because: Gaps/Overlaps analysis cannot be performed for InputEntry with unary test
Why I am not able to perform Date Comparios in Decision Table ?
If I give simple expression like > date("2005-01-01") it works !

A: The message "Skipped Decision Table Analysis ... Gaps/Overlaps ..." refers to static analysis.
It does NOT affect any runtime behaviour and the Drools DMN Engine can evaluate your model as you would normally expect.
Gap/Overlap static analysis cannot be performed with the variable expressions in your table, hence it is skipped, and the message reports this accordingly.


text:
Q: How do I change file associations from the command line? The system in question is Solaris, using the Gnome type interface (Java Desktop Environment).  We have occasional issues with users managing to mess up their file assocations (most notably .tif).  Trying to find out what files to edit from a command line to change those file associations. (as logging in graphically as them to use the desktop utilities can be a bit of a problem remotely).

A: You need to edit /usr/share/applications/default.list. The format should be obvious, have fun ;)
p.s. there may be a command line tool I'm not aware of which does this for you ... I like sed though ;)
Update:
This particular location is often correct for Ubuntu installations and some other operating systems where gnome is the default window manager (although sometimes it is in /usr/share/gnome/applications/ .
If you're in luck, it will use the XDG_* environment variables, explained here:
http://developer.gnome.org/menu-spec/
If it is not there and you don't have those envrionment variables set, you can try using find:
find / -name default.list 2> /dev/null
Sometimes, a slightly different system is used;  On my laptop I use LXDE (which I recommend, btw), /usr/share/applications contains .desktop files, creating a new one in this directory adds items to the menu, the contents of the file dictates where, what it is called, and what it runs (and icon etc.).  This system is also in widespread use, try the find command to see if your system has .desktop files.  Copy one to a new file and modify it (easiest way).
find / -name "*.desktop" 2> /dev/null
If you still can't sort it out, I think you'll need to give more information about why your linux version, window manager version and so on.

A: Xdg-utils is used for configuring (sort of) desktop environments in terms of things like which app opens which type of file.  I once had (darn, can't find it now, I'll try to track it down and post it) a script that works like Mac OS X's open command.  It mainly used xdg-open.
Note that this is not specific to Gnome; Xdg-utils works with e.g. KDE, Xfce, fluxbox etc.
Good luck!


text:
Q: grocery list app I do not have a smart phone, nor do I have a computer in my kitchen or anything elaborate like that. I would simple like recommendations on any applications that others have found to be useful for keeping recipes and printing out grocery lists.

A: For recipes, I use e-mail. One e-mail per recipe, name in the title, can contain text, URL, and images, easy to forward to friends, can all be filed in a folder/label, and available from multiple locations and devices. Hard to beat, really!
For grocery lists, I tend to use google sticky notes and todo-list gadgets that reside on my personalized google home page. Again the availability from both home and work is quite a considerable factor.
If I were to use a local application, check out FreeMind. It is free, open source and acts as a well organized collection of little texts. It supports basic rich text like bold, italic, but does not allow to put in pictures, although URLs are possible.

A: I use Allrecipes.com to organize my recipes, find new recipes, and make grocery lists.  You can create private recipes only viewable to you, as well as public recipes that anyone can share and rate.  Of course, you can also add other people's public recipes to your "Recipe Book," rate them as you try them out, and categorize your favorite recipes however you like.  There's not much sense in fumbling around trying to bend general-purpose software to your will when there's already a domain-specific solution that was built from the ground up do exactly what you need.
One of my favorite features of Allrecipes.com  is that many of the recipes have been rated by hundreds of other users, and that they also often provide additional preparation tips.  Another handy feature is a converter which allows you to enter the number of servings you want to produce, then shows you the modified list of ingredients.
You can also use the website to build a shopping list from selected recipes, which you can then print out and take along with you to the store.

A: Notepad and a good directory/file structure.
Seriously, I have tried everything in the past, but nothing works as well!
At any one moment, I have about 6 notepad windows open (which can become annoying, so thinking of switching to a multi-tabbed variant), but I find this very good - fast to open, prints well - works the way I want it to!

A: Shopping List - Quickly make your shopping lists and print them sorted by aisle.
Simply make a shopping list by dragging items from the 'supermarket shelves' into your current weekly list - edit the quantities you need and print it.

it doesn't get much easier, except you still have to go to the supermarket yourself ;)
more of the same here: SHOPPING - FREE SOFTWARE

A: I would highly recommend Remember The Milk. It's very powerful and customizable so it can be used for Work, Home, Grocery, etc. One of the best applications I've ever used.

A: I use OneNote for all of my recipes and lists.  If you copy stuff from the web, it includes a link to the original site, which is handy for tracking down information.

A: I wrote a recipebook which is html & javascript. This works ok for me because, I am able to copy the recipebook to any folder or send it to people without changes for any OS.

My biggest problem with it is that I was a beginner at HTMLwhen I wrote it and I didn't standardize the code so getting the data to everywhere I need it to be can be cumbersome.

The recipebook contains over 500 recipes, with the javascript being used for the search.

A: I'll throw in my own method too (I like to cook a lot of things). Google docs, with a link to each recipe if there is one. It is just line delimented with categories like lunch. I then write down a recipe and usually know the ingredients by recipe alone, but sometimes I forget things and go back :(.


text:
Q: Spring cloud config Branch vs Profiles We have started using spring-cloud-config to manage the configuration of our microservices.
We have DEV, INT, QA and PROD stages. What would be the better way to manage the configuration specific to stages?

*

*Using branches or

*Using profiles

Having it as the separate branch will be cleaner as configuration will not be cluttered in one place (my view). Any recommendations?

A: I have chose using Branch because of the following advantages

*

*Easier to manage the config

*Configuration files will be smaller as there will be config for each environment

*As spencergibb suggested, you wont change the production config if it is in the different branch


text:
Q: Topology question open sets A subset of $\mathbb{R}$ is open if it is either $\mathbb{R}$, $\emptyset$, or an interval of the form $(a,\infty)$ where $a$ is any real number.
How do I show that this choice of open sets defines a topology on $\mathbb{R}$?

A: Call $\tau\subseteq P(\mathbb{R})$ the collection of sets as you said. Clearly $\mathbb{R}$ and $\emptyset\in \tau$. Now consider an arbitrary union $\bigcup_{T\in I} T$ where each $T\in I$ belongs to $\tau$. If one of the $T$'s is $\mathbb{R}$, this union is $\mathbb{R}$ and thus the union belongs to $\tau$. Of one of the $T$'s is $\emptyset$, we can simply drop them from the union. Hence we may assume that each $T\in I$ is of the form $(a_T,\infty)$.
Note that $\bigcup_{T\in I}(a_T,\infty)=(a,\infty)$ where $a:=\inf_{T\in I}a_T$. This shows that arbitrary unions of things in $\tau$ again belongs to $\tau$.
It remains to show that finite intersection of elements in $\tau$ belongs to $\tau$. I'll leave that case to you.

A: There are three axioms that must be met for a collection of subsets to form a topology on $\mathbb{R}$.
The first one is that $\emptyset, \mathbb{R}$ must be contained in the collection of subsets. Looks like you have that one covered.

The second axiom is that given an arbitrary collection of open sets, their union must also be open. Let $\{(a_i,\infty)\}_{i \in I}$ be a collection of open sets indexed by some set $I$ (note that I may be uncountable for all we know!).
There are two cases to consider:
case 1: The set $\{a_i\}_{i \in I}$ has no lower bound.
Thus, for every $n \in \mathbb{N}$, $\exists i \in I$ s.t. $n < a_i$, and therefore $\bigcup_{i \in I} (a_i,\infty) = \mathbb{R}$.
case 2: The set $\{a_i\}_{i \in I}$ has a lower bound.
In this case, let $\tilde{a} = inf_{i \in I} a_i$.
Then we have $\bigcup_{i \in I} (a_i,\infty) = (\tilde{a},\infty)$.

The third axiom is given any FINITE collection of subsets, their intersection is an open. So, let $\{(a_i,\infty)\}_{i \in I}$ be a collection of subsets where the cardinality of $I$ is finite.
Since this collection is finite, let $\tilde{a} = max\{a_i\}_{i \in I}$
Then we can see that $\bigcap_{i \in I} (a_i,\infty) = (\tilde{a},\infty)$.

Thus, the three axioms for a collection of subsets to be a topology have been met!!!


text:
Q: How to get Typescript to compile CommonJS imports? I have written a TS file, that loads in a 3rd party package, using import XXX { YYY, ABC, 123 }from 'XXX';
It will compile to CommonJS no issue, and thats OK. But I'd like to compile it to an ESModule. I changed the target and module settings to esnext in my TS config file, and it does compile, however, when I run the file, it errors out saying:
SyntaxError: Named export 'ABC' not found. The requested module 'XXX' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export, for example using:

import pkg from 'XXX';
const { ABC } = pkg;

Is there any settings I can use to tell Typescript to convert the imports to the import tye shown in the error message?

A: You may want to try nodenext instead of esnext for the module setting. This is currently experimental but it seems to address your need with CommonJS interop.
I haven't tried it myself so I cannot promise it will work.


text:
Q: How to override core functionality of drupal? I am looking for a CMS tool and looks like the top ones (with highest market share) are mostly PHP based.
So started building a POC using Drupal as it can be tweaked extensively.
I am facing few issues,

*

*Created articles using Drupal admin panel and when content is populated in the view there are many structural html tags(div,span) wrapped around the actual content. Is there a possibility if we can override and remove these changes. Tried overriding using templates but it is deeply nested and it seems we have to override many template files. Also looking to override at controller level if possible

*For each block on the UI is it possible to have a separate controller kind of thing which fetches data from database and binds to the UI.
Any guidance to sample code / good documentation will be helpful? and also is it good to use Drupal as headless or should we consider other headless CMS like Strapi/Ghost.


text:
Q: AWS CloudWatch alarm for ELB HealthyHostCount or UnhealthyHostCount I have set up two EC2 instances in an Auto Scaling Group behind an application load balancer. I want to set up an alarm in Cloud Watch to get notification when both EC2 insatnces are unhealthy .
What metric should I use in CloudWatch?
Either HealthyHostCount >= 0 or UnhealthyHostCount <=1 or UnhealthyHostCount >=0

A: Personally I would use UnhealthyHostCount >=0 to let you know that at least one of your instances is unhealthy and I'd use HealthyHostCount < minimum ASG count to make sure that your instances are not missing from the ELB. Make sure to consider any timings of events whereby you might deregister/register instances.


text:
Q: Memory(buffer pool) not populating on mysql start on Percona 5.6.28 We are testing Percona 5.6.28 at the moment, during our testing we found out even though the innodb_buffer_pool_populate is set to ON, it doesn't populate the memory(buffer pool) during mysql start.
There is the new parameter that was added in 5.6.27, innodb_numa_interleave, even with that ON the buffer pool doesn't populate on mysql.
We even tried with enabling numa at hardware level, but still same results
Memory: 512G
innodb_buffer_pool_size: 420G
We have a 420G innodb_buffer_pool_size, but following are the memory results after mysql start, it doesn't allocate the memory during mysql start
NUMA: Allocated memnodemap from d000 - d440
NUMA: Using 30 for the hash shift.
pci_bus 0000:00: on NUMA node 0
pci_bus 0000:20: on NUMA node 1
pci_bus 0000:40: on NUMA node 2
pci_bus 0000:60: on NUMA node 3
[root@db001 ~]# numactl --hardware
available: 4 nodes (0-3)
node 0 cpus: 0 1 2 3 4 5 6 7 32 33 34 35 36 37 38 39
node 0 size: 131037 MB
node 0 free: 104737 MB
node 1 cpus: 8 9 10 11 12 13 14 15 40 41 42 43 44 45 46 47
node 1 size: 131072 MB
node 1 free: 95004 MB
node 2 cpus: 16 17 18 19 20 21 22 23 48 49 50 51 52 53 54 55
node 2 size: 131072 MB
node 2 free: 115600 MB
node 3 cpus: 24 25 26 27 28 29 30 31 56 57 58 59 60 61 62 63
node 3 size: 131071 MB
node 3 free: 125262 MB
node distances:
node   0   1   2   3
  0:  10  21  21  21
  1:  21  10  21  21
  2:  21  21  10  21
  3:  21  21  21  10

Around 74G used memory, 430G free and 6G in cache
Most of the memory is free and not allocated
innodb_buffer_pool_dump_at_shutdown anf innodb_buffer_pool_load_at startup are ON
    [root@db001 ~]# grep innodb_buffer_pool /etc/my.cnf
    innodb_buffer_pool_size        = 420G
    innodb_buffer_pool_dump_at_shutdown = ON
    innodb_buffer_pool_load_at_startup  = ON
    innodb_buffer_pool_instances   = 64

Buffer pool is fully loaded at the moment because the server has been up for almost 3 days now
    root@db001 [(none)]> show global status like 'innodb_buffer_pool_%';
    | Variable_name                           | Value                                              |
    | Innodb_buffer_pool_dump_status          | not started                                      |
    | Innodb_buffer_pool_load_status          | Buffer pool(s) load completed at 160603 16:10:29 |
    | Innodb_buffer_pool_pages_data           | 27381056                                         |
    | Innodb_buffer_pool_bytes_data           | 448611221504                                     |
    | Innodb_buffer_pool_pages_dirty          | 994204                                           |
    | Innodb_buffer_pool_bytes_dirty          | 16289038336                                      |
    | Innodb_buffer_pool_pages_flushed        | 105665319                                        |
    | Innodb_buffer_pool_pages_LRU_flushed    | 0                                                |
    | Innodb_buffer_pool_pages_free           | 65522                                            |
    | Innodb_buffer_pool_pages_made_not_young | 9919036                                          |
    | Innodb_buffer_pool_pages_made_young     | 4488881                                          |
    | Innodb_buffer_pool_pages_misc           | 78478                                            |
    | Innodb_buffer_pool_pages_old            | 5453509                                          |
    | Innodb_buffer_pool_pages_total          | 27525056                                         |
    | Innodb_buffer_pool_read_ahead_rnd       | 0                                                |
    | Innodb_buffer_pool_read_ahead           | 784                                              |
    | Innodb_buffer_pool_read_ahead_evicted   | 0                                                |
    | Innodb_buffer_pool_read_requests        | 10840103331                                      |
    | Innodb_buffer_pool_reads                | 17722410                                         |
    | Innodb_buffer_pool_wait_free            | 0                                                |
    | Innodb_buffer_pool_write_requests       | 1822727016                                       |

    root@db001 [(none)]> show global status like 'uptime';
    +---------------+--------+
    | Variable_name | Value  |
    +---------------+--------+
    | Uptime        | 256907 |
    +---------------+--------+
    1 row in set (0.00 sec)

    root@db001 [(none)]> set global innodb_buffer_pool_load_now=1;
    Query OK, 0 rows affected (0.03 sec)

    root@db001 [(none)]> show global status like 'innodb_buffer_pool_%';
    +-----------------------------------------+--------------------------------------------------+
    | Variable_name                           | Value                                            |
    +-----------------------------------------+--------------------------------------------------+
    | Innodb_buffer_pool_dump_status          | not started                                       |
    | Innodb_buffer_pool_load_status          | Buffer pool(s) load completed at 160606 15:25:12 |
    | Innodb_buffer_pool_pages_data           | 27381012                                         |
    | Innodb_buffer_pool_bytes_data           | 448610500608                                     |
    | Innodb_buffer_pool_pages_dirty          | 990362                                           |
    | Innodb_buffer_pool_bytes_dirty          | 16226091008                                      |
    | Innodb_buffer_pool_pages_flushed        | 105742542                                        |
    | Innodb_buffer_pool_pages_LRU_flushed    | 0                                                |
    | Innodb_buffer_pool_pages_free           | 65522                                            |
    | Innodb_buffer_pool_pages_made_not_young | 9930674                                          |
    | Innodb_buffer_pool_pages_made_young     | 4497569                                          |
    | Innodb_buffer_pool_pages_misc           | 78522                                            |
    | Innodb_buffer_pool_pages_old            | 5453502                                          |
    | Innodb_buffer_pool_pages_total          | 27525056                                         |
    | Innodb_buffer_pool_read_ahead_rnd       | 0                                                |
    | Innodb_buffer_pool_read_ahead           | 784                                              |
    | Innodb_buffer_pool_read_ahead_evicted   | 0                                                |
    | Innodb_buffer_pool_read_requests        | 10847012782                                      |
    | Innodb_buffer_pool_reads                | 17730031                                         |
    | Innodb_buffer_pool_wait_free            | 0                                                |
    | Innodb_buffer_pool_write_requests       | 1823928823                                       |
    +-----------------------------------------+--------------------------------------------------+

My question is more on populating the buffer pool on startup, with 5.6.19 the memory used on the server stayed close to our buffer pool size(around 420G) right after mysql start and it took around 7-8 minutes to start mysql.
With 5.6.28, used memory after mysql start is close to 50G and then it starts loading with time and mysql starts in less than 30 seconds for a 420G buffer pool.

A: Amit, the problem is that this variable is set to reload a copy of the buffer pool dumped to disk during a stop/restart process.
In order to achieve this you need to set innodb_buffer_pool_dump_at_shutdown to ON prior to restart your server, please check this link for further info: https://dev.mysql.com/doc/refman/5.6/en/innodb-preload-buffer-pool.html
Regarding NUMA configuration this has nothing to do with buffer pool fill but how memory dedicated to buffer pool is balanced between CPU nodes (this is useful only for physical servers) so in modern hardware where you have more than one physical CPU you will avoid having swapping issues by balancing large portions of memory allocation (like buffer pool normally has) between nodes.
Hope this helps.

A: According to release docs innodb_buffer_pool_populate was mapped to innodb_numa_interleave starting with Percona 5.6.27-75.0, so based on what you see, it appears it is no longer preallocating the buffer pool, only setting the numa policy.
Regarding innodb_buffer_pool_dump_at_shutdown and load at startup, you might want to have a look at http://dev.mysql.com/doc/refman/5.6/en/innodb-preload-buffer-pool.html. Those parameters won't cause preallocation of the full size on restart, only any pages that were in the buffer pool before you shutdown the db will be restored.

A: NUMA is not unrelated to buffer pool preallocation. That is the reason why innodb_buffer_pool_populate was introduced in the first place.
See https://blog.jcole.us/2012/04/16/a-brief-update-on-numa-and-mysql/
That is also the reason why it took around 7-8 minutes to start mysql with the older Percona release. Now the upstream implementation replaced innodb_buffer_pool_populate and the other numa related parameters with innodb_numa_interleave, which apparently only does numactl --interleave=all and does not do the preallocation. Newer Percona releases should also have this behaviour (see https://www.percona.com/doc/percona-server/5.6/performance/innodb_numa_support.html#version-specific-information)
Regarding your test, innodb_buffer_pool_load_at_startup  = ON can take a lot of time depending on buffer pool size and io performance, so you should look for a message like
 InnoDB: Buffer pool(s) load completed at 5:29:10
in the error log before checking memory usage


text:
Q: Test MySQL Connection with default Python I'm wondering if there is any built-in way in Python to test a MySQL server connection. I know I can use PyMySQL, MySQLdb, and a few others, but if the user does not already have these dependencies installed my script will not work? How can I write a Python script to test a MySQL connection without requiring external dependencies?

A: Python distributions do not include support for MySQL, which is only available by installing a third-party module such as PyMySQL or MySQLdb. The only relational support included in Python is for the SQLite database (in the shape of the sqlite3 module).
There is, however, nothing to stop you distributing a third-party module as a part of your application, thereby including the support your project requires. PyMySQL would probably be the best choice because, being pure Python, it will run on any platform and give you best portability.


text:
Q: Get Logo to Display For Facebook Link Here's the link to the site: http://510nora.com
For some reason, I cannot get the site's logo to show up in Facebook when you go to share the link. Instead, it shows three of the four page thumbnails.
I've inserted meta data. I've gotten plugin's to override settings in the theme. I've done everything that I know of and nothing is working!!!
Instead of showing the site's logo (which is in a meta tag, a featured image, AND attached to the page), it's showing three of the four thumbnails listed on the page.

A: The Facebook debugger shows you as having multiple og:urls set.
https://developers.facebook.com/tools/debug/og/object?q=http%3A%2F%2F510nora.com
Resolve this and Facebook should be able to correctly fetch your OG tags, including your og:image one.

A: <!-- for Facebook -->
<meta property="og:title" content="" />
<meta property="og:type" content="article" />
<meta property="og:image" content="" />
<meta property="og:url" content="" />
<meta property="og:description" content="" />

Just edit this with URL of your logo: <meta property="og:image" content="" />
and add to head section


text:
Q: Como chamar uma "Stored Procedure" oracle c# Tenho a seguinte procedure no meu banco:

Estou tentando chamar minha store procedure no .net desta forma:
        public int CountEvent(int resourceId, int eventCounterDefinitionId, DateTime startDate, DateTime stopDate)
    {
        int ret = 0;
        using (OracleConnection conn = new OracleConnection(ConfigurationManager.ConnectionStrings[MyConnectionStrings.Default].ConnectionString))
        {
            try
            {
                conn.Open();
                Console.WriteLine("ServerVersion: {0} \nDataSource: {1} \nHostName: {2}",
                    conn.ServerVersion, conn.DataSource, conn.HostName);

                OracleCommand com = new OracleCommand("PRODUCTION.COUNT_EVENT", conn);
                OracleParameter paramiter1 = new OracleParameter();
                com.Parameters.Add("@P_RESOURCEID", resourceId);
                com.Parameters.Add("@P_EVENTCOUNTERDEFINITIONID",eventCounterDefinitionId);
                com.Parameters.Add("@P_SHIFT_START", startDate);
                com.Parameters.Add("@P_SHIFT_END", stopDate);
                com.CommandType = System.Data.CommandType.StoredProcedure;
                com.ExecuteReader();

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        return ret;
    }

No entanto, ao executar meu código, dá a mensagem de erro:

Número incorreto de tipos de argumentos na chamada para
  'COUNT_EVENT'

Alguém poderia me ajudar no porquê os parâmetros estão errados?

A: A sua procedure possui uma variavel de saida (out) , que deve ser declarada na sua chamada no c# também.
Consumindo uma variável de saída
ora_cmd.Parameters.Add("Lc_Exito", OracleDbType.Int32).Direction = ParameterDirection.Output;

ora_cmd.ExecuteNonQuery();

var returno = ora_cmd.Parameters["Lc_Exito"].value

Assim o seu código deve funcionar.
Cursor
Notei também que o out da sua consulta é um cursor do oracle, um tipo mais complicado de trabalhar. O Codigo para consumi-lo seria algo assim:
cmd.Parameters.Add("REC_CUR",OracleType.Cursor).Direction=ParameterDirection.Output;
con.Open();
cmd.ExecuteNonQuery();

E você pegará ele assim:
cmd.Parameters["REC_CUR"].value


text:
Q: Android action bar autosrollable title I'd like to create app with setTitle function at ActionBar
But, some strings are bigger than ActionBar width, and i want use autoscrollable function for my title.
I try to create style for my ActionBar:
 <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="android:actionBarStyle">@style/MyActionBar</item>

        <!-- Support library compatibility -->
        <item name="actionBarStyle">@style/MyActionBar</item>
    </style>

    <!-- ActionBar styles -->
    <style name="MyActionBar" parent="Widget.AppCompat.ActionBar.Solid">
        <item name="android:background">@drawable/ab_background</item>

        <item name="android:titleTextStyle">@style/ActionBarTitleStyle</item>
        <!-- Support library compatibility -->
        <item name="background">@drawable/ab_background</item>
        <item name="titleTextStyle">@style/ActionBarTitleStyle</item>
    </style>

    <style name="ActionBarTitleStyle" parent="TextAppearance.AppCompat.Widget.ActionBar.Title">
        <item name="android:ellipsize">marquee</item>
        <item name="android:marqueeRepeatLimit">1</item>
        <item name="android:singleLine">true</item>
        <item name="android:focusable">true</item>
        <item name="android:focusableInTouchMode">true</item>
        <item name="android:textColor">#FF64A3</item>
    </style>

But it doesn't work.
Please tell me what i do wrong?