text:
Q: Difference in SHA Hash between git hash-object & git hash-object -t I want to calculate git SHA hash without using the git hash object function, that is I want to use the shasum function to calculate it.
I know that for the following case
    body="tree 491e9405120eaaa57cce3938fd38508d85a5e08b
parent 8550f0f1a7e32fb1bb0933b0294c116a8dbe6dce
author user <me@example.com> 1390718030 +0000
committer user <me@example.com> 1390718030 +0000
This is a test"

echo $body | git hash-object -w --stdin #755481b921f13bcfd731d74287a0c5847519ee81

l=`expr ${#body} + 1`
echo -e 'blob $l\0$body' | shasum #755481b921f13bcfd731d74287a0c5847519ee81

hashes are the same. But if I use -t commit option in hash-object I get a different Hash. How can I calculate the commit hash using shasum?
git hash-object -t commit --stdin <<< "$body" #b4c45adbbe35d3d3c73de48d039a8e3038f5ec54

A: You changed the type of the object you wrote the hash with.
From git hash-object
-t <type>

    Specify the type (default: "blob").

You went from the default blob to commit.
And the object actually written start with the object type, which is part of what the sha1 has to compute.
See:

*

*"Why does git hash-object return a different hash than openssl sha1?"

*"Assigning Git SHA1's without Git"

Git calculates the SHA1 for a file (or, in Git terms, a "blob"):

sha1("blob " + filesize + "\0" + data)

That changes the content of what is taken into account by the sha1.
With -t commit, you modify that prefix (it is no longer 'blob'), and since the content is different, the sha1 is also different.
You can do a:
python -c "import zlib,sys;print repr(zlib.decompress(sys.stdin.read()))" < .git/objects/02/b365d4af3ef6f74b0b1f18c41507c82b3ee571:

The first word will be the type of the content
For further reference check How Git Works


text:
Q: How to sort User and Role in core Identity I'm trying to display a list of Roles with users in my view.
This is my current output:
Role | Email
A | aaa@example.com
B | bbb@example.com
B | abc@example.com
C | baa@example.com
But I want it to be like this:
Role | Email
A | aaa@example.com
B | abc@example.com <--order by Role, then Email
B | bbb@example.com
C | baa@example.com
Any idea how to order the child in collection?
SettingController.cs
    private readonly UserManager<ApplicationUser> _userManager;
    private readonly RoleManager<ApplicationRole> _roleManager;

    public SettingController(UserManager<ApplicationUser> userManager, RoleManager<ApplicationRole> roleManager)
    {
        _userManager = userManager;
        _roleManager = roleManager;
    }

    public IActionResult Index()
    {
        var usersWithRole = _roleManager.Roles.Include(r => r.UserRoles).ThenInclude(u => u.User).OrderBy(r => r.Name).ToList();

        return View(usersWithRole);
    }

Index.cshtml
@{
    ViewData["Title"] = "Index";
    ViewData["Name"] = "Index";
    int count = 1;
}

            No
            Role
            Email

        @foreach (var role in Model)
        {
            var result = role.UserRoles;
            @foreach(var userRole in result)
            {

                    @count
                    @role.Name
                    @userRole.User

                count++;
            }
        }

ApplicationRole.cs
public class ApplicationUser : IdentityUser
{
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

ApplicationUserRole.cs
public class ApplicationUserRole : IdentityUserRole<string>
{
    public virtual ApplicationUser User { get; set; }
    public virtual ApplicationRole Role { get; set; }
}

ApplicationUser.cs
public class ApplicationUser : IdentityUser
{
    public ICollection<ApplicationUserRole> UserRoles { get; set; }
}

ApplicationDbContext.cs
protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.Entity<ApplicationUserRole>(userRole =>
        {
            userRole.HasKey(ur => new { ur.UserId, ur.RoleId });

            userRole.HasOne(ur => ur.Role)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.RoleId)
                .IsRequired();

            userRole.HasOne(ur => ur.User)
                .WithMany(r => r.UserRoles)
                .HasForeignKey(ur => ur.UserId)
                .IsRequired();
        });
    }

A: Use ThenBy() method for the second sort column like below to have order by Name, Email asc
 var usersWithRole = _roleManager.Roles.Include(r => r.UserRoles)
                      .ThenInclude(u => u.User)
                      .OrderBy(r => r.Name)
                      .ThenBy(l => l.Email)
                      .ToList();

A: I manage to find a way to get the result that I wanted.
I create entities for the tables and access it via linq instead of using Identity's UserManager and RoleManager.
Then, I bind the result to ViewModel and display it in my view.
Controller
public IActionResult Index()
    {

        //var usersWithRole = _roleManager.Roles.Include(r => r.UserRoles).ThenInclude(u => u.User).OrderBy(r => r.Id).ToList();

        var roleAndUsers = (from r in _context.Role
                     join ur in _context.UserRole
                     on r.Id equals ur.RoleId
                     join u in _context.User
                     on ur.UserId equals u.Id
                     orderby r.Name, u.Email
                     select new UserAndRoleViewModel { Name = r.Name, Email = u.Email, Id = u.Id }).ToList();

        return View(roleAndUsers);
    }

ViewModel
public class UserAndRoleViewModel
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Id { get; set; }
}

View
@{
    ViewData["Title"] = "Index";
    int count=1;
}

            No
            Role
            Email

        @foreach (var role in Model)
        {

                @count
                @role.Name
                @role.Email

            count++;
        }

ApplicationDbContext
    public DbSet<ApplicationRole> Role { get; set; }
    public DbSet<ApplicationUserRole> UserRole { get; set; }
    public DbSet<ApplicationUser> User { get; set; }

redpajama_set_name: RedPajamaStackExchange


text:
Q: REST API for IoT Edge module twins? What is the corresponding REST API to read and update the twins of Azure IoT Edge modules? For IoT devices this API works. So far I only can see the twins in the portal and via the SDK.

A: For reading Module Twin, the format of REST API for is /twins/${deviceId}/modules/${moduleId}?api-version=${IoTHubApiVersion}. You could refer to the code in Azure IoT Toolkit extension for reference to learn how it reads Module Twin.


text:
Q: Placing MessagesEventArgs in class In the code I wrote for a telegram bot I wanted to place this code:
Telegram.Bot.Args.MessageEventArgs a

in the
Task.Run(() => { //code });

Because in the code I use a.Messages.From.Username and sometimes more than one user is using the bot and because of that I need to separate a.Messages.From.Username's, but I couldn't find any way.
This is my code:
 void bot_OnMessage1(object sender, Telegram.Bot.Args.MessageEventArgs a)
 {
     Task.Run(() =>
     {
         string watermarkText = a.Message.Text;
         string fileName = "C:\\temp\\01.png";

         using (Bitmap bmp = new Bitmap(fileName))
         {
             using (Graphics grp = Graphics.FromImage(bmp))
             {
                 bmp.Save("c:\\temp\\" + a.Message.From.Username + ".png", ImageFormat.Png);
                 using (FileStream fs = new FileStream("c:\\temp\\" + a.Message.From.Username + ".png", FileMode.Open))
                 {
                     fs.CanTimeout.ToString();
                     FileToSend fileToSend = new FileToSend("c:\\temp\\" + a.Message.From.Username + ".png", fs);
                     var rep = bot.SendPhotoAsync(a.Message.From.Id, fileToSend, "این عکس را پست کنید").Result;
                 }
             }
         }
     });
 }


text:
Q: Load excel files with different columns from a directory into database using SSIS package I have 40 excel sheets in a single folder. I want to load them all in different tables sql server database through SSIS package. The difficulty I am having is because of different number and name of columns in each excel sheet.
Can this task be achievable through a single package?

A: Another option, if you want to do it in one data flow, you can write custom C# source component with multiple outputs. In the script task you'll figure out the file type and send the data to the proper output.
NPOI library(https://npoi.codeplex.com/) is a good way to read excel files in C#.
But if you have fixed file formats I would prefer to create N Data Flows inside Foreach loop container. Use regular Excel source components and just ignore errors in each data flow. This will let you get a file and try to load it in each data flow one by one. On error you will not fail the package but just go to the next data flow until you find the proper file format.

A: It can only be done, by adding multiple sources or using a script component, white a flag on what sheet it is. Then you can use a conditional split and enter multiple destinations.


text:
Q: Add seleniumlibrary prefix to keyword call issue I was facing keyword issue with robot framework and selenium in eclipse. I downgrade robot to 3.2.2 from 4.0 as it is not supporting in RED editor. Now I am facing new issue. I need to add seleniumlibrary prefix manually to all the keywords.
Is there any way to do it quickly as I have around 55 scripts.

A: Your issue, as can be seen in the screenshot, is that you have both SeleniumLibrary as well as Selenium2Library providing the same keyword for you. The best solution to this would be to remove the Selenium2Library altogether, if possible. Unless you have some extremely old scripts done with the old SeleniumLibrary it doesn't provide anything for you.
If both libraries are needed, the BuiltIn library provides keyword called Set Library Search Order which will resolve the conflicts by using the primary library first and then if the keyword is not found, defaulting to the secondary one. See the keyword documentation here.
So it would work like this
TC ID : N
    Set Library Search Order    SeleniumLibrary    Selenium2Library
    Open Browser    ${URL}    ${BROWSER}
    Maximize Browser Window


text:
Q: How to make lowest part of this curve follow straight line instead sine wave? https://www.desmos.com/calculator/xgw33pnx1p
When moving the slider of variable "m", we can see that the red curve is being bend, and you can clearly see that the lowest part of that red curve follow sine wave (green line)
Instead follow sine wave, how to make that lowest part follow blue line (straight line) instead sine wave while changing "m" variable and still keep original shape? If you know how, please explain as simple as possible how did it work and provide the polar function :(.
I know that this question may asked somewhere, but with limit English, I don't know how to search this type of problem and the name of the curve, and the question may unclear to some...

A: The green line is NOT a part of the red curve. It is the drawing of a different function.
You can see on the left side of the figure the equations of three different functions, which are respectively drawn in red, green and blue.
The red curve is the is the drawing in polar coordinates. When you change the value of $m$, of course the chape changes, but not as you imagine. You wrote "The red curve is being bend". This because you make $m$ vary only on a small range. Try on a larger range and see what append. For example $m=1.5$ then $m=5$ on the figures below.

The green curve is not "the lowest part of the red curve" as you wrote. It represents a pure sinusoidal function. The change of $m$ translate it, nothing more.
The blue curve represents a linear function. The change of $m$ translate it, that's all.
Drawing the three functions is only a feature of the  software that you use. The question "How to make lowest part of this curve follow straight line instead sine wave?" is a non-sens.
In ADDITION :
The Cartesian coordinates of the "tipped point" are $\left(x=0\:,\:y=\cos(m\frac{\pi}{2})\right)$. If you want that this point follows a moving straight line (drawn in blue), just change the equation of the straight line to :
$$y=\left(-x+\cos(m\frac{\pi}{2}) \right)d$$

Another variant. Only the polar function is changed :


text:
Q: Remove .php in files (redirect user to custom 404 page if such file does not exist) in .htaccess Please i need a quick fix,
I have completed a site and I use .htaccess to rewrite the urls to remove .php with my intention for only known files i.e. if I have about.php then I can have /about it worked fine with the following .htaccess lines
Options -MultiViews
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ $1.php [L]

Now I created another line to handle custom 404 error
ErrorDocument 404 /404.html

Now here is the problem, I get 500 Internal Server Error upon navigating to unknown files instead of redirecting to 404....
Apache rewriting is somehow wield so i just dont have the time now, any help please
Thanks in anticipation

A: Well you should be able to go to the page without the .php, so if you have like a header file or config file, just put this code up top after session stuff. You can remove the rewrite rule.
if (substr($_SERVER['REQUEST_URI'], -4) === '.php') {
    require '404.php';
}


text:
Q: Mac 10.6 cursor control in Python?
Possible Duplicate:
Controlling the mouse from Python in OS X

I'm trying to control the system cursor position on Mac OS X 10.6 with Python. Can I do this directly, and if so how? Or would I have to use something like PyObjC?
Thanks for the help.


text:
Q: Kentico Image Resizing per device profile configuration I suspect that this is more a configuration problem than anything else:
The site has been configured using the default device profiles (phone, tablet, desktop) and in settings -> content ->content management -> resize images according to device profile is enabled.
However the images aren't resizing. The sample page I am using contains 2 images served up via the media library so resolve to /getmedia/etc. and I'm using physical devices to double check with. From what I understand the settings listed above should have been all I needed to set?

A: I'd suggest not using device profiles if you're using a responsive design.  Using device profiles and responsive is not really recommended.  I'd highly recommend checking out responsive images instead of device profiles.


text:
Q: null cannot be cast to non-null type kotlin.collections.List - kotlin I'm trying to add search Filterable in RecyclerView. but the app is getting crashed with following error:

kotlin.TypeCastException: null cannot be cast to non-null type
  kotlin.collections.List
                  at com.kabelash.movies.ui.PostListAdapter$searchFilter$1.publishResults(PostListAdapter.kt:87)
                  at android.widget.Filter$ResultsHandler.handleMessage(Filter.java:284)
                  at android.os.Handler.dispatchMessage(Handler.java:107)
                  at android.os.Looper.loop(Looper.java:214)

Adapter:
class PostListAdapter: RecyclerView.Adapter<PostListAdapter.ViewHolder>(), Filterable {
    private lateinit var postListFiltered:List<Data>
    private lateinit var postListFull:List<Data>

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val binding: ListItemBinding = DataBindingUtil.inflate(LayoutInflater.from(parent.context), R.layout.list_item, parent, false)
        return ViewHolder(binding)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        holder.bind(postListFiltered[position])
    }

    override fun getItemCount(): Int {
        return if(::postListFiltered.isInitialized) postListFiltered.size else 0
    }

    fun updatePostList(postList:List<Data>){
        this.postListFiltered = postList
        notifyDataSetChanged()
    }

    class ViewHolder(private val binding: ListItemBinding): RecyclerView.ViewHolder(binding.root){
        private val viewModel = MoviesViewModel()

        fun bind(post:Data){
            viewModel.bind(post)
            binding.viewModel = viewModel
        }

    }

    override fun getFilter(): Filter? {
        return searchFilter
    }

    private val searchFilter: Filter = object : Filter() {
        override fun performFiltering(constraint: CharSequence?): FilterResults? {
            val filteredList: MutableList<Data> = ArrayList()
            if (constraint == null || constraint.isEmpty()) {
                filteredList.addAll(postListFull)
            } else {
                val filterPattern = constraint.toString().toLowerCase().trim()
                for (item in postListFull) {
                    if (item.title.toLowerCase().contains(filterPattern) || item.genre.toLowerCase().contains(filterPattern)) {
                        filteredList.add(item)
                    }
                }

            }
            val results = FilterResults()
            results.values = filteredList
            return results
        }

        override fun publishResults(constraint: CharSequence?,results: FilterResults) {
            postListFiltered = (results.values as List<Data>)
            notifyDataSetChanged()
        }
    }
}

If you need any other class file please do let me know. Can someone please help me to solve it?

A: It's this line:
results.values as List<Data>
results.values is null, and you're telling it to be a non-null list, which it can't do.

A: You will have to perform a null check before performing the cast, modify your pulishResults method as following.
   override fun publishResults(constraint: CharSequence?,results: FilterResults) {
                postListFiltered = if(results == null || results.values == null)
                                       ArrayList<Data>()
                                   else
                                        results.values
                notifyDataSetChanged()
            }

A: As the other two answers correctly point out, your results.values is null.  But the code clearly shows that the FilterResults returned from performFiltering always has a non-null values field.  How can this have happened?
A brief look at the Filter source code gives a possible answer:
// Filter.RequestHandler.handleMessage(Message msg)

try {
    args.results = performFiltering(args.constraint);
} catch (Exception e) {
    args.results = new FilterResults();
    Log.w(LOG_TAG, "An exception occured during performFiltering()!", e);
}

In plain English, if performFiltering() throws an exception, the filter catches the exception and uses an empty FilterResults in place of what would otherwise be returned.  The stack trace for this exception can be found in logcat.
Looking at your performFiltering function, the only exception that stands out is UninitializedPropertyAccessException.  If this turns out to be the exception thrown, you can fix it by either checking whether the fullPostList property is initialized or explicitly initializing it to the empty list.


text:
Q: Highchart 3D drag also move the plot image I need a way to also rotate the plot image in 3D column chart at the bottom to make it align with the rotation of the whole chart when I make a drag on the chart.
Now the plot image keep static when the chart is dragging.
Here is the example:
options3d: {
    enabled: true,
    alpha: 20,
    beta: 30,
    depth: 200,
    viewDistance: 5,
    frame: {
      bottom: {
        size: 1,
        color: 'url(#frameBg)'
      }
    }
  },

http://jsfiddle.net/akoLv4z9/
Thanks in advance.


text:
Q: Tempo de sessão do utilizador Boas comunidade.
Quando o utilizador faz login eu adiciono na base de dados o dia e hora que este utilizador logou.
O ficheiro init.php, que contém o inicio de sessão e o qual eu uso em todas as minhas páginas eu coloquei o seguinte código:
if(($_SESSION['last_login'])>2){
//echo "ok";
}else{

header("location: logout.php?timeout=1");
}

Agora, eu queria que o utilizador depois de 30minutos fosse redirecionado para a página de logout. Estarei a fazer de forma correta? Formato da data 2016-01-29 14:19:45

A: Não vejo a necessidade de gravar em banco de dados, use somente variáveis de sessão. Aqui vai um exemplo simples fazendo isso em 30 segundos:
login.php
<?php

session_start();
if(!isset($_SESSION['start_login'])) { // se não tiver pego tempo que logou
    $_SESSION['start_login'] = time(); //pega tempo que logou
    // adiciona 30 segundos ao tempo e grava em outra variável de sessão
    $_SESSION['logout_time'] = $_SESSION['start_login'] + 30;
}

// se o tempo atual for maior que o tempo de logout
if(time() >= $_SESSION['logout_time']) {
    header("location:logout.php"); //vai para logout
    session_destroy();
} else {
    $red = $_SESSION['logout_time'] - time(); // tempo que falta
    echo "Início de sessão: ".$_SESSION['start_login']."
";
    echo "Redirecionando em ".$red." segundos.
";
}

?>

logout.php
<?php

echo "logout\n
";
session_start();
session_destroy();

?>
Voltar

Para colocar 30 minutos coloque 30 * 60.

A: O PHP já possui um parametro session.gc_maxlifetime, que pode ser alterado.
Edite o PHP.ini:
session.gc_maxlifetime = 1800

Isso irá fazer expirar a sessão após 1800 segundos (30 minutos).
Verifique se existe a sessão:
Dessa forma apenas verifique se existe a sessão:
<?php

if(isset($_SESSION['sua_sessao'])){
// Se houver sessão - OK
}else{
header('location: logout.php');
// Se não houver - Redireciona para logout.php
}

?>

A sessão irá expirar em 30 minutos e irá redirecionar para logout.php.
Problemas e correções:
Suponha que um usuário NUNCA fez o login, se ele acessar a página será redirecionado para logout.php, porque também não possui sessão, o que no meu entender seria errado.
Por isso crie um cookie quando fizer o login e verifique da seguinte forma:
<?php

//...
}else{

if(isset($_COOKIE['login'])){
// Se existe o cookie, que já indica que o usuário já se conectou alguma vez
    header('location: logout.php');
    // Redireciona para logout.
}else{
// Se o visitante caiu de paraquedas na página e nunca fez o login
    header('location: login.php');
    // Redireciona para o login.
}

?>


text:
Q: Nested include sequelize I have three relations with association like this:
User.belongsToMany(Course, { as: 'courses', through: CourseUser, foreignKey: 'userId' });
Course.belongsToMany(User, { as: 'users', through: CourseUser, foreignKey: 'courseId' });
CourseRole.belongsToMany(User, { as: 'users', through: CourseUser, foreignKey: 'roleId' });
User.belongsToMany(CourseRole, { as: 'course_roles', through: CourseUser, foreignKey: 'userId' });

I'm trying to do a nested include to find all user in a course and their roles.
const course = await Course.findOne({
    where: { id: courseId },
    include: [{ model: CourseUser, as: 'organization_users' }, { model: CourseRole, as: 'course_roles' }]
  });

But it does not work, I did many research but perhaps dont have a way to do this type of include in sequelize?

A: Try use required: true when loading course while finding roles which include users include courses.
const roles = await CourseRole.findAll({
    include:  [
                {
                    model: User,
                    as: 'users',
                    include:[{
                        model: Course,
                        as: 'courses',
                        where: {id: courseId},
                        required: true
                    }]
                }
            ],
  });


text:
Q: why the difference between numpy matrix and numpy array when selecting element I have a calculated matrix
from numpy import matrix
vec=matrix([[  4.79263398e-01+0.j        ,  -2.94883960e-14+0.34362808j,
     5.91036823e-01+0.j        ,  -2.06730654e-14+0.41959935j,
      -3.20298698e-01+0.08635809j,  -5.97136351e-02+0.22325523j],
    [  9.45394208e-14+0.34385164j,   4.78941900e-01+0.j        ,
       1.07732017e-13+0.41891016j,   5.91969770e-01+0.j        ,
      -6.06877417e-02-0.2250884j ,   3.17803028e-01+0.08500215j],
    [  4.63795513e-01-0.00827114j,  -1.15263719e-02+0.33287485j,
      -2.78282097e-01-0.20137267j,  -2.81970922e-01-0.1980647j ,
       9.26109539e-02-0.38428445j,   5.12483437e-01+0.j        ],
    [ -1.15282610e-02+0.33275927j,   4.63961516e-01-0.00826978j,
      -2.84077490e-01-0.19723838j,  -2.79429184e-01-0.19984041j,
      -4.42104809e-01+0.25708681j,  -2.71973825e-01+0.28735795j],
    [  4.63795513e-01+0.00827114j,   1.15263719e-02+0.33287485j,
      -2.78282097e-01+0.20137267j,   2.81970922e-01-0.1980647j ,
       2.73235786e-01+0.28564581j,  -4.44053596e-01-0.25584307j],
    [  1.15282610e-02+0.33275927j,   4.63961516e-01+0.00826978j,
       2.84077490e-01-0.19723838j,  -2.79429184e-01+0.19984041j,
       5.11419878e-01+0.j        ,  -9.22028113e-02-0.38476356j]])

I want to get 2nd row, 3rd column element
  vec[1][2]
  IndexError: index 1 is out of bounds for axis 0 with size 1

and slicing works well
  vec[1,2]
  (1.07732017e-13+0.41891015999999998j)

My first question why first way does not work in this case? it worked before when I used it.
Second question is: the result of slicing is an array, how to make it an complex value without bracket? My experience was using
 vec[1,2][0]

but again it is not working here.
I tried to do everything on numpy array at begining, those methods that do not work on numpy matrix work on numpy array. Why there are such differences?

A: The key difference is that a matrix is always 2d, always. (This is supposed to be familiar to MATLAB users.)
In [85]: mat = np.matrix('1,2;3,4')
In [86]: mat
Out[86]:
matrix([[1, 2],
        [3, 4]])
In [87]: mat.shape
Out[87]: (2, 2)
In [88]: mat[1]
Out[88]: matrix([[3, 4]])
In [89]: _.shape
Out[89]: (1, 2)

Selecting a row of mat returns a matrix - a 1 row one.  It should be clear that it cannot be indexed again with [1].
Indexing with the tuple returns a scalar:
In [90]: mat[1,1]
Out[90]: 4
In [91]: type(_)
Out[91]: numpy.int32

As a general rule operations on a np.matrix returns a matrix or a scalar, not a np.ndarray.
The other key point is that mat[1][1] is not one numpy operation.  It is two, a mat[1] followed by another [1].  Imagine yourself to be a Python interpreter without any special knowledge of numpy.  How would you evaluate that expression?
Now for the complex question:
In [92]: mat = np.matrix('1+3j, 2;-2, 2+1j')
In [93]: mat
Out[93]:
matrix([[ 1.+3.j,  2.+0.j],
        [-2.+0.j,  2.+1.j]])
In [94]: mat[1,1]
Out[94]: (2+1j)
In [95]: type(_)
Out[95]: numpy.complex128

As expected the tuple index has returned a scalar numpy element.  () is just part of numpys way of displaying a complex number.
We can use item to extra python equivalent, but the display still uses ()
In [96]: __.item()
Out[96]: (2+1j)
In [97]: type(_)
Out[97]: complex

In [98]: 1+3j
Out[98]: (1+3j)

mat has A property that gives the array equivalent.  But notice the shapes.
In [99]: mat.A        # a 2d array
Out[99]:
array([[ 1.+3.j,  2.+0.j],
       [-2.+0.j,  2.+1.j]])
In [100]: mat.A1         # a 1d array
Out[100]: array([ 1.+3.j,  2.+0.j, -2.+0.j,  2.+1.j])
In [101]: mat[1].A
Out[101]: array([[-2.+0.j,  2.+1.j]])
In [102]: mat[1].A1
Out[102]: array([-2.+0.j,  2.+1.j])

Sometimes this behavior of matrix is handy.  For example np.sum acts like the array keepdims=True:
In [108]: np.sum(mat,1)
Out[108]:
matrix([[ 3.+3.j],
        [ 0.+1.j]])

In [110]: np.sum(mat.A,1, keepdims=True)
Out[110]:
array([[ 3.+3.j],
       [ 0.+1.j]])


text:
Q: Change  text via <% JSP %>

    <%

     out.println(mainBlog.getText()); %>

How can i connect the MainText Label with the mainBlog.getText() element?
Thanks.

A: <%=mainBlog.getText()%>

This would work. But it's not a good practice to mix Java code in JSP.
Ideally you should set the mainBlog bean in request scope in java controller as an attribute
request.setAttribute("mainBlog",mainBlog);

and then use it in JSP using expression language
${mainBlog.text}


text:
Q: Connecting to phpmyadmin xampp mysql server over ssl I was setting up a local server on my mac using xampp, however i ran into a problem when i needed to set up ssl for my site. I set up the php side to enable ssl that works fine, I can visit 'https://localhost/' fine it loads up the xampp welcome page. Now when it comes to mysql and setting it up to use ssl i cant get it to use ssl. When i go into phpmyadmin and check the variables it says that ssl isn't on and that there is no cipher specified.
I tried going into the config.inc.php and adding the following lines:
    $cfg['Servers'][$i]['ssl'] = true;
    $cfg['ForceSSL'] = TRUE;

I then restarted apache and mysql servers through xampp and that changed nothing. I then generated my own certificates put them in a folder and added the following to the same config.inc.php file:
    $cfg['Servers'][$i]['ca'] = '/Applications/XAMPP/xamppfiles/etc/ssl/ca-cert.pem';
    $cfg['Servers'][$i]['cert'] = '/Applications/XAMPP/xamppfiles/etc/ssl/client-cert.pem';
    $cfg['Servers'][$i]['key'] = '/Applications/XAMPP/xamppfiles/etc/ssl/client-key.pem';

That also did nothing to change mysql's ssl settings. I was just looking to connect to mysql in php using ssl. My php code looks like this below:
   error_reporting(E_ALL);
   ini_set("display_errors", "1");
   $link = mysqli_init();
   mysqli_ssl_set($link,'/Applications/XAMPP/xamppfiles/etc/ssl/server-key.pem','/Applications/XAMPP/xamppfiles/etc/ssl/server-cert.pem','/Applications/XAMPP/xamppfiles/etc/ssl/ca-cert.pem',null, null);
   mysqli_real_connect($link,$dbhost, $dbuser, $dbpass, $dbname);

I can't connect with the code above it gives me a ssl error. Is there anyone that can help me set this up so that i can use ssl please?

A: The MySQL in XAMPP is actually a MardiaDB binary version. That version does not support SSL (TSL).
Try this: How can I change MariaDB to MySQL in XAMPP?


text:
Q: How to embed ole bin file to docx file We have extracted bin file from some other application. The bin file is ole. Now my requirement is - how to extract file from the bin file? Is there any way to extract file from bin file?
Language: C#
Thanks.
Prakash


text:
Q: Logic behind continuity definition. I have a question regarding the definition of continuous functions : from wikipedia and my book : $f$ is said to be continuous at the point $c$ if the following holds:

For any number $\varepsilon\gt0$, however small, there exists some number $\delta\gt0$ such that for all $x$ in the domain of $f$ with $c − \delta\lt x \lt c + \delta$, the value of $f(x)$ satisfies
     $$  f(c) - \varepsilon < f(x) < f(c) + \varepsilon.$$

Which can be summarize by $A$ if $B$, which is the same as $B \Rightarrow A$.
But then my book and wikipedia are assuming that if $f$ is continuous then we have  $f(c) - \varepsilon < f(x) < f(c) + \varepsilon $:

Fix some $\varepsilon\gt0$. Since f is continuous, there is a $δ > 0$ such that $|f(x) − f(c)| < \varepsilon$ whenever $|x − c| < δ$. This means that
  $$    f(x) − \varepsilon < f(c) < f(x) + \varepsilon.$$

Which is the same than assuming $A\Rightarrow B$ but our definition of continuity only states that $B\Rightarrow A$. Is there something that I don't get ? Or is my memory of mathematical logic wrong ?
Thanks in advance.

A: The definition of a predicate can be expressed as a bi-conditional :

$f$ is continuous at point $c$ iff for all $\epsilon > 0$, there exists some $\delta > 0$ such that for all $x$ in the domain of $f$, if $c − \delta\lt x \lt c + \delta$, then $f(c) - \varepsilon < f(x) < f(c) + \varepsilon$.

Thus, in order to prove the continuity of $f$ at $c$, we have to choose a positive $\epsilon$ whatever (for all $\epsilon > 0$) and we have to find a suitable positive $\delta$ (there exists $\delta > 0$) such that, for any $x$, the condition "if ..., then ..." is satisfied.
In this way, we "use" the right-to-left part of the bi-conditional :

if for all $\epsilon > 0$, ..., then $f$ is continuous at point $c$.

I think that part of the doubt is due to the "correct formalization" of the defining clause.
You can see here a discussion about the conditional statements and the formalization of "if and only if".
The usual way to state the above definition is to omit the iff and states it as :

$f$ is continuous at point $c$ if ...

This means that we are saying : "$A$, if $B$", that is we are using the part : "if $B$, then $A$" of the bi-conditional, i.e. :

if for all $\epsilon > 0$ ..., then $f$ is continuous at point $c$.

Why so ? because "usually" we have to apply the defining condition in order to prove the continuity.


text:
Q: My application doesn't work with OnTouchListener I do not know why my program stops when I run it. The application does not display anything, I only get the error: "The application closed", but nothing was displayed on the screen, neither the background nor the buttons in the application appeared.
I noticed that this happens when I attach a picture to the button
public class Telecomanda extends AppCompatActivity {
public Button btnFata, btnFataDreapta, btnFataStanga, btnSpate, btnFar, btnGaraj, btnObstacol;

public BluetoothAdapter btAdapter;
public BluetoothDevice device;
public BluetoothSocket socket;
public OutputStream outputStream;

String ip = "192.168.1.102";

String comand;

public final UUID PORT_UUID = UUID.fromString( "00001101-0000-1000-8000-00805f9b34fb" ); //SPP UUID
public final String DEVICE_ADDRESS = "00:18:E4:35:08:B6"; // HC-05 BT ADDRESS

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate( savedInstanceState );
    setContentView( R.layout.activity_telecomanda );
    this.setRequestedOrientation( ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE );
    outputStream = new ByteArrayOutputStream( 1024 );

    //  declarare butoane
    btnFata = (Button) findViewById( R.id.btnFata );
    btnSpate = (Button) findViewById( R.id.btnSpate );
    btnFataDreapta = (Button) findViewById( R.id.btnFataDreapta );
    btnFataStanga = (Button) findViewById( R.id.btnFataStanga );
    btnGaraj = (Button) findViewById( R.id.btnGaraj );

    btAdapter = BluetoothAdapter.getDefaultAdapter();
    device = btAdapter.getRemoteDevice( DEVICE_ADDRESS );

    if (btAdapter == null) {
        Toast.makeText( getApplicationContext(), "Bluetooth not available", Toast.LENGTH_LONG ).show();
    } else {
        if (!btAdapter.isEnabled()) {
            Intent enableIntent = new Intent( BluetoothAdapter.ACTION_REQUEST_ENABLE );
            startActivityForResult( enableIntent, 3 );
        } else {
            ConnectThread connectThread = new ConnectThread( device );
            connectThread.start();
        }
    }

    btnFata.setOnTouchListener( new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                comand = "1";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                comand = "5";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    } );

    btnFataDreapta.setOnTouchListener( new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                comand = "3";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                comand = "5";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    } );

    btnFataStanga.setOnTouchListener( new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                comand = "4";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                comand = "5";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    } );

    btnSpate.setOnTouchListener( new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            if (event.getAction() == MotionEvent.ACTION_DOWN) {
                comand = "2";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else if (event.getAction() == MotionEvent.ACTION_UP) {
                comand = "5";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return false;
        }
    } );

    btnObstacol.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (socket != null) {
                comand = "6";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                comand = "5";
                try {
                    outputStream.write( comand.getBytes() );
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    } );

    btnGaraj.setOnClickListener( new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            commandArduino( "http://" + ip + "/?cmd=1" );
        }
    } );
}

public void commandArduino(String url) {
    try {
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.execute( new HttpGet( url ) );
    } catch (Exception e) {
    }
}

}

android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@drawable/images"
android:minHeight="0dp"
android:visibility="visible"
tools:context="com.td.daniela.control_masina.Telecomanda">

<Button
    android:id="@+id/btnFata"
    style="@style/Widget.AppCompat.Button"
    android:layout_width="98dp"
    android:layout_height="65dp"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/fata"
    android:elevation="0dp"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.096" />

<Button
    android:id="@+id/btnSpate"
    style="@style/Widget.AppCompat.Button"
    android:layout_width="98dp"
    android:layout_height="65dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/spate"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:layout_constraintVertical_bias="0.9" />

<Button
    android:id="@+id/btnFataDreapta"
    style="@style/Widget.AppCompat.Button"
    android:layout_width="98dp"
    android:layout_height="65dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:background="@drawable/stanga"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.306"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btnFataStanga"
    style="@style/Widget.AppCompat.Button"
    android:layout_width="98dp"
    android:layout_height="65dp"
    android:layout_marginBottom="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginStart="8dp"
    android:layout_marginTop="8dp"
    android:background="@mipmap/dreapta"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintHorizontal_bias="0.693"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/btnGaraj"
    android:layout_width="98dp"
    android:layout_height="65dp"
    android:layout_marginBottom="8dp"
    android:layout_marginTop="8dp"
    android:background="@drawable/home"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


text:
Q: Whereas + present participle Is it grammatically correct to use whereas + a present participle?
For example:
I am disinclined to recognize my weak mathematical skills, whereas willing to admit my lack of English skills.
This sounds silly to me, but the reason I am asking is because this same sentence seems to work when using while instead of whereas
Same example with while:
I am disinclined to recognize my weak mathematical skills, while willing to admit my lack of English skills.
Are they both grammatically correct? Are they both incorrect? Is one correct, but not the other?
If the example with while is grammatically incorrect, then is the following sentence also grammatically incorrect?
He does the dishes while singing.

A: After doing some reading, I think it is grammatically correct to use whereas + a non-finite participle clause - it just may not be idiomatically correct (as suggested by @JasonBassford).
One of my sources for coming to this conclusion is the Cambridge dictionary. As explained in this article:

We often use non-finite clauses after some subordinating conjunctions
  like after, although, though and if.

A: Here is the hard-and-fast grammatical pattern taken from the language itself as a living organism (maybe that is going too far) that shows that whereas is not a subordinating conjunction.

*

*The boys played tennis and the girls played volleyball.

Everyone (I hope) will agree that the word and is a coordinating conjunction because the bits on either side of it, but not including it, can stand on their own. Can they stand on their own? Yes? Well, then the word and is what allows that.
You can substitute any of the so-called coordinating conjunctions there, remove them and you create two stand-alone utterances that are independent clauses. That is way to see how two independent clauses may be joined.

*

*The boys played tennis but the girls played volleyball. [coordinator:but]

*The boys played tennis. The girls played volleyball.
Now, if you use whereas instead of and, the same is true as regards the sentence above.
Now take the OP's sentence:

*

*I am disinclined to recognize my weak mathematical skills, whereas willing to admit my lack of English skills.

If you want to introduce a whereas in that sentence, you need to do this:

*

*I am not willing to recognize my weak mathematical skills whereas I am willing to admit my lack of English skills. OR

*I am disinclined to recognize my weak mathematical skills whereas I am willing to admit my lack of English skills.

*I am disinclined to recognize my weak mathematical skills whereas I am not disinclined to admit my lack of English skills. or: not so disinclined as regards my English skills.
Most grammars/grammarians do classify the word whereas as a
  subordinating conjunction where an independent clause is joined to an
  dependent one. However, all you need to do is see whereas used in texts,to see that the clauses used with it are not "subordinate to one another."

The word whereas in sentences contrasting "equal" utterances (subject, verb and predicate) plays a coordination role and not a subordination role. This can be seen by substituting any of the well-known coordinators such as but or yet where two clauses are coordinated, which are called coordinating words, and there is no "subordination". The kind of logic one finds with subordinating conjunctions is not the actual logic of the use of whereas (in its non-time meanings).
Here is a traditional explanation of a subordinating conjunctions, and it's pretty good too: subordinating conjunctions


text:
Q: Solr Master Slave Failover setup for High Availability While using Solr (we are currently using 3.5), how do we setup the Masters for a Failover?
Lets say in my Setup I have Two Masters and Two Slaves.  The Application commits all the writes to One Active Master, and both the slaves get the updates from this Active Master.  There is another repeater which serves the same purpose of the Master.
Now my question is if the Master for some reason comes down, how can I make the Repeater as a Master without any Manual intervention.   How can the slaves start getting the updates from the Repeater instead of the broken Master.   Is there a recommended way to do this?  Are there any other recommended Master/Slave setup's to ensure High availability of the Solr systems?

A: At this time, your best option is probably to investigate the SolrCloud functionality present in the current Solr 4.0 alpha, which at the time of this writing is due for its final release within a few months. The goal of SolrCloud is to handle data distribution and master election, using the ZooKeeper distributed database to maintain consensus within the cluster about which nodes are serving in while roles.
There are other more traditional ways to set up failover for Solr 3's replicated master-slave architecture, but I personally wouldn't want to make that investment with Solr 4.0 so near to release.
Edit: See Linux-HA, for one such traditional approach. Personally, I would create a purpose-built daemon that reconfigures your cores and load balancer, using ZooKeeper for presence detection and distributed locks.
If outsourcing is an option, you might consider a hosted service such as my own humble Websolr. We provide this kind of distribution and hot failover by default, so our customers don't have to worry as much about the mechanics of how it's implemented.

A: I agree with Nick. The way replication works in Solr 3.x is not always handy, especially for master fail-over. If you are going to consider Solr 4 you might want to have a look at elasticsearch too, which solves this kind of problems in a really brilliant way!
It uses push replication instead of the pull mechanism used by Solr. That means the document is literally reindexed on all nodes. It might sound strange but that allows to reduce the network load (due to segment merge for example). Furthermore, a node is elected as master and if it crashes one other node will automatically replace it becoming the new master.


text:
Q: Should a web app for a service access its data via its own API or directly? I'm building a service that will consist of mobile and desktop apps, which will require me to build my own RESTful web API to easily keep the data for the service in sync.  I am also building a web app in Ruby on Rails.  Initially I plan to host everything on one server due to cost.
I'm curious which is a better design:

*

*Have the Rails app access the database strictly via calls to the API
to allow for the future ability to host them on separate servers.

*Host the API and Rails app on the same server always, and have each access the database directly.

I'm currently planning on the API to be private, with the possibility of opening up a small portion of it later.
Disclaimer: This would be my first time building my own API

A: It is better to go with the first option. Having your 3 clients - mobile, desktop and webapp - use the API in the same way is a better design since all of them use the API in a consistent manner, and any changes in the API will be reflected as-is in all the three clients.
This way it is easier to debug and simpler to extend new features. If your Rails app talks directly to the database you will have to modify the data access code (instead of the ReST client code) in your Rails app every time the API changes and the Rails app might end up modifying the data in a different way than the desktop and mobile app, leading to inconsistencies.
In a nutshell: Keeping consistent access mechanism will ensure better maintainability.


text:
Q: R Moving Yahoo Fantasy API from Oauth 1 to Oauth2 It appears that Yahoo has discontinued support for oauth1.0. I am trying to update my R code to use oauth2.0 using the httr package, and am stumped. I am able to get token, but am unable to use the token to query the api.
I continue to get "You are not authorized to view this league".
options("httr_oob_default" = T)
library(httr)

b_url <- "https://fantasysports.yahooapis.com" #base url

#Create Endpoint
yahoo <- httr::oauth_endpoint(authorize = "https://api.login.yahoo.com/oauth2/request_auth"
                                       , access = "https://api.login.yahoo.com/oauth2/get_token"
                                       , base_url = b_url)
#Create App
yahoo_app <- httr::oauth_app("yahoo", key=cKey, secret = cSecret,redirect_uri = "oob")

#Open Browser to Authorization Code
httr::BROWSE(httr::oauth2.0_authorize_url(yahoo, yahoo_app, scope="fspt-r"
                                          , redirect_uri = yahoo_app$redirect_uri))
#Code = zp6v82a

#Create Token
yahoo_token<- httr::oauth2.0_access_token(yahoo,yahoo_app,code="zp6v82a")

Now im not sure where to go from here.
If there is any advice, or an easier method please let me know. I am an amateur coder so please, be gentle.


text:
Q: Read and access twitter response in json format I am reading twitter response as a json and trying to read it's content.
I have applied json loads, even it displays result value as invalid json. Twitter response has been stored into .json file
    with open(filename) as f:
        for line_terminated in f:
            line = line_terminated.rstrip('\n')
            if (len(line.split())) != 0:
                doc = json.loads(line)
                print doc

one of the value of doc is :
{u'contributors': None, u'truncated': False, u'text': u'RT @eci_ttip: UK Leave vote deflates hopes for #TTIP trade deal https://fdfdR1hIwdqng1 via @moneycontrolcom', u'is_quote_status': False, u'in_reply_to_status_id': None, u'id': 747348906208460800, u'favorite_count': 0, u'entities': {u'user_mentions': [{u'indices': [3, 12], u'id': 2613612890, u'screen_name': u'eci_ttip', u'name': u'Stop TTIP', u'id_str': u'2613612890'}, {u'indices': [92, 108], u'id': 68927629, u'screen_name': u'moneycontrolcom', u'name': u'moneycontrol', u'id_str': u'68927629'}], u'symbols': [], u'hashtags': [{u'indices': [47, 52], u'text': u'TTIP'}], u'urls': [{u'indices': [64, 87], u'url': u'https://twtR1hIwdqng1', u'expanded_url': u'http://t.in.com/21yS', u'display_url': u't.in.com/21yS'}]}, u'retweeted': False, u'coordinates': None, u'timestamp_ms': u'1467016838968', u'source': u'Twitter for Android', u'in_reply_to_screen_name': None, u'id_str': u'747348906208460800', u'retweet_count': 0, u'in_reply_to_user_id': None, u'favorited': False, u'retweeted_status': {u'contributors': None, u'truncated': False, u'text': u'UK Leave vote deflates hopes for #TTIP trade deal https://ttwitter.cme/R1hIwdqng1 via @moneycontrolcom', u'is_quote_status': False, u'in_reply_to_status_id': None, u'id': 747347273579794432, u'favorite_count': 2, u'entities': {u'user_mentions': [{u'indices': [78, 94], u'id': 68927629, u'screen_name': u'moneycontrolcom', u'name': u'moneycontrol', u'id_str': u'68927629'}], u'symbols': [], u'hashtags': [{u'indices': [33, 38], u'text': u'TTIP'}], u'urls': [{u'indices': [50, 73], u'url': u'https://twitter.com', u'expanded_url': u'http://t.in.com/21yS', u'display_url': u't.in.com/21yS'}]}, u'retweeted': False, u'coordinates': None, u'source': u'Twitter Web Client', u'in_reply_to_screen_name': None, u'id_str': u'747347273579794432', u'retweet_count': 5, u'in_reply_to_user_id': None, u'favorited': False, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'contributors_enabled': False, u'id': 2613612890, u'verified': False, u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/745615537737207808/decyhsav_normal.jpg', u'profile_sidebar_fill_color': u'DDEEF6', u'profile_text_color': u'333333', u'followers_count': 13887, u'protected': False, u'id_str': u'2613612890', u'default_profile_image': False, u'listed_count': 316, u'utc_offset': 10800, u'statuses_count': 4764, u'description': u"The self-organized European Citizens' Initiative to stop TTIP and CETA which from October 7th 2015 continues campaigning as an European Initiative.", u'friends_count': 1090, u'location': u'European Union', u'profile_link_color': u'0084B4', u'profile_image_url': u'http://pbs.twimg.com/profile_images/745615537737207808/decyhsav_normal.jpg', u'following': None, u'geo_enabled': False, u'profile_background_color': u'C0DEED', u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/2613612890/1466603542', u'profile_background_image_url': u'http://abs.twimg.com/images/themes/theme1/bg.png', u'name': u'Stop TTIP', u'lang': u'en', u'profile_background_tile': False, u'favourites_count': 3409, u'screen_name': u'eci_ttip', u'notifications': None, u'url': u'http://stop-ttip.org', u'created_at': u'Wed Jul 09 14:04:30 +0000 2014', u'profile_background_image_url_https': u'https://abs.twimg.com/images/themes/theme1/bg.png', u'time_zone': u'Athens', u'profile_sidebar_border_color': u'C0DEED', u'default_profile': True, u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'lang': u'en', u'created_at': u'Mon Jun 27 08:34:09 +0000 2016', u'filter_level': u'low', u'in_reply_to_status_id_str': None, u'place': None}, u'user': {u'follow_request_sent': None, u'profile_use_background_image': True, u'contributors_enabled': False, u'id': 145999456, u'verified': False, u'profile_image_url_https': u'https://pbs.twimg.com/profile_images/747179195361562624/KzWjBe0R_normal.jpg', u'profile_sidebar_fill_color': u'DDEEF6', u'profile_text_color': u'333333', u'followers_count': 1692, u'protected': False, u'id_str': u'145999456', u'default_profile_image': False, u'listed_count': 47, u'utc_offset': 7200, u'statuses_count': 90111, u'description': u'http://noalttip.org/actua El conocimiento es el ant\xeddoto del miedo  #noTTIP', u'friends_count': 2385, u'location': u'a otra cosa mariposa,  espe ', u'profile_link_color': u'0084B4', u'profile_image_url': u'http://pbs.twimg.com/profile_images/747179195361562624/KzWjBe0R_normal.jpg', u'following': None, u'geo_enabled': True, u'profile_background_color': u'C0DEED', u'profile_banner_url': u'https://pbs.twimg.com/profile_banners/145999456/1449143895', u'profile_background_image_url': u'http://pbs.twimg.com/profile_background_images/297105510/Spanishrevolution2-640x420.jpg', u'name': u'Ram\xf3n #noTTIP', u'lang': u'es', u'profile_background_tile': False, u'favourites_count': 11060, u'screen_name': u'klf129', u'notifications': None, u'url': u'http://noalttip.blogspot.com.es/?m=1', u'created_at': u'Thu May 20 11:01:46 +0000 2010', u'profile_background_image_url_https': u'https://pbs.twimg.com/profile_background_images/297105510/Spanishrevolution2-640x420.jpg', u'time_zone': u'Amsterdam', u'profile_sidebar_border_color': u'C0DEED', u'default_profile': False, u'is_translator': False}, u'geo': None, u'in_reply_to_user_id_str': None, u'possibly_sensitive': False, u'lang': u'en', u'created_at': u'Mon Jun 27 08:40:38 +0000 2016', u'filter_level': u'low', u'in_reply_to_status_id_str': None, u'place': None}

Which I can not access as dic.
Could anyone please correct if I am wrong.

A:
Which I can not access as dic

Eh, No. doc is a dictionary and values can be accessed using the keys:
>>> doc = {u'contributors': None, u'truncated': False}
>>> doc['truncated']
False

But you have certain values that are wrapped inside lists. To access these values, you will need to access the key of the parent dictionary, index the list at the dictionary value and then access the key for the dictionary in the list. Like so:
>>> doc['entities']['user_mentions']
[{'screen_name': 'eci_ttip', 'id_str': '2613612890', 'id': 2613612890, 'indices': [3, 12], 'name': 'Stop TTIP'}, {'screen_name': 'moneycontrolcom', 'id_str': '68927629', 'id': 68927629, 'indices': [92, 108], 'name': 'moneycontrol'}]
>>>
>>> doc['entities']['user_mentions'][0]
{'screen_name': 'eci_ttip', 'id_str': '2613612890', 'id': 2613612890, 'indices': [3, 12], 'name': 'Stop TTIP'}
>>>
>>> doc['entities']['user_mentions'][0]['screen_name']
'eci_ttip'

So you should know how and where a particular value is structured in the dict, in order to access it.
I suggest you use pprint to print the dictionaries to have a better view of the entire structure:
from pprint import pprint

pprint(doc)


text:
Q: DBIC- select specific columns in "prefetch" while maintaining has_many relationship I have two tables with 'Artist' has_many 'CD' .
I want to fetch 'artist' and 'CDs' and use HashRefInflator to get something like (JSON format)
I use 'HashRefInflator'.
     [ {

        "artist_name": "Dummy",
        "artist_id": "1",
            "cds": [{
            "cd_id": "1,
            "cd_desc": "Dummy",
            }],
         },
      ]

When I use
$schema->resultset('Artist')->search({},
                                       {
                                         prefetch => 'cds',
                                       });

I get result with "EXTRA" column from CD table. I want to be able to select only specific column from 'CD'.
When I use
$schema->resultset('Artist')->search({},
                                     {'+select' => [ 'columns I need' ],
                                      '+as' => [ 'col names' ],
                                     });

I get 'columns i need' merged with main columns instead of a hierarchy.
      [ {
        "artist_name": "Dummy",
        "artist_id": "1",
        "cds": []
        **"cd_id": "1,
        "cd_desc": "Dummy",**

         },
        ]

How can I prefetch specific columns from related table while maintaining the hierarchical structure?
Edit: I am sorry if I was not very clear. The problem here with join and +columns / +select is that it does not preserve the hierarchical data structure.
The 'cds' should be an array of objects within 'Artist' object.Instead it gets joined at Artist level.
I could not use "collapse" as I have an older version of DBIx::Class. I would try to install a later version and check.

A: Use join instead of prefetch:
$schema->resultset('Artist')->search(
    {},
    {
        join         => ['cds'],
        '+select'    => ['cd.desc'],
        result_class => 'DBIx::Class::ResultClass::HashRefInflator'
    }
);

A: You'll need DBIx::Class version 0.08250 or later which supports the collapse result set attribute:
my $rs = $schema->resultset('Artist')->search({}, {
    '+columns' => [ qw/ cds.col1 cds.col2 / ],
    join       => 'cds',
    collapse   => 1,
});


text:
Q: creo que hay un error en el condicional del metodo *darPesoEnKilogramos package taller_practico;
import java.util.Scanner;
/**
 *
 * @author salas
 */
public class Punto5 {

    // ---------------------------
    //--------------atributos
    private double pesoEnToneladas;
    private double pesoEnKilogramos;
    //------------------------------
    //---------------getters and setters

    public double getPesoEnToneladas() {
        return pesoEnToneladas;
    }

    public void getPesoEnToneladas(double pesoEnToneladas) {
        this.pesoEnToneladas = pesoEnToneladas;
    }

    public double getPesoEnKilogramos() {
        return pesoEnKilogramos;
    }

    public void setPesoEnKilogramos(double pesoEnKilogramos) {
        this.pesoEnKilogramos = pesoEnKilogramos;
    }

//_-------------------------------
    // constructor vacio
    public Punto5() {
   }
    //--------------------------------
    //----------convertir peso a kilogramos

    public double darPesoEnKilogramos(double pesoEntoneladas){
         double pesoEnKilogramos = 0.0;

        if(pesoEnToneladas>=4 && pesoEnToneladas<=7.5){
            pesoEnKilogramos = pesoEnToneladas*1000;

        }/*else{

             salida ="el peso a ingresar no puede ser menor a 4 toneladas ni mayor a 7.5 toneladas";
        }*/
        return pesoEnKilogramos;
    }

    public static void main(String[] args){
        Punto5 punto5 = new Punto5();
        Scanner scanner = new Scanner(System.in);
        System.out.println("ingrese el peso del elefante en toneladas");
        double pesoEnToneladas = scanner.nextDouble();
        System.out.println(punto5.darPesoEnKilogramos(pesoEnToneladas));

    }
}


text:
Q: Software Development Kit version is not the same as WebSphere Application Server I have installed IBM WebSphere Application Server ND V7, and I want to install fix pack 7 on this WAS ND V7. So, I have installed Update Installer and installed fix pack on WAS ND, installed fix pack successfully. Now, I want to install WebSphere Application Server feature pack for XML, so tried to install this feature pack using IBM Installation Manager v1.6.2, but it throwing the below error,
Installation Manager detected one or more packages that cannot be synchronized. Installation Manager cannot manage installation packages until they are synchronized.
You can import the packages again to synchronize Installation Manager with your imported packages.
You must configure repository connections and ensure that you can access the network or repository media to keep imported packages synchronized.
  Package data for these locations was not synchronized:
    C:\IBM\WAS_ND_7
      The Software Development Kit version is not the same as the IBM WebSphere Application Server - ND version.
Use another tool, such as the Update Installer for WebSphere Software, to synchronize the versions.

A: Please ensure you install the same fixpack level for SDK as is installed for WAS. I.e. if WAS is at 7.0.0.7, please install SDK fixpack 7. For IM to be in synch with WAS, WAS and SDK fixpack levels should match.


text:
Q: Read or select value names from .json file to push in the array if myjson.js file data:
{
  "key1": [
    {
      "name1": [
        "word1",
        "word2",
      ],
      "name2": [
        "word3",
        "word4",
      ]
    }
  ]
}

loaded:
  var jsonData = fs.readFileSync("myjson.json", "utf8");
  const data = JSON.parse(jsonData);

  console.log(Object.keys(data));

output:
[ 'key1' ]

or:
 console.log(Object.values(data));

output:
[
  [
    {
      name1: [Array],
      name2: [Array],
    }
  ]
]

How properly read or select only value names (without 'value' values - arrays) to create  array of value names:
[
   "name1",
   "name2",
]

A: You can use Array#flatMap over each of the arrays of objects.

const data={key1:[{name1:["word1","word2",],name2:["word3","word4",]}]};
let res = Object.values(data).flatMap(x => x.flatMap(Object.keys));
console.log(res);

A: Note key1 is actually an array.

const obj = {
  "key1": [
    {
      "name1": [
        "word1",
        "word2",
      ],
      "name2": [
        "word3",
        "word4",
      ]
    }
  ]
};

console.log(Object.keys(obj.key1[0]));


text:
Q: Why is turbo rails remove action not removing this div and returning this error? I've got a Rails 6 app using turbo-rails. In my HTML I'm rendering a div like so
<div id="<%= dom_id(@enroll)%>">

When I click a button_to tag I trigger the destroy action that runs a destroy.turbo_stream.erb view file
<%= turbo_stream.remove dom_id(@enroll) %>

When this runs, however, I get this error in the browser console
Error: <turbo-stream action="remove" target="enroll_2423">: first child element must be a <template> element

Judging by the turbo docs remove actions don't need a <template> (of course).
Why is that the case? Could this be a bug with the turbo library?


text:
Q: States for input field when typing Is there some sort of state(like :hover, :focus, :active) for when typing in an input field only using CSS or does this have to be done in another way like JavaScript?
What I want to achieve is to only display a character counter when someone is typing.

A:
There is no state in css when typing in an input field.

Please see the link for more info about pseudo classes
https://www.w3schools.com/css/css_pseudo_classes.asp

The state for input when typing is possible in javascript.

Please see the code below.

document.getElementById("demo").addEventListener("keypress", myFunction);

function myFunction() {
    alert("Someone is typing");
}
<input type="text" id="demo">

You can see more info about onkeypress in this link

https://www.w3schools.com/jsref/event_onkeypress.asp
Hope this helps.


text:
Q: Click event not working on google ads iframe I am trying to make a script which detects clicks on google ads. All events works like onmouseover, out etc except click, focus, mousedown. When i click on google ads it open its ads link but dont run my jquery script on click event. I have tried preventdefault and other functions like that too.
I want to detect click on google ads and parse the iframe width and height to php file when clicked.
$(window).load(function(){
    $('iframe').bind('mouseover', function(){
        var iframeID = $(this).attr('id');
        $(this).contents().find('html').unbind();
        $(this).contents().find('html').bind('click', function(){
            alert(iframeID);
        });
    });
});

This is the code run on mouseover but not on click event.

A: You need to bind the click events on the contents of the iframe untill the contents are loaded completely inside the iframe. Try wrapping the code inside the load event.
  $('iframe').load(function() {
       var iframeID = $(this).attr('id');
       $(this).contents().find('html').unbind();
       $(this).contents().find('html').bind('click', function(){
           alert(iframeID);
       });
  });

A: Capturing the click event of an iFrame is not possible when the content is from another domain.
What you can do is detect the mouse-enter and leave on iframe.
Here is example


text:
Q: In an isothermal process there is no change in internal energy, but why in an isobaric one?
*

*In an isothermal process, the heat Q added (which increases the temperature and internal energy) is exactly cancelled out by the work W done by the gas in the environment (which lowers the temperature and internal energy), so that neither the internal energy nor the temperature of the gas changes.

(Chet Miller (https://physics.stackexchange.com/users/102308/chet-miller), Work done in Isobaric Process, URL (version: 2018-07-05): https://physics.stackexchange.com/q/415224)
But why doesn't this also happen in the isobaric process? Volume work is also done there. But there is a little left over after the volume work (83.15J in my example (picture)), why?

My question could possibly be a duplicate of my previous one: Enthalpy, why is work only partially done? i have only made it a little more concrete here (hopefully).
A molecular interpretation would be very helpful, for example i imagined if the gas had only 2 translational degrees of freedom, there would be no change in internal energy in the isobaric process too (166,29J - 166,29J = 0J).

A:
But why doesn't this also happen in the isobaric process? Volume work
is also done there.

Because unlike the isothermal process where the initial and final temperatures are the same making $\Delta U=0$ for an ideal gas, the final temperature of the isobaric process is greater than the initial temperature resulting in an increase in internal energy.
This can be shown by applying the ideal gas equation to the initial and final states, where
$$\frac{P_{f}V_{f}}{T_{f}}=\frac{P_{i}V_{i}}{T_{i}}$$
For the isobaric process, $P_{f}=P_{i}$. Therefore
$$T_{f}=T_{i}\frac{V_{f}}{V_{i}}$$
Since for the expansion $V_{f}>V_i$ the final temperature if greater than the initial. Finally, since for an ideal gas
$$\Delta U=nC_{v}(T_{f}-T_i)$$
There is an increase in internal energy.
Bottom line: Not all the heat goes into work because part of it increases the internal energy. The added heat is not "canceled out" by the work done.
Hope this helps.


text:
Q: Understanding 400 error during AJAX Post request to Flask endpoint Trying to understand what I'm doing wrong here when using JQuery AJAX POST request to send both form data and an attached file to a Flask endpoint.
The basic Flask view that I'm still building looks like this:
@main.route('/videoupload', methods=['GET','POST'])
def videoupload():
    if request.method == 'POST':
        ajaxpost = request.form['m_data']
        print(ajaxpost)
    return render_template('videoupload.html')

The JQuery for the form and attached file looks like this:
$("#submit_btn").click(function() {
        var proceed = true;

        if(proceed) //everything looks good! proceed...
        {
            //data to be sent to server
            var m_data = new FormData();
            m_data.append( 'video_title', $('input[name=videoTitle]').val());
            m_data.append( 'video_description', $('input[name=videoDescription]').val());
            m_data.append( 'video_tags', $('input[name=videoTags]').val());
            m_data.append( 'file_attach', $('input[name=file_attach]')[0].files[0]);
            //instead of $.post() we are using $.ajax()
            //that's because $.ajax() has more options and flexibly.
            $.ajax({
              url: '/videoupload',
              data: m_data,
              processData: false,
              contentType: false,
              type: 'POST',
                  //dataType:'json',
              datatype:'json',
              success: function(response){
                 //load json data from server and output message
                if(response.type == 'error'){ //load json data from server and output message
                    output = '
'+response.text+'
';
                }else{
                    output = '
'+response.text+'
';
                }
                $("#videoform #form_results").hide().html(output).slideDown();
              }
            });
        }
    });

Using Firebug and the Net window, I can confirm that data entered in the fields of the form and the attached file are being appended to the FormData() object.
When the user clicks Submit button, I get the following error in the Console:
> POST http://127.0.0.1:8000/videoupload 400 (BAD REQUEST)
send @ jquery.js:9664
m.extend.ajax @ jquery.js:9215
(anonymous function) @ videoupload:137
n.event.dispatch @ jquery.min.js:3
r.handle @ jquery.min.js:3

Navigated to http://127.0.0.1:8000/videoupload?videoTitle=asdf&videoDescription=asdfasdfasdfasdfasdf&videoTags=ZcZXcZXcZXcZXC&file_attach=ScreenCaptureProject1.mp4

In the Terminal window running Flask app (using Gunicorn) running in debug mode, no errors appear:
[2016-05-20 00:18:21 -0400] [27033] [DEBUG] POST /videoupload
POST CALLED
[2016-05-20 00:18:24 -0400] [27033] [DEBUG] GET /videoupload

It seems as though the AJAX is pinging the Flask view with a POST request. Am I handling the form incorrectly in the Flask view? Is there something incorrect with the JQuery AJAX POST request that Flask doesn't like?

A: request.form is a MultiDict with the key-value pairs of the received form data.
You are attempting to index this dictionary using the string 'm_data' as a key, but it looks like 'm_data' is just the name of your JavaScript variable and not actually a key of the form data. If 'm_data' is not a valid key this would raise an exception.
To quote the Werkzeug documentation on MultiDicts:

"From Werkzeug 0.3 onwards, the KeyError raised by this class is also
  a subclass of the BadRequest HTTP exception and will render a page for
  a 400 BAD REQUEST if caught in a catch-all for HTTP exceptions."

To help debug this route, you can wrap your python code in a try-except block:
@main.route('/videoupload', methods=['GET','POST'])
def videoupload():
    if request.method == 'POST':
        try:
            [your code]
        except Exception, e:
            print e
    return render_template('videoupload.html')

Then you can check whether a KeyError appears in the error logs (or console if you're running the Flask test server locally).


text:
Q: Panasonic MN39470PT CCD Sensor Timing The datasheet for the MN39470PT CCD sensor seems to be missing some details regarding the timing needed to drive the sensor. For this reason I'm very confused on how I'd drive the sensor particularly regarding why there seem to be six vertical clock inputs.
What kind of timing is needed to drive this sensor?
For reference the datasheet I'm reading is located here: https://datasheet.datasheetarchive.com/originals/distributors/Datasheets-24/DSA-474480.pdf
A backup copy is located here in case the above link does not work for you: https://web.archive.org/web/20210922020336/https://datasheet.datasheetarchive.com/originals/distributors/Datasheets-24/DSA-474480.pdf


text:
Q: tictactoe iteration issue. Function error I am new to programming (About 2 months in to teaching myself). I am attempting to create a game of tic tac toe and use it as an opportunity to practice using functions and passing parameters.
I have got most of what I want to work working (for now I will add AI and a computer opponent) but when one of the human players win the endgame() function is called but it does not work as expected. It calls itself somehow and you have got to say N to end the game three times before the program is terminated. I am unable to see the wood for the trees on this one folks so help would be appreciated.
I know some of my coding will not be great so no trolling please.
Thanks
Shaun
def start():

    choices = [" "," "," "," "," "," "," "," "," "]
    while checkwin(choices)==False:
        board(choices)
        getchoice(choices)

def board(choices):

    print("+---+---+---+")
    print("+ "+choices[0]+" + "+choices[1]+" + "+choices[2]+" +")
    print("+---+---+---+")
    print("+ "+choices[3]+" + "+choices[4]+" + "+choices[5]+" +")
    print("+---+---+---+")
    print("+ "+choices[6]+" + "+choices[7]+" + "+choices[8]+" +")
    print("+---+---+---+")

def endgame(winner):

    print("The winner is "+ winner)
    playagain=input("Another game? Y/N")
    playagain = playagain.upper()
    if playagain == "N":
        print("Thanks, hope to see you again soon.")
    else:
        start()

def getchoice(choices):

    userchoice = int(input ("Where would you like to put your X?"))
    index = userchoice-1
    while choices[index]!=" ":
        userchoice = int(input ("That space is taken. Where would you like to put your X?"))
        index = userchoice-1

    choices[index]="X"
    board(choices)
    if checkwin(choices)==False:
        userchoice = int(input ("Where would you like to put your O?"))
        index = userchoice-1
        while choices[index]!=" ":
            userchoice = int(input ("That space is taken. Where would you like to put your O?"))
            index = userchoice-1

        choices[index]="O"
    checkwin(choices)
    return choices

def checkwin (c):

    if checkwin1(c)==False:
        if checkwin2 (c)==False:
            return False
        else:
            endgame("Player 2")
    else:
        endgame("Player 1")

def checkwin1(c):

    return ((c[0]=="X" and c[1]=="X" and c[2]=="X") or
(c[3]=="X"and c[4]=="X" and c[5] =="X") or
(c[6]=="X"and c[7]=="X" and c[8] =="X") or
(c[0]=="X"and c[3]=="X" and c[6] =="X" )or
(c[1]=="X"and c[4]=="X" and c[7] =="X") or
(c[2]=="X"and c[5]=="X" and c[8] =="X") or
(c[0]=="X"and c[4]=="X" and c[8] =="X") or
(c[6]=="X"and c[4]=="X" and c[2] =="X"))

def checkwin2(c):

    return ((c[0]=="O" and c[1]=="O" and c[2]=="O") or
(c[3]=="O"and c[4]=="O" and c[5] =="O") or
(c[6]=="O"and c[7]=="O" and c[8] =="O") or
(c[0]=="O"and c[3]=="O" and c[6] =="O" )or
(c[1]=="O"and c[4]=="O" and c[7] =="O") or
(c[2]=="O"and c[5]=="O" and c[8] =="O") or
(c[0]=="O"and c[4]=="O" and c[8] =="O") or
(c[6]=="O"and c[4]=="O" and c[2] =="O"))

start()

A: Let's imagine that X wins (because this is probably what caused it to "end") three times.
You then get to if checkwin(choices)==False: within getchoice(),
'checkwin()' happily calls endgame(). endgame() returns, and then getchoice() continues executing.
At the end of getchoice(), checkwin() is called again, with the same result.
After getchoice() returns we get back to while checkwin(choices)==False: within start(), once again with the same result.
Also note that you will see this happening even more times if you actually played multiple games in a row.
Also try making O win, I think you will only have to say no to your prompt twice in that case.
EDIT:
class TicTacToeGame:
    INCOMPLETE = 0
    WINNER_PLAYER_1 = 1
    WINNER_PLAYER_2 = 2
    DRAW = 3

    SYMBOLS=["X","O"," "]

    def __init__(self,player_1, player_2):
        self.board = [[-1]*3,[-1]*3,[-1]*3]
        self.players = [player_1,player_2]
        self.current_turn = 0;

    def advance(self):
        if self.calcGameState() != TicTacToeGame.INCOMPLETE:
            return
        while True:
            x,y = self.players[self.current_turn].getMove();
            if x < 0 or x > 2 or y < 0 or y>2 :
                continue
            if self.board[y][x] == -1:
                break
        self.board[y][x] = self.current_turn
        self.current_turn += 1
        self.current_turn %= 2

    def stringify(self):
        re = ""
        fr = True
        for row in self.board:
            if fr:
                fr=False
            else:
                re+= "\n" + "---+" * 2 + "---\n"
            fe = True
            for el in row :
                if fe:
                    fe = False;
                else:
                    re += "|"
                re += " " + TicTacToeGame.SYMBOLS[el] + " "
        return re

    def calcGameState(self):
        for i in range(0,3):
            #col
            if all(self.board[i][j] == self.board[i][0] for j in range(0,3)) and self.board[i][0] != -1:
                return self.board[i][0] + 1
            #row
            if all(self.board[j][i] == self.board[0][i] for j in range(0,3)) and self.board[0][i] != -1:
                return self.board[0][i] + 1
        if all(self.board[i][i] == self.board[0][0] for i in range(0,3)) and self.board[0][0] != -1:
            return self.board[0][0] + 1
        if all(self.board[i][2-i] == self.board[0][2] for i in range(0,3)) and self.board[0][2] != -1:
            return self.board[0][2] + 1
        if all(self.board[i][j] != -1 for i in range(0,3) for j in range(0,3)):
            return TicTacToeGame.DRAW
        return TicTacToeGame.INCOMPLETE

    def stringResult(self):
        res = self.calcGameState()
        if res == TicTacToeGame.INCOMPLETE:
            return "Incomplete"
        if res == TicTacToeGame.DRAW:
            return "Draw"
        return "Player " + self.SYMBOLS[res-1] + " Won!"

class HumanPlayer:
    def __init__(self):
        self.board = None

    def setGame(self,game):
        self.game = game

    def getMove(self):
        print(self.game.stringify())
        print("Current turn is: " + self.game.SYMBOLS[self.game.current_turn])
        print("enter row for move")
        y = input()
        print("enter col for move")
        x = input()
        return int(x)-1,int(y)-1

def playAgain():
    playagain=input("Another game? Y/N\n > ")
    playagain = playagain.upper()
    if playagain == "N":
        print("Thanks, hope to see you again soon.")
        return False
    return True

while True:
    p = HumanPlayer()
    t = TicTacToeGame(p,p)
    p.setGame(t)

    while t.calcGameState() == TicTacToeGame.INCOMPLETE:
        t.advance()
    print(t.stringResult())
    if not playAgain():
        break;


text:
Q: Excel Vba Abnormal Behavior of Cells.Find on Merged Cells RESOLVED: Error was caused by manipulating find's properties elsewhere
I'm very new to the world of VBA and I had a question about some abnormal behavior of the Range .Find function I've been experiencing. I have some code that I call in a subroutine as below.
For i = 2 To UBound(pullDataPckg)
        For j = 1 To UBound(section)
            Set cell = dataSheet.Cells.Find(What:=section(j))
           'Below returns nothing on call 2, works for call 1
           'Set cell = dataSheet.Cells.Find(What:="Value from section(j) in second call")

            If Not cell Is Nothing Then
              'Do some stuff
            End If
        Next
Next

pullDataPckg and section are two string arrays, dataSheet is a worksheet object and the code is all located in a Sub that I call to pull data values from a worksheet.
The abnormal behavior I'm experiencing is that Find always returns the cell as Nothing on my second call of the sub (The cells searched for are all merged cells that I know are in the sheet and if I unmerge the cells then the find method is able to locate the cell).
However, if I instead use dataSheet.Range("A1:R999").Find(What:=section(j)) then the method successfully finds the cell. So the problem seemed to be with the Cells property when used with merged cells.
I call the sub two times on the same worksheet so I added a dataSheet.Cells.Find(What:="Known Value in section array of Second Sub Call") call and found that the same code when executed in the first Sub call successfully found the merged cell, while when executed in the second Sub call it failed to find the merged cell (If the cell was unmerged it worked for both calls).
I was hoping someone might be able to shed some light as to why the find method fails when called on the Cells property only in the second Sub call and only with merged cells. Since the test value is hardcoded, able to be found using the Range property/unmerging the cell, and I pass the same worksheet to both calls I'm really scratching my head as to how the Find method could fail only when searching for a merged cell in the second call.
EDIT: There are 5 merged cells that each have a width that spans A:R and a height of 2. Just before the loop starts there is a call to a sub the populates the pullDataPckg array by opening a workbook, pulling information from the workbook into the array, and then closing the workbook. When getting information from the new workbook I call Find() 3 times.

A: Any Find() settings are persistent between calls (just as they are when you use find via the UI).
If your other use of Find changes any parameters other than What you should be sure to explicitly reset those in any subsequent calls.
In general it's always best to explicitly include all arguments to Find which could affect the outcome (such as LookAt, LookIn etc)


text:
Q: Swift HealthKit Trigger Heart Rate Sample I'm able to read average heart rate data from HealthKit for a period of time (duration of workout) with the below code.
However, when I look in the Apple Health app, it shows that the heart rate samples from the Apple Watch are taken very infrequently (every 15-30 min). This makes my average HR read for the period quite inaccurate.
How can I trigger HealthKit to sample (gather) Heart Rate data from the watch and write it to HealthKit?
    let endDate = (calendar as NSCalendar).date(byAdding: NSCalendar.Unit.minute, value: duration, to: startDate, options: NSCalendar.Options())
    let predicate = HKQuery.predicateForSamples(withStart: startDate, end: endDate, options: HKQueryOptions())

    let squery = HKStatisticsQuery(quantityType: heartRateType, quantitySamplePredicate: predicate, options: HKStatisticsOptions.discreteAverage, completionHandler: { (qurt, result, errval) -> Void in

        guard errval == nil else { print("error"); completion(0.0, errval); return }

        var averageHeartRate : Double = 0.0
        if (result != nil && result!.averageQuantity() != nil) {
            let quantity : HKQuantity = result!.averageQuantity()!
            averageHeartRate = quantity.doubleValue(for: HKUnit.count().unitDivided(by: HKUnit.minute()))
        }
    })

A: To get more frequent heart rate data from Apple Watch, the user must be running an app on their watch that is tracking an HKWorkoutSession. If your app has a paired watchOS app that tracks workouts, you can start a workout from the iPhone by using startWatchApp(with workoutConfiguration:completion:).


text:
Q: Forth Roots of $17$ in the P-adic Numbers Does $2y^2=x^4-17$ have a root in every P-adic number field?
My answer is yes, using Hensels lemma.
Let $f(x)=x^4-17$ (all coefficients have P-adic norm less than $1$ for each P-adic norm), let $a$=1, then for $p \neq 2$ we have
$|f(a)|_p=|16|_p=1 < 4=|4a^3|_p^2=|f'(a)|_p^2$
and so $f$ has a root by Hensels lemma.
For $p=2$ we have
$|f(a)|_2=16^{-1}<4^{-1}=|f'(a)|_2^2$
so again, by Hensels lemma, there is a root.
Is this correct? It feels too easy.


text:
Q: Manually trigger jquery Datatable search I'm using the Javascript Datatable with server side searching.
So:
var table = $('#myTable').DataTable({
                responsive: true,
                serverSide: true,
                ajax: {
                    url: myUrl,
                    dataSrc: ''
                },
                fnServerData: function (sSource, aoData, fnCallback, oSettings)
                {
                    oSettings.jqXHR = $.ajax({
                        url: myUrl,
                        success: function (json, status, xhr) {
                            //Do stuff
                        }
                    });
                }
            });

I build the url dynamically using options set on my form.
I would like a button on my form so I can manually trigger the fnServerData function. At the moment I have to type into the included search box.
e.g. <button ng-click="model.search()">Search</button>
Is this possible?
Thanks

A: Here is the code that I used for refresh the DataTable
 var table = $("#gridId").dataTable();
//if you want to add extra parameters in the query
/*table.fnSettings().ajax.data = function (d) {
            $.extend(d, jsonPostData);
        };
*/
table.fnDraw(false);

A: I've found a solution:
var oTable = $('#myTable').dataTable();
oTable.fnFilter('');

A: With the latest DataTable, you need to use following in order to trigger server side call:
table.draw();


text:
Q: Generate all combinations of mathematical expressions that add to target (Java homework/interview) I've tried to solve the problem below for a coding challenge but could not finish it in 1 hour. I have an idea on how the algorithm works but I'm not quite sure how to best implement it. I have my code and problem below.

The first 12 digits of pi are 314159265358.
  We can make these digits into an expression evaluating to 27182 (first 5 digits of e)
      as follows:
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182

or
3 + 1 - 415 * 92 + 65358 = 27182

Notice that the order of the input digits is not changed. Operators (+,-,/, or *) are simply inserted to create the expression.
Write a function to take a list of numbers and a target, and return all the ways that those numbers can be formed into expressions evaluating to the target
For example:
  f("314159265358", 27182) should print:
3 + 1 - 415 * 92 + 65358 = 27182
3 * 1 + 4 * 159 + 26535 + 8 = 27182
3 / 1 + 4 * 159 + 26535 + 8 = 27182
3 * 14 * 15 + 9 + 26535 + 8 = 27182
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8 = 27182

This problem is difficult since you can have any combination of numbers and you don't consider one number at a time. I wasn't sure how to do the combinations and recursion for that step. Notice that parentheses are not provided in the solution, however order of operations is preserved.
My goal is to start off with say
{"3"}
then
{"31", "3+1", "3-1", "3*1" "3/1"}
then
{"314", "31+4", "3+1+4", "3-1-4", "31/4", "31*4", "31-4"} etc.

then look at the every value in the list each time and see if it is target value. If it is, add that string to result list.
Here is my code
public static List<String> combinations(String nums, int target)
    {

        List<String> tempResultList = new ArrayList<String>();
        List<String> realResultList = new ArrayList<String>();
        String originalNum = Character.toString(nums.charAt(0));

        for (int i = 0; i < nums.length(); i++)
        {
            if (i > 0)
            {
                originalNum += nums.charAt(i); //start off with a new number to decompose
            }
            tempResultList.add(originalNum);
            char[] originalNumCharArray = originalNum.toCharArray();
            for (int j = 0; j < originalNumCharArray.length; j++)
            {
                //go through every character to find the combinations?
                // maybe recursion here instead of iterative would be easier...
            }
            for (String s : tempResultList)
            {
                //try to evaluate
                int temp = 0;
               if (s.contains("*") || s.contains("/") || s.contains("+") || s.contains("-"))
               {
                  //evaluate expression
               } else {
                   //just a number
               }
                if (temp == target)
                {
                    realResultList.add(s);
                }

            }
         tempResultList.clear();
        }
        return realResultList;
    }

Could someone help with this problem? Looking for an answer with coding in it, since I need help with the generation of possibilities

A: First, you need a method where you can input the expression
3141 * 5 / 9 * 26 / 5 * 3 - 5 * 8

and get the answer:
27182

Next, you need to create a tree structure.  Your first and second levels are complete.
3
31, 3 + 1, 3 - 1, 3 * 1, 3 / 1

Your third level lacks a few expressions.
31 -> 314, 31 + 4, 31 - 4, 31 * 4, 31 / 4
3 + 1 -> 3 + 14, 3 + 1 + 4, 3 + 1 - 4, 3 + 1 * 4, 3 + 1 / 4
3 - 1 -> 3 - 14, 3 - 1 + 4, 3 - 1 - 4, 3 - 1 * 4, 3 - 1 / 4
3 * 1 -> 3 * 14, 3 * 1 + 4, 3 * 1 - 4, 3 * 1 * 4, 3 * 1 / 4
3 / 1 -> 3 / 14, 3 / 1 + 4, 3 / 1 - 4, 3 / 1 * 4, 3 / 1 / 4

You can stop adding leaves to a branch of the tree when a division yields a non integer.
As you can see, the number of leaves at each level of your tree is going to increase at a rapid rate.
For each leaf, you have to append the next value, the next value added, subtracted, multiplied, and divided.  As a final example, here are 5 of the fourth level leaves:
3 * 1 + 4 -> 3 * 1 + 41, 3 * 1 + 4 + 1, 3 * 1 + 4 - 1, 3 * 1 + 4 * 1,
    3 * 1 + 4 / 1

Your code has to generate 5 expression leaves for each leaf until you've used all of the input digits.
When you've used all of the input digits, check each leaf equation to see if it equals the value.

A: I don't think it's necessary to build a tree, you should be able to calculate as you go -- you just need to delay additions and subtractions slightly in order to be able take the precedence into account correctly:
static void check(double sum, double previous, String digits, double target, String expr) {
   if (digits.length() == 0) {
     if (sum + previous == target) {
       System.out.println(expr + " = " + target);
     }
   } else {
     for (int i = 1; i <= digits.length(); i++) {
       double current = Double.parseDouble(digits.substring(0, i));
       String remaining = digits.substring(i);
       check(sum + previous, current, remaining, target, expr + " + " + current);
       check(sum, previous * current, remaining, target, expr + " * " + current);
       check(sum, previous / current, remaining, target, expr + " / " + current);
       check(sum + previous, -current, remaining, target, expr + " - " + current);
     }
   }
 }

 static void f(String digits, double target) {
   for (int i = 1; i <= digits.length(); i++) {
     String current = digits.substring(0, i);
     check(0, Double.parseDouble(current), digits.substring(i), target, current);
   }
 }

A: My Javascript implementation:
Will improve the code using web worker later on
// was not allowed to use eval , so this is my replacement for the eval function.
function evaluate(expr) {
  return new Function('return '+expr)();
 }
 function calc(expr,input,target) {
   if (input.length==1) {
    // I'm not allowed to use eval, so I will use my function evaluate
    //if (eval(expr+input)==target) console.log(expr+input+"="+target);
    if (evaluate(expr+input)==target) document.body.innerHTML+=expr+input+"="+target+"<br>";
   }
   else {
     for(var i=1;i<=input.length;i++) {
      var left=input.substring(0,i);
      var right=input.substring(i);
      ['+','-','*','/'].forEach(function(oper) {
         calc(expr+left+oper,right,target);
      },this);
     }
   }
 };
 function f(input,total) {
  calc("",input,total);
 }


text:
Q: Tkinter canvar scroll with mousewheel I am creating 4 frames and canvas with a for loop and assigning each of them a different scrollbar, i wanted to add the scroll with the mouse wheel and the code i found works fine, but only if the mouse cursor is not overing the labels or other widgeds that might be inside the frame inside the canvas. This is the error that i get AttributeError: 'Label' object has no attribute 'yview_scroll'
    f_s = ['s_one', 's_two', 's_three', 's_four']
    f_o = ['f_one', 'f_two', 'f_three', 'f_four']
    self.f_c = ['c_one', 'c_two', 'c_three', 'c_four']
    self.f_f = ['fs_one', 'fs_two', 'fs_three', 'fs_four']

    def set_mousewheel(widget, command):
        widget.bind("<Enter>", lambda _: widget.bind_all('<MouseWheel>', command))
        widget.bind("<Leave>", lambda _: widget.unbind_all('<MouseWheel>'))

    for f in range(4):
        f_o[f] = Frame(self.f_bot, width=250, height=580, bg=self.bg)
        f_o[f].grid(row=1, column=f)
        f_o[f].grid_propagate(False)
        self.f_c[f] = Canvas(f_o[f], width=229, height=580, bg=self.bg)
        self.f_c[f].pack(side=LEFT, fill=BOTH, expand=1)
        f_s[f] = Scrollbar(f_o[f], orient=VERTICAL, command=self.f_c[f].yview, bg=self.bg)
        f_s[f].pack(side=RIGHT, fill=Y)
        self.f_c[f].configure(yscrollcommand=f_s[f].set)
        self.f_c[f].bind('<Configure>', lambda event: event.widget.configure(scrollregion=event.widget.bbox('all')))
        self.f_f[f] = Frame(self.f_c[f], bg=self.bg)
        self.f_c[f].create_window((0, 0), window=self.f_f[f], anchor='nw')
        self.f_c[f].bind("<Enter>", lambda event: event.widget.bind_all('<MouseWheel>', lambda event: event.widget.yview_scroll(-1 * (event.delta // 120), "units")))
        self.f_c[f].bind("<Leave>", lambda event: event.widget.unbind_all('<MouseWheel>'))

the labels inside the final frames are created with a for loop as well

A: Found a solution following this thread: Tkinter Scrollbars with labels, canvas and frames
    def scroll(widget, event):
        widget.yview_scroll(int(-1 * (event.delta / 120)), "units")

    def final_scroll(widget, func, *_):
        widget.bind_all("<MouseWheel>", func)

    def stop_scroll(widget, *_):
        widget.unbind_all("<MouseWheel>")

    for f in range(4):
        f_o[f] = Frame(self.f_bot, width=250, height=bot_height, bg=self.bg)
        f_o[f].grid(row=1, column=f)
        f_o[f].grid_propagate(False)
        self.f_c[f] = Canvas(f_o[f], width=229, height=bot_height, bg=self.bg)
        self.f_c[f].pack(side=LEFT, fill=BOTH, expand=1)
        f_s[f] = Scrollbar(f_o[f], orient=VERTICAL, command=self.f_c[f].yview, bg=self.bg)
        f_s[f].pack(side=RIGHT, fill=Y)
        self.f_c[f].configure(yscrollcommand=f_s[f].set)
        self.f_c[f].bind('<Configure>', lambda event: event.widget.configure(scrollregion=event.widget.bbox('all')))
        self.f_f[f] = Frame(self.f_c[f], bg=self.bg)
        self.f_c[f].create_window((0, 0), window=self.f_f[f], anchor='nw')
        self.f_c[f].bind("<Enter>", lambda e: final_scroll(e.widget, lambda event: scroll(e.widget, event), e))
        self.f_c[f].bind("<Leave>", lambda e: stop_scroll(e.widget, e))


text:
Q: docker pull files from package.json I have simple node.app, with this package.json:
{
  "name": "docker_web_app",
  "version": "1.0.0",
  "description": "Node.js on Docker",
  "author": "xxxxx",
  "main": "server.js",
  "scripts": {
    "start": "node server.js"
  },
  "dependencies": {
    "express": "^4.16.1",
    "myuser-deploy": "git+ssh://git@github.com:myuser/deploy.git"
  }
}

Normally when I run "npm i", it installs all dependencies, and also the one form the github. I have SSH that I previously setup with the github. All works fine so far.
Now I added Docker support for my application, like this
Dockerfile:
FROM node:carbon

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./

RUN npm install
# If you are building your code for production
# RUN npm install --only=production

# Bundle app source
COPY . .

EXPOSE 8080
CMD [ "npm", "start" ]

docker-compose.yml:
version: "3"
services:
  test-service:
    build: .
    image: test-service
    container_name: test-service
    working_dir: /usr/src/app
    user: node
    restart: always
    ports:
      - '3001:3000'

When I run docker-compose up, it gives me this error:
> npm ERR! Error while executing: npm ERR! /usr/bin/git ls-remote -h -t
> ssh://git@github.com/myuser/deploy.git npm ERR!  npm ERR! Host key
> verification failed. npm ERR! fatal: Could not read from remote
> repository. npm ERR!  npm ERR! Please make sure you have the correct
> access rights npm ERR! and the repository exists. npm ERR!  npm ERR!
> exited with error code: 128
>
> npm ERR! A complete log of this run can be found in:

What can I do with the docker, so it uses my SSH keys?