Q:

How to optimized a big size jpeg on AIR IOS? (AS3)

I am developing a ipad game using AS3. Because of the detail of the game, I have to switch between around 5 backgrounds with the size of 4800x1800. Normally, I use the the switch function the turn off the visible of all background movieclips then turn on the one I need, but everytime, I function will work ok for the first time but crack on the second. I have traced and found it is really of the switch visible of the backgrounds. After that, I try to use bitmapdata and redraw every screen starts. But it even worse, crack for the first time I test. Seem it is not ok for the processor to handle such big bitmapdata.
Anyone have a good way to due with something like this?
P/s: My game run perfectly on PC, not a single error, it is just crack on the iPad and I have debugged that it stop while running the switch bg function.

A:

Are you subdividing the bitmapdata into smaller tiles for culling? If not, this is definitely the way to go. You want your engine to work like a puzzle, with only the pieces of the viewable puzzle put together. Ideally for a platform like iOS, you will want the sizes to be around 250x250 for optimal memory management (based on some of the tests I've done). IMHO, 4800x1800 is far too large of a dataset to handle as a single entity.
Basics of bitmap tiling:
http://as3adventure.blogspot.com/2011/06/bitmapfill-and-tiles-and-scrolling-it.html
Hope this helps!


Q:

Monotouch.Dialog changing x of elements frame gets repositioned after it goes off screen and back on

I'm using Monotouch.Dialog and need to reposition some EntryElements - they seem to drift right when inside a Section.
I am setting the frame to frame.X = frame.X - 5; to account for this. However if the cell goes off screen and then is scrolled back on the frame seems to be reset and the UI looks out of line.
What can I do to ensure the frame is never reset or at least set back to what it should be?
Here is the code - this is using the MvvmCross port of Monotouch.Dialog so GetCell is now GetCellImpl - it works in pretty much the same way - thing is dequeuereusablecell is called in it's base class (EntryElement) and I am modifying the cell after that point anyway... so should work no?:
public class MyEntryElement : EntryElement, IElementSizing
{
    public bool Disabled {
        get;
        set;
    }

    public MyClaimEntryElement()
        : base()
    {
    }

    public MyEntryElement(string caption)
        : base(caption)
    {
    }

    public MyEntryElement(string caption, string placeholder)
        : base(caption, placeholder)
    {
    }

    public MyEntryElement(string caption, string placeholder, string value)
        : base(caption, placeholder, value)
    {
    }

    public MyEntryElement(string caption, string placeholder, string value, bool isPassword)
        : base(caption, placeholder, value, isPassword)
    {
    }

    protected override UITableViewCell GetCellImpl(UITableView tv)
    {
        var cell = base.GetCellImpl(tv);
        cell.BackgroundColor = UIColor.Clear;
        UITextField uiTextField;

        if (cell.ContentView.Subviews.Length == 1)
        {
            uiTextField = ((UITextField)cell.ContentView.Subviews[0]);
        }
        else
        {
            uiTextField = ((UITextField)cell.ContentView.Subviews[1]);
        }

        if (cell.ContentView.Subviews.Length == 2) {
            var labelField = ((UILabel)cell.ContentView.Subviews [0]);
            labelField.TextColor = UIColor.White;
        }
        uiTextField.Enabled = Disabled;
        uiTextField.TextColor = UIColor.Black;
        uiTextField.Background = UiHelper.Text_Bubble;
        uiTextField.Enabled = !Disabled;
        var frame = uiTextField.Frame;
        frame.X = frame.X - 5;
        frame.Height = frame.Height + 10;
        uiTextField.Frame = frame;
        return cell;
    }

    private const float CellHeight = 40; //standard height. You can make it bigger or smaller, tho smaller means fingers miss easier.

    public float GetHeight(UITableView tableView, NSIndexPath indexPath)
    {
        return CellHeight;
    }
}

A:

Since UITableViewCell are re-used modifying it's Frame property based on it's previous value will lead you to problems.
E.g.

You show 12 cells on your table view. They are all visible and need to be created;
Your code subtract 5 from the X position. If the original X was 20, then it's now 15;
You scroll then some new cells are created (X will be 20 - 5 = 15 again) but, mostly, cells that are not visible anymore will be recycled;
Your code subtract again 5 from the X position. Any cell where X == 15 will now be at 10;

This is why setting Frame.X to a static field value (not based on the current X) works.
note: the above would be a lot easier to understand if you run this in the debugger and inspect the Frame for each call to GetCellImpl.


Q:

Apply CSS rule to elements matching one of multiple possible attribute values

I'm trying to apply css rule for multiple values of html attribute.
I've tried to apply it like described here, with no success:
input[name="a"][name="b"] {
    display: none;
}

<input name="a"> <!-- should be hidden -->
<input name="b"> <!-- should be hidden -->
<input name="c"> <!-- should not be hidden -->

The rule isn't applied at all.
However, when I use only one attribute selector, it works for that one matching element:
input[name="a"] {
    display: none;
}

<input name="a"> <!-- is hidden -->
<input name="b"> <!-- is not hidden -->

What am I doing wrong / is there any way to define it except duplicating rules?

A:

Put them separately and use a comma in between like below.
This code applies the css to input[name="a"] and/or input[name="b"].
Look at the docs to find out more.
Note: I used background-color: red; instead of display: none; so you can see the difference. To suit your problem, change it back to display: none;

input[name="a"], input[name="b"] {
    background-color: red;
}
<input name="a" />
<input name="b" />
<input name="c" />


Q:

Tricontourf plot with a hole in the middle.

I have some data defined on a regular Cartesian grids. I'd like to show only some of them with a condition based on the radius from the center. This will effectively create a ring-like structure with a hole in the center. As a result, I cannot use imshow. tricontourf or tripcolor are what I found to deal with it. My code looks something like this:
R = np.sqrt(x**2+y**2)
flag = (R<150)*(R>10)
plt.tricontourf(x[flag], y[flag], data[flag], 100)

where x and y are mesh grids where data defines. The problem here is that both tricontourf and tripcolor try to fill the middle of the ring, where I hope can be left blank.
To be more specific, the one in the left is similar to what I want but I can only get the one in the right with this piece of code shown above.

A:

The following shows how to mask some parts of the plot based on a condition. Using imshow is perfectly possible, and that's what the script below is doing.
The idea is to set all the unwanted parts of the plots to nan. To make the nan values disappear, we can set their alpha to 0, basically making the plot transparent at those points.
import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(-150, 150, 300)
y = np.linspace(-150, 150, 300)
X,Y = np.meshgrid(x,y)
data = np.exp(-(X/80.)**2-(Y/80.)**2)

R = np.sqrt(X**2+Y**2)
flag =np.logical_not( (R<110) * (R>10) )
data[flag] = np.nan

palette = plt.cm.jet
palette.set_bad(alpha = 0.0)

im = plt.imshow(data)

plt.colorbar(im)
plt.savefig(__file__+".png")
plt.show()

Just to add that also tricontourf can do what you're asking about. This example from the matplotlib gallery shows exactly what you're looking for, while this question on SO deals with a similar issue in a more comprehensive way.


Q:

print json data

This is jquery (ajax) -> php  response
  {"errorInfo":["23000",1062,"Duplicate entry 'blahblah' for key 'sn'"]}

how to print out, with jquery, only "Duplicate entry 'blahblah' for key 'sn'"
 success: function (html) {
   $("#notification").fadeIn("slow")
   .text(html); //Duplicate entry 'blahblah' for key 'sn'? html->errorInfo[2]?
  }

thank you
UPDATE:
It's Standard PDO Error function
     catch(PDOException $e) {
          print json_encode($e);
      }

that print out like this:
   {"errorInfo":["23000",1062,"Duplicate entry 'SDAAASSASADASADASDAS' for key 'sn'"]}

UPDATE:
I change it on other side, on source, I use
   print json_encode($e->errorInfo[2]); instead of print json_encode($e)

A:

The correct syntax is html.errorInfo[2] or html["errorInfo"][2] which is equivalent. When you can (as in this case) it's customary to use the first form.
While you are at it, why not also rename the parameter from html to something more appropriate, like result?


Q:

Store data not in database

I want to implement simple chat but store them only during server work. I don't want to store them in database, just like in List or Map. How to?

A:

This solution works for "Simple" chat as you explained.
There isn't much information on how you had built this before so I'm just going to explain how to have an Application scoped bean that can be injected into other beans to handle storing chat.
You can configure a Service to store this information.
ChatHistoryService.java
@Service
@Scope("application")//This is the key this will keep the chatHistory alive for the length of the running application(As long as you don't have multiple instances deployed(But as you said it's simple so it shouldn't)
public class ChatHistoryService {

    List<String> chatHistory = new LinkedList<>();//Use LinkedList to maintain order of input

    public void storeChatMessage(String chatString) {
        chatHistory.add(chatString);
    }

    public List<String> getChatHistory() {
        //I would highly suggest creating a defensive copy of the chat here so it can't be modified.
        return Collections.unmodifiableList(chatHistory);
    }

}

YourChatController.java
@Controller
public class YourChatController {

    @Autowired
    ChatHistoryService historyService;

    ...I'm assuming you already have chat logic but you aren't storing the chat here is where that would go

    ...When chat comes in call historyService.storeChatMessage(chatMessage);

    ...When you want your chat call historyService.getChatHistory();

}

Once again keep in mind that this really only works for a simple application. If it's distributed there will be different chat histories per instance of the application at that point you could look into a distributed cache.
In any case don't go beyond simple with this implementation.
If you look here it will give you an idea of several caches that work with spring boot.

https://github.com/spring-projects/spring-boot/tree/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/cache


Q:

Nginx unable to server static and media images

I have a django app on DigitalOcean droplet running using gunicorn and nginx. The site is working but the static files are giveing 404. Below is my '/etc/nginx/sites-available/django-project' file:
server {

        #listen 80 default_server;
        #listen [::]:80 default_server ipv6only=on;

        server_name aakar.in;

        root /usr/share/nginx/html;
        index index.html index.htm;

        #access_log off;

        client_max_body_size 4G;
        #server_name _;

        keepalive_timeout 5;

        location /media  {
           alias /home/django/django_project/django_project/media;
        }

        location /static/ {
            alias /home/django/django_project/django_project/static;
        }

        location / {

                proxy_pass http://127.0.0.1:9000;
                proxy_redirect off;
                proxy_set_header X-Forwarded-Host $server_name;
                proxy_set_header X-Real-IP $remote_addr;
                proxy_set_header Host $http_host;
                add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM N$
        }
    }

A:

Correction made:
location /static/ {
            alias /home/django/django_project/django_project/static/;
        }

Working now.


Q:

Use JWT Auth for authenticate against LDAP service

I'm creating a web services that use JWT Auth. I'm using django-rest-framework-jwt
 for that. I want my users could authenticate using their ldap accounts. I have found that there's a Django authentication backend that authenticates against an LDAP service. The function that does the authentication in django-rest-framework-jwt is coded like this :
def authenticate_credentials(self, payload):
    try:
        user_id = payload.get('user_id')

        if user_id:
            user = User.objects.get(pk=user_id, is_active=True)
        else:
            msg = 'Invalid payload'
            raise exceptions.AuthenticationFailed(msg)
    except User.DoesNotExist:
        msg = 'Invalid signature'
        raise exceptions.AuthenticationFailed(msg)

    return user

The function looks in the User model to authenticate the user. I think that even if I setup the ldap backend, it will never work. Am I right? If yes what can I change to be able to use JWT Auth and be able to authenticate against LDAP service?

A:

Every Django authentication backend has a very simple API. Normally, they're installed in the AUTHENTICATION_BACKENDS setting, but there's nothing stopping you from using them manually:
from django_auth_ldap.backend import LDAPBackend

user = LDAPBackend().authenticate(username, password)

This is assuming that users are authenticating with a username and password. If you need to authenticate against LDAP by some other means, then you're probably on your own.
One thing to keep in mind is that every authentication backend will create/return the same User model objects. So assuming a user has been authenticated once, your user_id-based code above should be compatible with any underlying backend.


Q:

A Graph Map of Math.SE

I've just made a map of tags for Math.SE. (And to some degree - a greatly simplified map of mathematics.)
In short: tag size is related to tag popularity (caveat: see below) and edges are related to tag co-occurrences in questions (or more precisely: the observed/expected ratio, see About joint probability divided by the product of the probabilities). Colors are to distinguish graph communities, as detected by this algorithm.
For me it looks as a "snapshot" of topics and scope of this SE site. So if you want to use it in any way to promote Math.SE - feel free!
Also, if you have comments how to improve its usefulness or niceness to our community, I would appreciate them (but bear in mind that I have no color esthetics).

Caveat: I plotted all of 64 most popular tags that have at least one link, that is, 63 tags. As I see now, homework (the most popular tag) went out. Lousily speaking, it means that this tag doesn't co-occur with other tags "much more than on random". Do you think that I should attach it as a separate node? (Alternatively, I can lower the threshold, but then (almost) everything is going to be linked with almost everything, hardly making in any clearer.)
Edit:
I added one more visualization, this time a bit less dense. Based on Gephi - OpenOrd:

Links:

An entry for StackExchange vis competition at Kaggle (please vote if you like it :), it ends on the 3th of Nov 2012)
Recipe, code and images at GitHub (e.g. tweak the plot to your taste; feel invited to co-develop)

A:

I played with the layout settings and made this version:

I feel like with this layout you can more clearly see the shape of the connectivity between tags. For example, the arrangement seems to be stretched out along a discrete/continuous spectrum. But on the discrete side, there isn't a lot of overlap between the algebraists and the computer-sciencey types.


Q:

How to remove SASS debug from Brunch.io compiled CSS?

When I compile my SCSS code in to CSS using Brunch.io it adds the following to the CSS.
@media -sass-debug-info{filename{font-family:file\:[*FILE PATH REMOVED*]/reset\.scss}line{font-family:\000031}}

I have tried adding a "quiet" flag to the Brunch config file (as suggested here: https://github.com/brunch/sass-brunch) but this doesn't seem to make a difference.
How can I stop the compiler from adding these lines?

A:

Try to disable :debug_info to false. Like this in config.rb:
debug_info = false

Or in brunch config file you should edit these lines:
config =
   plugins:
     sass:
         debug: 'comments'


Q:

Scrollbar captures wheel event by focus?

I've made a scrollable image viewer based on this example.
I use QLabel, QImage and QScrollArea.
I would like to zoom in and out using QWheelEvent.
My problem is, the event is only emitted if the scrollbar is at the top or bottom, otherwise it just scrolls the image.
Any ideas?
.h
#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QLabel>
#include <QHBoxLayout>
#include <QScrollArea>
#include <QWheelEvent>
#include <QScrollBar>

class MyWidget : public QWidget
{
    Q_OBJECT

    QLabel* _label;
    QHBoxLayout* _layout;
    QScrollArea* _scrollArea;

    double _factor;
public:
    MyWidget(QWidget *parent = 0);
    ~MyWidget();
protected:
    void wheelEvent(QWheelEvent* e);
};

#endif // MYWIDGET_H

.cpp
#include "mywidget.h"

MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
{
    QImage im("D:\\parrot_1366.jpg");

    _label = new QLabel;
    _label->setPixmap(QPixmap::fromImage(im));
    _label->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    _label->setScaledContents(true);

    _layout = new QHBoxLayout;
    _scrollArea = new QScrollArea;
    _scrollArea->setWidget(_label);

    _layout->addWidget(_scrollArea);
    setLayout(_layout);

    _factor = 1.0;
}

MyWidget::~MyWidget()
{

}

void MyWidget::wheelEvent(QWheelEvent *e)
{
    QScrollBar* scrollbarHor = _scrollArea->horizontalScrollBar();
    QScrollBar* scrollbarVer = _scrollArea->verticalScrollBar();

    QPoint degree = e->angleDelta() / 8;

    double f;
    if (degree.y() < 0)
    {
        _factor *= 0.8;
        f = 0.8;
    }
    else
    {
        _factor *= 1.25;
        f = 1.25;
    }

    _label->resize(_factor * _label->pixmap()->size());

    scrollbarHor->setValue(int(f * scrollbarHor->value() + ((f - 1) * scrollbarHor->pageStep() / 2)));
    scrollbarVer->setValue(int(f * scrollbarVer->value() + ((f - 1) * scrollbarVer->pageStep() / 2)));

    e->accept();
}

A:

I had to define an event filter in MyWidget:
bool MyWidget::eventFilter(QObject *o, QEvent *e)
{
    if (e->type() == QEvent::Wheel)
    {
        QWheelEvent* we = static_cast<QWheelEvent*>(e);

        if (o == _scrollArea->verticalScrollBar())
            wheelEvent(we);
        else
            return false;
    }
}

And install the filter on the vertical scrollbar:
_scrollArea->verticalScrollBar()->installEventFilter(this);


Q:

Error imprimiento con printf

Compañeros buenos días, si me pueden ayudar por favor. Todos los printf me marca como error, no se cual es la razon??? Este programa me servira para saber cuantos elementos de una lista de 5 números enteros son mayores que el promedio.
import java.util.Scanner;

public class Main {
  public static void main(String[] args) {
    int[] arr = new int[5];
    int suma;
    double prom;
    int mayorProm;
    Scanner l = new Scanner(System.in);
    for (int i = 0; i < arr.length; i++) {
      System.out.printf("Ingrese elemento[%d]: ", i);
      arr[i] = l.nextInt();
    }

    suma = sumar(arr);
    System.out.printf("Suma =  % d\n", suma);

    prom = suma / (double)arr.length;
    System.out.printf("Promedio = %f\n", prom);

    mayorProm = contarMayorProm(prom, arr);
    System.out.printf("%d elementos son mayores al promedio\n", mayorProm);

  }

  public static int sumar(int[] a) {
    int resultado = 0;

    for (int i = 0; i < a.length; i++) {
      resultado = resultado + a[i];
    }
    return resultado;
  }

  public static int contarMayorProm(double prom, int[]a) {
    int contador = 0;

    for(int i = 0; i < a.length; i ++) {
      if(a[i] > prom) {
        contador = contador + 1;
      }
    }
    return contador;
  }
}

A:

De acuerdo a esta respuesta aceptada, el problema estaría en la configuración de Eclipse que usas para compilar tu código.
Project > Properties > Java Compiler
Si Enable project specific settings no está habilitado, use la opción Configure Workspace Settings en ese panel para revisar la configuración global de Compiler compliance level.

Si no está al menos en 1.5 o superior, así uses JDK8, la compilación arrojará ese error por como estaba implementada PrintStream en 1.4 y anteriores.


Q:

jQuery invalid slideUp, slideDown effect

I have an problem with my small jQuery menu.
Here`s a live example:
http://jsfiddle.net/jvalousek/NthrX/
As you can see there, I need to show a specific part of code over hover my first visible menu. It seems that everything works fine, but if you try it, you can see some tricky effect which doesn't seems nice. It randomly generates slideUp, or slideDown...
Can anyone help?

A:

You're sliding them all up! Target only the visible ones :
$('.selector').mouseenter(function() {
    var name = this.id + 'Text';
    $('.careerHint:visible').slideUp(function () {
        $("#" + name).slideDown("fast");
    });
});

FIDDLE


Q:

When do we double the consonant before '-ing' affix?

My son is learning how to spell. He is doing a good job listening to sounds and working out spelling that way (which doesn't work for many words, but at least a lot of common ones), but although he's gotten the -ing chunk, he frequently misses doubling letters in these words.
Is there a guideline for when the end consonant is doubled? He's working on these sorts of words:

riding
sitting
skating
writing
getting

A:

Are they still teaching the old 'long/short' vowels? If so, here's the rule:

If the syllable before the /-ing/ is pronounced with a 'long' vowel, leave the final consonant single (and delete any final silent /e/)
  If it's pronounced with a 'short' vowel, double the final consonant.

It may help make this clearer if you explain that a vowel before a doubled consonant is (almost) always short. Then write the /-ing/ forms out 'wrong' and invite your son to pronounce them the way they look:
ride   ridding
sit    siting
skate  skatting
write  writting
get    geting

As Renan points out, it gets more complicated when the final syllable of the base form is unstressed; but it looks like your son hasn't gotten that far yet.

A:

For verbs ending in 'el' such as travel, cancel, chisel, excel, fuel, funnel, grovel, label, marvel etc, remember that British English requires a double 'l' as in 'travelling', whereas American English does not.

A:

From here, you double the consonant when:

one-syllable words: if the word ends with a consonant-vowel-consonant pattern (sit -> sitting, get -> getting).
two-syllable words: if the stress is on the second syllable (begin -> beginning).

For your other words (ride -> riding, skate -> skating, write -> writing) the e is dropped and replaced by ing.


Q:

macOS packet filter (port forwarding)

I am trying to redirect the outbound traffic to destination port 80 to the local proxy port 127.0.0.1:8080 without success
/etc/pf.anchors/com.forwarding
rdr pass inet proto tcp from any to any port 80 -> 127.0.0.1 port 8080

/etc/pf.conf
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
rdr-anchor "myproxy"
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"
load anchor "myproxy" from "/etc/pf.anchors/com.forwarding"

Then:
sudo sysctl net.inet.ip.forwarding=1
sudo pfctl -ef /etc/pf.conf

The local traffic 127.0.0.1:80 is redirected to 127.0.0.1:8080, but not the external, the one towards internet.

A:

You can only redirect incoming traffic. Any outgoing traffic to port 80 isn't affected by your rdr rule.
To redirect outgoing traffic to port 80 you have to re-route it first to lo0 then redirect it to the proxy port:
The order in the config file is necessarily rdr incomming packets, then filter packets (like pass), but chronologically the 2nd rule will hit first (on en0), which will then activate the first rule (on lo0).
# Step "2". redirect those same packets that were routed to lo0 below
rdr pass log on lo0 proto tcp from any to any port 80 -> 127.0.0.1 port 8080
# Step "1". Route new IPv4 TCP connections leaving en0 to lo0
pass out on en0 route-to lo0 proto tcp from en0 to any port 80 keep state

in pf.conf this would look like this:
...
scrub-anchor "com.apple/*"
nat-anchor "com.apple/*"
rdr-anchor "com.apple/*"
rdr pass log on lo0 proto tcp from any to any port 80 -> 127.0.0.1 port 8080
dummynet-anchor "com.apple/*"
anchor "com.apple/*"
load anchor "com.apple" from "/etc/pf.anchors/com.apple"
pass out on en0 route-to lo0 proto tcp from en0 to any port 80 keep state

In the above example I assume en0 is your only outbound en interface.
Unload your current pf.conf and stop pf: sudo pfctl -d. Then add the two additional lines above. After modifying pf.conf check the syntax of the file with sudo pfctl -vnf /etc/pf.conf which should result in the following output:
pfctl: Use of -f option, could result in flushing of rules
present in the main ruleset added by the system at startup.
See /etc/pf.conf for further details.

scrub-anchor "/*" all fragment reassemble
nat-anchor "/*" all
rdr-anchor "/*" all
rdr pass log on lo0 proto tcp from any to any port 80 -> 127.0.0.1 port 8080
anchor "/*" all
pass out on en0 route-to lo0 proto tcp from en0 to any port 80 flags S/SA keep state
dummynet-anchor "/*" all

and if successful load it with sudo pfctl -e -f /etc/pf.conf.

A proper system and proxy configuration (and well-behaving apps) don't require such pf rules!


Q:

Check the position inside the textbox

Is there any way to check the position inside the textbox by using javascript, or any kinds of javascript framework? Say, the figure 1 is at position 2 and the figure 3 is at position 3.

Figure. 1.

Figure. 2.

A:

Below are the 2 helpful methods:
function doGetCaretPosition (ctrl) {

    var CaretPos = 0;
    // IE Support
    if (document.selection) {

        ctrl.focus ();
        var Sel = document.selection.createRange ();

        Sel.moveStart ('character', -ctrl.value.length);

        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;

    return (CaretPos);

}

function setCaretPosition(ctrl, pos)
{

    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}


Q:

Is it possible to get a reference to MyList if the listname is a string "myList"

I have some lists of the type ObservableCollection<SampleObject>
They all end with a letter of the alphabet: lista, listb, listc...
Now i want to make a loop which runs through the alphabet and at every letter it should add an item to the current list.
Example:
for (char i = 'a'; i < 'z'; i++)
{
    string name = "list" + i;
    name.Add(.....);
}

The "name" in this example should be the list where i want to add an item.

A:

You want a Dictionary<char, ObservableCollection<SampleObject>>, which will have a different collection for each char.


Q:

How can I use nested quotes when calling a PowerShell script within a VBScript file?

I'm a VBScript and PowerShell newbie. I have a PowerShell script that runs correctly when I call it from the command line. However when I try and call it from VBScript, it runs but does nothing.
The command I use on the CLI that works is
powershell.exe -nop -exec bypass -noni -command "& { . C:\<censored path>\testscript1.ps1; Get-Test }"

This works. When I run the following vbscript code, I get no results
Set objShell = CreateObject("Wscript.shell")
objShell.run("powershell.exe -nop -exec bypass -noni -command &""& { . C:\<censored path>\testscript1.ps1; Get-Test }" &"")

What am I doing wrong?
PS: After trimming down my command to:
objShell.run("powershell.exe -nop -exec bypass -noni -command "& { . C:\<censored path>\testscript1.ps1; Get-Test }" ")

I get a Code 800A0408 - Invalid Character error for the opening brace bracket. I have tried escaping both brackets, but I still get the same error.

A:

You can try something like that :
PSCommand = "powershell.exe -nop -exec bypass -noni -command" & DblQuote("& { . C:\<censored path>\testscript1.ps1; Get-Test }")&""
MsgBox PSCommand
set objShell = CreateObject("wscript.shell")
objShell.Run PSCommand
'****************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'****************************************************************


Q:

Can't format datetime in carbon

When I try to format my $date to d/m/Y it's work fine
$date = '20/4/2015';
Carbon::createFromFormat('d/m/Y', $date)

But when I try to format my $date to d/M/Y
$date = '20/4/2015';
Carbon::createFromFormat('d/M/Y', $date)

I got an error like the following,

The separation symbol could not be found Trailing data

What does wrong in my code?

A:

M means textual representation of month. 4 cannot be parset into month and it fails even though with strange message. Try this and it works
    $date = '20/Jan/2015';
    $carbDate=Carbon::createFromFormat('d/M/Y', $date);
    dd($carbDate);

Outputs
Carbon {#260 ▼
  +"date": "2015-01-20 10:01:01"
  +"timezone_type": 3
  +"timezone": "UTC"
}


Q:

How to use GetChildAtPoint with PointF

Im trying to write a basic drawing app with some formulas that requires me to keep my points precise.
all is working well but one part that will allow me to proceed with this program.
I need to use the Control.GetChildAtPoint Method to see if there is an object at a certain point of the line but my points is all in pointF (float).
here is a short piece of the code that should make sense.
    if (poscount > 15) {
            //to see if point is close to an object
            if (this.GetChildAtPoint(point2) != null) {
                label1.Text = "I found an object";
            } else label1.Text = " no object found";

        }

Sorry for the stupid example but at the point2  (which is apointF) it gives an error that I cant convert from afloattoSystem.Drawing.Point.
I cant find a way to convert it and keep the accuracy.
Is there a way I can useGetChildAtPointwith afloat`?

A:

The argument could be converted as follows.
if (poscount > 15)
{
    // to see if point is close to an object
    Point iPoint = new Point((int)point2.X, (int)point2.Y);
    if (this.GetChildAtPoint(iPoint) != null)
    {
        label1.Text = "I found an object";
    }
    else
    {
        label1.Text = " no object found";
    }
}


Q:

Смена вкладки при разных utm_term

Выручайте пожалуйста... Есть три вкладки. По умолчанию активна первая. Как можно сделать, чтобы при определенной utm метке, были открыты разные вкладки. Например, если utm_term=tab3, чтобы активной была вкладка tab3. Кто разбирается подскажите пожалуйста. Буду очень признательным!

        Вкладка 1

        Вкладка 2

        Вкладка 3

        Контент вкладки 1

        Контент вкладки 2

        Контент вкладки 3

A:

Сначала гуглим как получить URL-параметр в js.
Затем гуглим Bootstrap Tabs

function getParameter(parameterName) {
  var result = null,
    tmp = [];
  location.search.substr(1).split("&").forEach(item => {
    tmp = item.split("=");
    if (tmp[0] === parameterName) result = decodeURIComponent(tmp[1]);
  });
  return result;
}

// const tabName = getParameter("utm_term");
const tabName = "tab2"; // Для теста
if (tabName) {
  $(`a[data-toggle='tab'][href^='#${tabName}']`).tab('show');
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">

    Вкладка 1

    Вкладка 2

    Вкладка 3

    Контент вкладки 1

    Контент вкладки 2

    Контент вкладки 3


Q:

No package community-mysql-devel available

I'm trying to get this package because I need it to build software on CentOS 6, but I'm getting this error:
No package community-mysql-devel available

I'm logged in as root, using yum.
Could it be because I installed this from a non-net install CD?
I had the same problem with Scientific Linux 6 (non-net CD)

A:

The package name should be mysql-devel.
And yes, it is the development headers of the community edition of MySQL database.


Q:

Compute integral symbolically or numerically

I want to compute the integral of the following integrand
((0.000245587 + 0.0000651908 I) E^(-I kx)
   kx ky (kz^2 - 4 \[Pi]^2))/((kx^2 + ky^2) kz) - ((4.00033*10^-17 -
    3.51178*10^-18 I) E^(-I kx) (kx^3 kz + kx ky^2 kz + kx^2 kz^2 +
    4 ky^2 \[Pi]^2))/((kx^2 + ky^2) kz)

Where $k = 2 \pi$.
For this I have the following code:
SetAttributes[withTransforms, HoldAll];
withTransforms[code_] :=
 Block[{kx = k*Sin[a]*Cos[b],
   ky = k*Sin[a]*Sin[b], kz = k*Cos[a]},
  code]

And the symbolic integration:
IntoS[int_] :=
 withTransforms[
  Integrate[
   int*k^2*Sin[a]*Cos[a], {a, 0, Pi/4}, {b, 0, 2*Pi}]]

And finally, the numerical:
IntoN[int_] :=
 withTransforms[
  NIntegrate[
   int*k^2*Sin[a]*Cos[a], {a, 0, Pi/4}, {b, 0, 2*Pi}]]

Now, IntoS, the symbolic integration doesn't give a result within 5 minutes (after which I have aborted the evaluation) on my core 2 duo. I need to compute many of these integrals for a plot and if it takes several minutes already to evaluate one point that won't be very useful.
Furthermore, IntoN throws

NIntegrate::slwcon: Numerical integration converging too slowly;
  suspect one of the following: singularity, value of the integration is
  0, highly oscillatory integrand, or WorkingPrecision too small.

at me. How do I integrate this function?
Edit Scaling coefficients does not really work. I always get that some coefficients are quite large and others very small. This way, the integration never works. I can delete the "small" terms manually but that it not really automatic.
Edit 2: Mathematica is unable to compute the following integral numerically:
(E^(I kx) kx ky (-1 + kz^2))/(Sqrt[2] (kx^2 + ky^2) kz)

Symbolically this integral is $0$. However, I do need the numerical computation as the symbolic computation can take quite long and I need to plot the end-result. This is a special case of the term
(E^(I (kx x + ky y + kz z)) kx ky (-1 + kz^2))/(Sqrt[2] (kx^2 +
   ky^2) kz)

And I want to plot in $x$ (with $y, z = 0$ for example) and this integral is sometimes impossible to compute symbolically.
Edit 3: I have "fixed" it by writing my own numerical method:
Trapezoidal2D[f_, {x_, a0_, b0_}, {y_, c0_, d0_}, m0_] :=

  Module[{h = (b0 - a0)/m0, k = (d0 - c0)/m0, a = N[a0], b = N[b0],
    c = N[c0], d = N[d0], i, j, m = m0, X, Y},
   Subscript[X, k_] = a + i h;
   Subscript[Y, j_] = c + j k;
   Return[
    1/4 h k (Function[{x, y}, f][a, c] + Function[{x, y}, f][b, d] +
       Function[{x, y}, f][a, d] + Function[{x, y}, f][b, d] +
       2 Sum[Function[{x, y}, f][Subscript[X, i], c], {i, 1,
          m - 1}] +
       2 Sum[Function[{x, y}, f][Subscript[X, i], d], {i, 1,
          m - 1}] +
       2 Sum[Function[{x, y}, f][a, Subscript[Y, j]], {j, 1,
          m - 1}] +
       2 Sum[Function[{x, y}, f][b, Subscript[Y, j]], {j, 1,
          m - 1}] +
       4 Sum[Function[{x, y}, f][Subscript[X, i], Subscript[Y,
          j]], {i, 1, m - 1}, {j, 1, m - 1}])];];

A:

For the symbolic attempt I'd first rationalize to get exact input.
e1 = ((0.000245587 + 0.0000651908 I) E^(-I kx) kx ky (kz^2 -
        4 \[Pi]^2))/((kx^2 + ky^2) kz) - ((4.00033*10^-17 -
        3.51178*10^-18 I) E^(-I kx) (kx^3 kz + kx ky^2 kz +
        kx^2 kz^2 + 4 ky^2 \[Pi]^2))/((kx^2 + ky^2) kz);
e2 = Rationalize[e1, 0]

Out[5]= ((245587/1000000000 + (162977 I)/2500000000) E^(-I kx)
   kx ky (kz^2 - 4 \[Pi]^2))/((kx^2 + ky^2) kz) - (1/((kx^2 +
    ky^2) kz))(1/24997937670142213 - I/
    284755878785117533) E^(-I kx) (kx^3 kz + kx ky^2 kz + kx^2 kz^2 +
    4 ky^2 \[Pi]^2)

I believe this does the transformation you do in a different way.
e3 =
 e2*k^2*Sin[a]*Cos[a] /. {kx -> k*Sin[a]*Cos[b],
    ky -> k*Sin[a]*Sin[b], kz -> k*Cos[a]} /. k -> 2*Pi

With this, we can now do as below.
In[26]:= Timing[ii = Integrate[e3, {a, 0, Pi/4}, {b, 0, 2*Pi}]]

Out[26]= {158.87,
 Integrate[(8/284755878785117533 + (8*I)/24997937670142213)*Pi^3*
       (-2*I*Pi*BesselJ[2, 2*Pi*Sin[a]]*Cos[a]^2*Sin[a] +

     BesselJ[1, 2*Pi*Sin[a]]*(I*(1 + Cos[a]^2) + Pi*Sin[a]*Sin[2*a])),
     {a, 0, Pi/4}]}

In[28]:= N[ii]

Out[28]= 7.85307*10^-16 + 1.11299*10^-15 I

Whether this is accurate will depend on cancellation error and other vagaries of the quadrature.

A:

If I define
expr = Function[{a, b},
   Evaluate@withTransforms[intgnd]];

(with intgnd the expression given at the top of the question),
I get tiny differences between points symmetric around $b=\pi$:
ListLogPlot[Abs[expr[.3, #] + expr[.3, 2 Pi - #] & /@ Range[0, 2 Pi, .01]]]

so even if your coefficients are accurate, you will have lots of trouble obtaining good results unless you greatly increase working precision (and force the precision of your input numbers to be higher than machine precision).
If you can, it's probably better to rescale your variables at some earlier point to avoid such extreme numbers.
One may also see what is going on as follows:
t={
 NIntegrate[expr[a, b], {a, 0, Pi/4}, {b, 0, Pi}],
 NIntegrate[expr[a, b], {a, 0, Pi/4}, {b, Pi, 2 Pi}]
 }

(*{-0.0000297965 + 0.000112249 I, 0.0000297965- 0.000112249 I}*)

Plus@@t
(*-2.23895*10^-16 + 1.1891*10^-16 I*)

ie, the two halves are very close to being equal in magnitude.


Q:

Write binary data in QT '\n' 0x10->0x0d,0x010

I work on project that involved writing binary data, I use QString for storing line and then save it on hard by Qfile
 data.append(QChar(10));

and I set encoding to "ISO-8859-1", anyway when the data equal to 10 I as showed above, the saved data is 0x0d,0x0a I find the problem source ,10='\n' and Qt change it to '\n\r' so it happened.
How can I fix it?

A:

I found the reason, because the QFile object that I had created is in Text mode so when QFile want to write file it changes /n to /r/n the code below is the previous code that have problem in binary because of existence of QIODevice::Text
QFile myfile;
myfile.setFileName("build/Data.bin");
if(!myfile.open(QIODevice::WriteOnly|QIODevice::Text))
    return;

for binary mode simply we can omite QIODevice::Text so the second line change to
if(!myfile.open(QIODevice::WriteOnly))

at first I think this is the Qt's bug, and try to use ofstream to write file, the same thing happened with ofstream, and finally writing binary code with ofstream is showed below
the point is std::ios_base::binary
ofstream file;
file.open ("example.txt", std::ios_base::out | std::ios_base::binary);
file << (byte)10;
file.close();


Q:

What governs how fast grandmas make cookies?

They were making 10 each time, now it's 14. What governs the rate?

A:

This is the relevant code for the Grandmas in Cookie Clicker Classic:
var grandmaGain=Math.ceil(4+(Factories?1:0)+(Mines?2:0)+(Shipments?3:0)+(Labs?4:0)+(Portals?(Pledge?5+Portals*0.5:5):0)+(Times?6:0));
cps+=Grandmas*grandmaGain/5;

That confirms Sconibulus' idea that it might be related to the amount of available items. That said:

There is a base of 4 cookies.
If you have a Factory, it adds another 1 cookie.
If you have a Mine, it adds another 2 cookies.
If you have a Shipment, it adds another 3 cookies.
If you have an Alchemy Lab, it adds another 4 cookies.
If you have a Portal, the formula gets a bit complicated (See below).
If you have a Time machine, it adds another 6 cookies.

The Portal itself adds 5 cookies.
If you have a Pledge on top of that, you gain an additional .5 per portal.
The Grandmas produce the applicable sum of cookies every five seconds.
The formula changed completely in 1.0.

A:

In 1.0 and later, it's largely through doubling upgrades.
The base rate is 0.5 CpS, or 0.8 after you buy Forwards from grandma.
This increases by 0.02 for each grandma after buying One mind, an additional 0.02 for each grandma after buying Communal brainsweep, and 0.05 for each portal after buying Elder Pact.
The rest of the grandma upgrades make grandmas 2^18 = 262,144 times as efficient.

Six upgrades that double the rate are unlocked after having hired specific numbers of grandmas: 1, 5, 10, 50, 100, and 200.
The nine grandma costumes are unlocked for having at least 15 of each building (Farm through Prism). These are also doubling upgrades.
Buying seven grandma costumes unlocks Bingo center (quadruple); waiting after that unlocks Ritual rolling pins (double).
During Christmas, the "festive hat" upgrade chain will eventually unlock Naughty list (double).

Once you enter the Grandmapocalypse by buying One mind, part of the grandmas' production actually becomes quadratic (O(n^2)) because the base rate for each grandma includes something multiplied by the number of grandmas, and that in turn is multiplied by the number of grandmas. With more than 40 grandmas, the majority of your production is from quadratic effects.
As with every other source of cookie production, this is multiplied by your cookie production multiplier (mostly flavored cookies and heavenly chips), egg multiplier (Easter-related), covenant multiplier (95% if in effect), frenzy multiplier (usually 100%, occasionally 700%, 50%, or 66600%), and wrinkler multiplier (100% to 600%).
Sources: "Grandma", "Upgrade", and "CpS" pages on Cookie Clicker Wiki


Q:

Why does it make a difference where I include the jQuery script file?

On my master page (for all pages in my site) I have a ToolkitScriptManager.
On my content page, there are a series of hyperlinks and divs for collapsible functionality.
The code to show/hide the panels work like the following:
$(document).ready(function() {
// Hookup event handlers and execute HTML DOM-related code
$('#nameHyperLink').click(function() {

        var div = $('#nameDiv');
        var link = $('#nameHyperLink');
        if (div.css('display') == 'none') {
            link.text('Hide Data');
            div.show('100');
        }
        else {
            link.text('Show Data');
            div.hide('100');
        }

    });
});

If I include a ScriptReference to the jQuery 1.4.2 file in the toolkitscriptmanager, the javascript code is executed incorrectly on the page (only the text for the hyperlink is changed, the div is not actually shown.)  However, if I don't include the jQuery file in the ToolkitScriptManager and instead include it in the content page, it works correctly.
I'm a Javascript/jQuery newbie, and this makes no sense at all.  What's going on here?

A:

Positioning of the script include is important for the jQuery ref. If you look at your generated source I would bet the  tag is below the script function(). You should make sure that the jQuery reference comes as early as you can get it in the page source.
Try moving the jQuery library reference into the head of your master page, that should work. Otherwise post up some source!


Q:

Как сделать исчезающую FAB?

Имеется ListView и FAB. Можно ли сделать так, чтобы при прокрутке списка вниз FAB исчезала, а при прокрутке вверх появлялась? Только не предлагайте использовать RecyclerView, мне нужен вариант с имеющимися элементами.

A:

Используйте CoordinatorLayout, это самый лучший способ по данной задаче
Вот вам пример где Fab скрывается по скроллу ListView


Q:

Swagger NodeJS File Upload

Solution:
Had an error in my swagger contract, correct definition of a fileupload should look like this:
  parameters:
   - in: formData
     name: file
     description: The file to upload
     required: true
     type: file

Thank you for the hint!
Original question:
I have a problem regarding my Swagger/NodeJS API.
I want to receive fileuploads and store the retrieved file with another cloud service.
Sadly, the file does not arrive in the format I expect it to be.
This is what I receive in req.swagger.params.image.value via postman:
    ------WebKitFormBoundaryZCFoUQnf4lHIhzjj
Content-Disposition: form-data; name="image"; filename="r14kvzvmsh3xnuyl2vq8.png"
Content-Type: image/png

�PNG

IHD�o&�IDA�c���?� � ��1��X��5�юIEND�B`�
------WebKitFormBoundaryZCFoUQnf4lHIhzjj--

The tested image as a PNG or as base64:
iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==

My cloudprovider for the images is cloudinary, so when I use the following code it is successfully saved to the service.
cloudinary.v2.uploader.upload("data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==")

When I use
new Buffer(req.swagger.params.image.value, 'binary').toString('base64');

I expected the file to be converted to base64, but I think the part in the req defining the Content-Type etc. is also converted.
Does anybody know a way to work with fileuploads and swagger, so I can upload the image successfully to cloudinary?
Regex seems very "hacky"...
This is the imageupload part in my swagger contract:
/imageUpload:
x-swagger-router-controller: image_upload
post:
  description: Endpoint to upload the image file. The image has to be uploaded before the shipment is created, a response will be the image ID that has to be supplied to the shipment. If the image ID is not valid, i.e. not known to this api, the shipment can not be created
  operationId: storeImage
  consumes:
    - multipart/form-data
    - application/x-www-form-urlencoded
    - binary
  parameters:
   - in: body
     name: image
     description: The file to upload
     required: true
     schema:
        type: string
        format: file
  responses:
    "200":
      description: Success
      schema:
        # a pointer to a definition
        $ref: "#/definitions/ImageResponse"
    # responses may fall through to errors
    default:
      description: Error
      schema:
        $ref: "#/definitions/ErrorResponse"

A:

Looks to me like you're uploading the raw binary image instead of the base64 encoded image. I'd do away with all the binary stuff, define only base64 in your swagger doc, and ensure the Buffer->base64 encoding is working as expected (do some console logging).


Q:

PowerShell for developers

I understand why IT administrators like to use PowerShell, but is there a reason why developers should use it daily?
Are there any scripts you run in PowerShell quite often to make your life easier?

A:

For everything you were doing via command scripts/batches, you can now use PowerShell and most of the time it will be much easier because of the cmdlets provided.
For example, if you're a SharePoint developer, you'll really like/should use it for your daily development (to replace stsadm, etc.).
Next to that, you can use PowerShell to download podcasts and videos (downloading MIX11 videos as we speak), converting videos, parsing CSV files, ...
Use it in every scenario where you need some quick scripting. I'd take a quick PowerShell script to parse a CSV file over writing a full .NET application to do the same.

A:

I wrote a blog post about some areas I find useful: How PowerShell can help programmers. You might find some tips there.

A:

PowerShell Tips & Tricks for Developers


Q:

Err.description slow

The program takes 1-2 seconds on my pc
The slowness happens on the line
Debug.Print Err.Description
If I replace it with Err.number, it takes 0s.
The problem consist, if I changed the code to display a Type Mismatch error message
I'm using Excel 2007, 64 bit Windows Server.
I have disabled all Add-in
I put the following code in a brand-new .xlsm file.
The problem is NOT about debug.print , if I change it into string comparsion, problem presists
Private Declare Function GetTickCount Lib "kernel32" () As Long

Public Sub Testing()
Err.Clear
Application.DisplayAlerts = False
Application.CutCopyMode = False
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
On Error GoTo Problem

    Dim a As Double
    a = 10 / 0
Problem:
    Dim sOutput As String
    Dim lStart As Long, lEnd As Long

    lStart = GetTickCount
    Debug.Print Err.Description
    lEnd = GetTickCount
    gsOutput = "Time requires : " & (lEnd - lStart) / 1000 & "s"
    Debug.Print gsOutput
End Sub

Any help would be nice.
EDIT
Problem And Solution Found: http://support.microsoft.com/kb/2683270
By the way, I do think this is not a localized question if the issue has been stated by Microsoft.

A:

Basically the problem is because some registry value is missing on local computer.
As suggested here
the winhelp.ini, which is used by Excel Process during error handling is missing ( You can check by using the tool suggested.)
Therefore, it's looking up from some other  %PATH% variable into network drive's C:\Windows\winhelp.ini.
the 1-2 Seconds are network delay.
The problem is solved by adding the registry mentioned.
HTH


Q:

Community Promotion Ads - 2014

It's the time of the year again, namely it is December 2013, and so we shall now refresh our Community Promotion Ads for the new year.
What are Community Promotion Ads?
Community Promotion Ads are community-vetted advertisements that will show up on the main site, in the right sidebar. The purpose of this question is the vetting process. Images of the advertisements are provided, and community voting will enable the advertisements to be shown.
Why do we have Community Promotion Ads?
This is a method for the community to control what gets promoted to visitors on the site. For example, you might promote the following things:

cool Ubuntu applications
the site's Twitter account
Ubuntu scripts or power tools
cool events or conferences
anything else your community would genuinely be interested in

The goal is for future visitors to find out about the stuff your community deems important. This also serves as a way to promote information and resources that are relevant to your own community's interests, both for those already in the community and those yet to join.
Why do we reset the ads every year?
Some services will maintain usefulness over the years, while other things will wane to allow for new faces to show up. Resetting the ads every year helps accommodate this, and allows old ads that have served their purpose to be cycled out for fresher ads for newer things. This helps keep the material in the ads relevant to not just the subject matter of the community, but to the current status of the community. We reset the ads once a year, every December.
The community promotion ads have no restrictions against reposting an ad from a previous cycle. If a particular service or ad is very valuable to the community and will continue to be so, it is a good idea to repost it. It may be helpful to give it a new face in the process, so as to prevent the imagery of the ad from getting stale after a year of exposure.
How does it work?
The answers you post to this question must conform to the following rules, or they will be ignored.

All answers should be in the exact form of:
[![Tagline to show on mouseover][1]][2]

   [1]: http://image-url
   [2]: http://clickthrough-url

Please do not add anything else to the body of the post. If you want to discuss something, do it in the comments.
The question must always be tagged with the magic community-ads tag. In addition to enabling the functionality of the advertisements, this tag also pre-fills the answer form with the above required form.

Image requirements

The image that you create must be 220 x 250 pixels
Must be hosted through our standard image uploader (imgur)
Must be GIF or PNG
No animated GIFs
Absolute limit on file size of 150 KB

Score Threshold
There is a minimum score threshold an answer must meet (currently 6) before it will be shown on the main site.
You can check out the ads that have met the threshold with basic click stats here.

A:

A:

A:


Q:

Javascript Redux update nested object property value

I have a question. How can I update my value in my nested object ?
so my Redux state looks like:
const initialState = {
    elements: [],
    selectedElement: {},

};

In elements array I will storage my "elements" with structure like this:
   {
        id: 3243,
        elemType: 'p',
        content: 'some example content',
        style: {
            fontSize: 30,
            color: "red",
            textDecoration: "underline",
            fontFamily: "Arial"
        }
    }

And now I'd like change values in style. Maybe fontSize, maybe color... depends which property will be selected.
I've made action creator which give me id, property, value for these changes.. but the problem is that I don't know how to exactly write code in reducer :(
Action Creator
   export const updateElement = (property, value, id) => {
    return {
        type: 'UPDATE_ELEMENT',
        property,
        value,
        id
    }
}

Reducer
const {id, elemType, content, style, type, selected, property, value} = action;

        case 'UPDATE_ELEMENT':
                const elementForUpdate = state.elements.find(element => element.id === id);
                console.log(id, property, value);
                return ...?

A:

In short, you have to maintain immutability. In your case, you have to make sure that:

The elements array is copied.
The updated element object is copied.
The style object of the updated element is copied.

You can accomplish all of these with a single map:
case 'UPDATE_ELEMENT': {
    const elements = state.elements.map(el => {
        if (el.id === id) {
            const style = { ...el.style, [property]: value };
            return { ...el, style };
        } else {
            return el;
        }
    });

    return { ...state, elements };
}


Q:

How to send request to https webservice in Android?

I am trying to send a request to Https webservice but it always returns 404 Not Found(Request url not found on this server) but it works perfectly in browser.It returns response in XML format. Please help guys.
Here is my code
    try {

        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("https", SSLSocketFactory
                .getSocketFactory(), 443));

        HttpParams param = new BasicHttpParams();

        SingleClientConnManager mgr = new SingleClientConnManager(param,
                schemeRegistry);

        HttpClient client = new DefaultHttpClient(mgr, param);
        HttpPost post = new HttpPost(Global.CARD_API_URL);

        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("user", "xxx"));
        parameters.add(new BasicNameValuePair("pass", "xxxxxxxx"));
        parameters.add(new BasicNameValuePair("cardNumber",
                "xxxxxxxxxxxxxxxx"));
        parameters.add(new BasicNameValuePair("expiryDate", "0515"));
        parameters.add(new BasicNameValuePair("cvc", "123"));

        post.setEntity(new UrlEncodedFormEntity(parameters));

        HttpResponse response = client.execute(post);

        String res = EntityUtils.toString(response.getEntity());

        Log.d("Card Details", res);

    } catch (Exception e) {

        e.printStackTrace();

    }

A:

Finally i've solved the question. I need to use Simple HTTP Url Connection instead of above method.
Here is the code
      try {
            url = new URL(api_url);

            URLConnection connection = url.openConnection();
            HttpURLConnection http_connection = (HttpURLConnection) connection;
            http_connection.setConnectTimeout(10000);

            // Set the appropriate HTTP parameters.
            http_connection.setRequestMethod("POST");
            http_connection.setRequestProperty("Content-Type",
                    "application/x-www-form-urlencoded; charset=utf-8");

            http_connection.setDoOutput(true);
            http_connection
                    .setFixedLengthStreamingMode(post_data.getBytes().length);

            DataOutputStream dos = new DataOutputStream(
                    http_connection.getOutputStream());

            dos.writeBytes(post_data);
            dos.flush();
            dos.close();

            // Read the response.
            InputStreamReader isr = new InputStreamReader(
                    http_connection.getInputStream());
            BufferedReader in = new BufferedReader(isr);

            sb = new StringBuffer();

            // Write the message response to a String.
            while ((response = in.readLine()) != null) {

                sb.append(response);
            }

               Log.d("Card Details", sb.toString());
            }catch(Exception e){

                     e.printStackTrace();
            }


Q:

Chromium widevine doesnt work on Ubuntu 17.04

I am on a fresh install of Ubuntu 17.04 and I can't get any encrypted content to play. Both Netflix and the test at http://www.widevine.com/demo/index.html don't work. Also chrome://components shows Widevine Content Decryption Module - Version: 0.0.0.0. I tried copying the libwidevinecdm* libraries from the latest chrome build to /usr/lib/chromium but it didnt help. Is this a known issue?

A:

I was able to make this work but I needed to use the dev ppa of chromium which is here, then re-copy the widevine* libraries from the latest chrome package (which you can download from google as normal but open with file-roller to get at the libraries). I'm not sure if this is a bug in the version of chromium that is distributed with ubuntu or if ubuntu patches it to refuse to load the DRM component.
Additionally, most sites that use widevine also check your user agent to make sure you are on a supported browser, and while chrome is supported chromium is not. It is also not enough to just approximate a correct browser either, you need the entire user agent, the most straightforward being a recent google chrome UA.
I found that
Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36
works for spoofing chrome 58.0.3029.81 on Linux.


Q:

Git commit not Syncing with Github

I am trying to commit a new file on git.
i created a new file in my Repo using below:
touch help.txt
git add help.txt
git commit
git push

But it did not reflect in the github repo while the file is there in local repo.

A:

The reason and solution are in the output of git push.

Updates were rejected because the tip of your current branch is behind
  its remote counterpart. Integrate the remote changes (e.g. 'git pull
  ...') before pushing again. See the 'Note about fast-forwards' in 'git
  push --help' for details.

Your changes were rejected by the remote because it has changes that your local branch does not.
You can do

git pull --rebase origin name-of-branch-you-want-to-push-to
git push origin name-of-branch-you-want-to-push-to


Q:

How do I rename an app in MacOS properly?

I am trying to rename an app in MacOS. I tried it using Finder, navigating to Applications, right clicking on the app to rename, moving to "information" and renaming it there.
This works in most places where the app name appears, but if I have the app opened in fullscreen and I swipe up with 3 fingers I still see the old app name in the menu at the top of the screen.
How can I change the app name also there?

A:

Renaming the .app package in Finder only changes the name there, it doesn't change the name shown in the menu. To do so edit YOUR.app/Contents/Resources/XY.lproj/InfoPlist.strings (with XY being the language you are using) and change CFBundleName there.
For applications without localization files you can also edit YOUR.app/Contents/Info.plist and set a new value for CFBundleName there.


Q:

SQL error in C#

conn.Open();
String sql = "select CATEGORIES.CAT_NAME,PRODUCTS.PRO_MODEL,PRODUCTS.PRO_NAME,PRODUCTS.PRO_PRICE,PRODUCTS.PRO_IMAGE,PRODUCTS.PRO_DESCRIPTION,PRODUCTS.PRO_STATUS,PRODUCTS.PRO_ACTIVE" +
"from PRODUCTS INNER JOIN CATEGORIES on PRODUCTS.CAT_ID = CATEGORIES.CAT_ID";

My Query SQL runs fine in MYSQL Server but it has error in C# code Incorrect syntax near the keyword 'INNER'. hope have answer soon

A:

You need to add space between (.PRO_ACTIVE" and "from)  string concatenation.
.PRO_ACTIVE " + "from...

So your query should be:
String sql = "select CATEGORIES.CAT_NAME,PRODUCTS.PRO_MODEL,PRODUCTS.PRO_NAME,PRODUCTS.PRO_PRICE,PRODUCTS.PRO_IMAGE,PRODUCTS.PRO_DESCRIPTION,PRODUCTS.PRO_STATUS,PRODUCTS.PRO_ACTIVE"
+ " " +//explicit space
"from PRODUCTS INNER JOIN CATEGORIES on PRODUCTS.CAT_ID = CATEGORIES.CAT_ID";

A:

You need a space at the end of the first line of your string -- C# doesn't put line feeds in.


Q:

Magento 2 - Import CSV without duplicating images

Does anybody know how to import CSV of multiple products to Magento 2 without duplicating images? I have been searching for a while and have only found fixes for this issue on Magento 1.

A:

If you are importing the same CSV multiple times, I am guessing you are modifying the CSV data due to some product data not being correct on initial import?
I would remove the image column data until you are happy with the import, then include the image data in the CSV last and import again.
You could also find/override the importer class and add a image filename based check before updating a products assigned images. Given the different import options (update/replace), I would also check these and limit the check to 'update' method maybe...


Q:

What is a good horizontal menu design for a lot of categories?

Is there a good horizontal menu design to display many categories and sub categories? If so can you give or point me to an example?

A:

have you had a look into "Mega Menus"? there is a good tutorial at http://net.tutsplus.com/tutorials/html-css-techniques/how-to-build-a-kick-butt-css3-mega-drop-down-menu/ which tells you how to do it (or just copy&paste the existing code).


Q:

How insert data on mongoDB with condition

i'm new to mongodb is there any option to append new data set into collection.
i.e in 'student',
{name: 'Tom', age: 28, marks: [{subject: "English", marks: 90},{subject: "Maths", marks: 100},{subject: "Computes", marks: 20}]}

in this 'student' collection how to insert new subject and marks
like
{subject:"chemistry", marks:30}

I know it may be silly question but pls help me on this
Thanks

A:

Try this one:
db.students.updateOne(
   { name: 'Tom' },
   {
      $push:
         { marks: { subject: "chemistry", marks: 30 } }
   },
);

Note, $push will add the element every time you execute the command. If you want to add the element only once then use:
db.students.updateOne(
   { name: 'Tom' },
   {
      $addToSet:
         { marks: { subject: "chemistry", marks: 35 } }
   }
);

This will append element { subject: "chemistry", marks: 30 } only once. Note, if you run { subject: "chemistry", marks: 31 } then it will be added also.
In case you like to insert chemistry just once then you can use this:
db.students.updateOne(
   {
      name: 'Tom',
      "marks.subject": { $nin: ["chemistry"] }
   },
   {
      $push:
         { marks: { subject: "chemistry", marks: 30 } }
   }
);


Q:

Graph Coloring Question

Given T(n) as a star graph with n edges. (Basically T(n) is a graph that has one vertex u in the center, and from u there is one edge to each vertex v1,...,vn.)
It is easily know that star-graphs are at least 2-colorable. Assume you have two separate star-graphs, Tk and Tm, for some positive integers k and m. Pick one random vertex from each graph and connect them with an edge. What information would you infer is true from the resulting graph of T?
Answer Choices
1) The graphs chromatic number is 3
2) MAX_DEG(T) = max(k,m) + 1
3) T is two-colorable
4) MAX-DEG(T) = max(k,m)

A:

3 Is true: Color the first graph $T_k$ with two colors, lets call them for simplicity red and blue. The vertex you picked from this graph has one color. Color the vertex picked from the second graph with the other color.
As the second graph $T_m$  is 2-colorable, once we colored one single vertex with a color we can complete it to a 2-coloring of this $T_m$. It is easy to check that this is a good $2$-coloring of the big graph.
To complete the proof, it is easy to argue that the graph is not one -colorable.
1 is (always) false, because we just proved the graph is 2-colorable.
2 is (sometimes) false, you can see this by connecting vertices of degree 1.
4 is (sometimes) false you can see this by connecting the centers of the graphs.


Q:

Has my @ notification to a user worked?

I asked a question on Stack Overflow, and a user named Molecular Man answered it correctly. I don't know why, but he just deleted his post. I just @ notified him in a comment to ask him why he deleted his post. but I have not had a reply.
I just want to know whether the user has been notified of my comment or not? (I am just curious about it, because there is no response from that user)

A:

No, he didn't get notification of your reply, because you replied him on your question, where he has neither commented nor edited.
For more information on how comment replies work see this Meta Question:

How do comment @replies work?


Q:

How I can extract matrixes WI and WO from gensim word2vec?

CBOW word2vec scheme look like this:

How I can extract matrixes WI and WO from gensim.models.word2vec.Word2Vec?
I found only these fields in gensim w2v model:
gensim.models.word2vec.Word2Vec.trainables.syn1neg
and
gensim.models.word2vec.Word2Vec.vw.syn1neg.vectors
Can I make an assumption that syn1neg is WI, and WO = vectors - syn1neg?
Why this code
sentences = [['car', 'tree', 'chip2'], ['chip1', 'sugar']]
model = Word2Vec(sentences, min_count=1, size = 5)

give Word2Vec.trainables.syn1neg matrix with zero elements only?
For 30MB dataset Word2Vec.trainables.syn1neg matrix also contain zero elements only, log is here:
gensim log

A:

The w2v_model.wv.vectors is what was formerly called "syn0", and serves as the "projection weights" which essentially map a one-hot word-encoding into N dimensions. In your diagram, that's WI.
The w2v_model.trainables.syn1neg is the hidden-to-output weights for negative-sampling mode, what your diagram labels WO.


Q:

Ajax request after sometime freeze browser

I have made admin panel where setup notification alerts using ajax. It is working fine, but after few minutes than it starts to freeze the browser. Any idea what I am doing wrong, as it is my first Ajax project.
Following are codes which I am using, I used setInterval in a function which is called by body onload event.

        <-- Some notification divs to be replaced by javascript -->

JavaScript


Q:

How can I get the concatenation of two lists in Python without modifying either one?

In Python, the only way I can find to concatenate two lists is list.extend, which modifies the first list. Is there any concatenation function that returns its result without modifying its arguments?

A:

Yes: list1 + list2. This gives a new list that is the concatenation of list1 and list2.

A:

The simplest method is just to use the + operator, which returns the concatenation of the lists:
concat = first_list + second_list
One disadvantage of this method is that twice the memory is now being used . For very large lists, depending on how you're going to use it once it's created, itertools.chain might be your best bet:
>>> import itertools
>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = itertools.chain(a, b)

This creates a generator for the items in the combined list, which has the advantage that no new list needs to be created, but you can still use c as though it were the concatenation of the two lists:
>>> for i in c:
...     print i
1
2
3
4
5
6

If your lists are large and efficiency is a concern then this and other methods from the itertools module are very handy to know.
Note that this example uses up the items in c, so you'd need to reinitialise it before you can reuse it. Of course you can just use list(c) to create the full list, but that will create a new list in memory.

A:

concatenated_list = list_1 + list_2


Q:

PE - Бинарный формат

Здравствуйте, не могли бы вы подкинуть статей на русском языке о структуре данных в бинарнике pe формата.Спасибо.

A:

Я в свое время читал вот эту серию статей. Довольно доходчиво все описано.


Q:

Cannot find symbol "messaging" in com.google.firebase.messaging.FirebaseMessagingService

I am trying to access FirebaseMessagingService using firebase 9.2.1 library. I have successfully created a project then download the JSON file. I have finally integrated this JSON file with my project. FirebaseInstanceIDService is running fine but showing error with FirebaseMessagingService. So i checked my project folder inside android studio. Then i find that firebase-messaging 9.2.1 library is missing. How can i resolve this issue. I have already upgraded all of the SDK libraries. Please help me to fix this issue.

A:

You need to add Firebase Messaging to your dependencies:
compile 'com.google.firebase:firebase-messaging:9.2.1'

Setup for Firebase Cloud Messaging is explained in the documentation.


Q:

Why ExecutorService is not working in a stream?

I am passing a set of tasks by stream, here is a simplified demo:
    ExecutorService executorService = Executors.newCachedThreadPool((r) -> {
        Thread thread = new Thread();
        thread.setDaemon(true); // even I removed this, it's still not working;
        return thread;
    });
    IntStream.range(0, TASK_COUNT).forEach(i -> {
        executorService.submit(() -> {
            out.println(i);
            return null;
        });
    });

After all the tasks submitted, I try to wait all of them finished using:
    executorService.shutdown();
    executorService.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);

But the output is none, there is nothing printed out.
Something wrong? Any help will be appreciated.
One weird find-out is that when using the default DefaultThreadFactory, it's working.
ExecutorService executorService = Executors.newCachedThreadPool();

F.Y.I Daemon threads are the the cause which I checked already. To debug, I set them on purpose.

A:

You forgot to pass a Runnable to the Thread constructor:
ExecutorService executorService = Executors.newCachedThreadPool(r -> {
    Thread thread = new Thread(r);
                               ^
    thread.setDaemon(false);
    return thread;
});


Q:

path.exists returns unexpected result after rmtree command

The goal is to:

create a folder if it doesn't exist
delete a folder with
all items if it exists and then create a new empty folder

search_dir = path.join(...,..., 'My_Folder')

rmtree(search_dir , ignore_errors=True)

if not path.exists(search_dir):
    makedirs(search_dir)

That code works fine if the folder doesn't exist or folder has no files.
But it doesn't create a new empty folder if it has some files.

A:

You pass ignore_errors=True to rmtree(), so if any error occurs during the call (like the directory contains some file you don't have permissions on) you won't be warned - but the function will have failed nonetheless. Solution: dont ignore errors, handle them - either using a try/except block around the call or by passing an onerror callback to rmtree (cf the doc).


Q:

One to One unidirectional mapping with same primary key in hibernate

I have two classes/tables (Metafile and RowCount) with a one to one relation. Rowcount only applys to certain metafiles. Currently I have this set up (simplified):
MetaFile.java
@Entity
@Table(name = "file")
public class MetaFile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "file_id")
    private int fileId;
    // getters, setters, constructors...
}

RowCount.java
@Entity
@Table(name = "row_count")
public class RowCount implements Serializable {

    @OneToOne
    @JoinColumn(name="file_id")
    private MetaFile file;

    @Id
    @Column(name="file_id")
    private int file_id; // duplicate field needed so that crudrepo would recognise the id

    private int rows;

    public RowCount(MetaFile file, int rows) {
        this.file = file;
        this.rows = rows;
        this.file_id = file.getFileId();
    }
    // getters, setters...
}

I'm using crudrepositories for both to simplify persistance.
I first save the metafile to get an ID assigned, then I create a rowcount object using that metafile with the new ID and save it (shown below). This second save fails however, as the metafile isn't persisted to the database immediately, and the foreign key constraint fails.
metaFile = fileRepository.save(metaFile);

rowCountRepository.save(new RowCount(metaFile,getNumberOfRows(file));

The metaFile definitely gets a valid id assigned to it. Is there a way to make sure these two persists happen in order?
Thanks!

A:

You can change your mapping with @mapsId as suggested by Hadi J to have a single pk/fk column in RowCount
@Entity
@Table(name = "row_count")
public class RowCount implements Serializable {

   @OneToOne
   @JoinColumn(name = "file_id")
   @MapsId
   private MetaFile file;

   @Id
   @Column(name="file_id")
   private int file_id;

   private int rows;

   public RowCount(MetaFile file, int rows) {
       this.file = file;
       this.rows = rows;
   }
   // getters, setters...

}

I would use a bidirectional relationship to simplify saving:
@Entity
@Table(name = "file")
public class MetaFile {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "file_id")
    private int fileId;
    // getters, setters, constructors...

    @OneToOne(cascade = {CascadeType.ALL}, mappedBy = "file")
    private RowCount rowCount;
}

This way you can just set the relationship and save
RowCount rowCount = new RowCount(metaFile, getNumberOfRows(file));
metaFile.setRowCount(rowCount);
metaFile = fileRepository.save(metaFile);


Q:

Work around lacking const-correctness of external library

I am using an external C++ library that lacks const-correctness. Lets say I am working with objects of the following class:
// Library.h
namespace Library {

class Message {
 public:
    std::string getData() {
        return data_;
    }
 private:
    std::string data_;
};

}  // namespace Library

Note that getData() returns a copy, thus a call to the method does not change the Message object and it should be const. However, the vendor decided it's not.
On my side of the code, const-correctness is important and the Message is to be used in a function like so:
// MyApplication.cpp

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();
    // interprete and process content ...
}

Is there a way to achieve this? In other words, how to work around the error: passing 'const Library::Message' as 'this' argument discards qualifiers error without changing the signature of the handleMessage function?

A:

You could also use wrapper with mutable member variable like:
#include <string>

class Message {
 public:
    std::string getData() {
        return data_;
    }
    Message(std::string data): data_{data} { }
 private:
    std::string data_;
};

class MessageWrapper {
 public:
    MessageWrapper(Message message): message{message} {}
    std::string getData() const {
        return message.getData();
    }
 private:
    mutable Message message;
};

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();

}

int main() {
    MessageWrapper mw{{"abc"}};
    handleMessage(mw);
}

[live demo]
Edit:
To force const correctness you could save once retrieved data from the message e.g.:
#include <string>
#include <optional>

class Message {
 public:
    std::string getData() {
        return data_;
    }
    Message(std::string data): data_{data} { }
 private:
    std::string data_;
};

class MessageWrapper {
 public:
    MessageWrapper(Message message): message{message} {}
    std::string getData() const {
        return (data)?(*data):(*(data = message.getData()));
    }
 private:
    mutable Message message;
    mutable std::optional<std::string> data;
};

template<class T>
void handleMessage(const T& msg) {
    std::string content = msg.getData();

}

int main() {
    MessageWrapper mw{{"abc"}};
    handleMessage(mw);
}

[live demo]

A:

You basically have two options. You could use a const_cast
template<class T>
void handleMessage(const T& msg) {
    std::string content = const_cast<T&>(msg).getData();
    // interprete and process content ...
}

this is fine as long as you know for sure that getData really does not modify any members. Or if you dont mind some overhead you can make a copy:
template<class T>
void handleMessage(const T& msg) {
    T copy = msg;
    std::string content = copy.getData();
    // interprete and process content ...
}

... or as a third option, if you want to hide the const_cast from the call site you can wrap it:
class MyMessage {
     Message msg;
public:
     std::string getData() const {
         return const_cast<Message>(msg).getData();
     }
};


Q:

How do I uninstall Ubuntu from a dual-boot with Windows 8?

I'm definitely coming back to Ubuntu in the fall for one of my classes but for now I would like to uninstall it. The only problem is, I've heard that people who uninstall it improperly are unable to boot back into Windows 8 and I really can't have that.
Currently, my system has Ubuntu 13.04, Windows 7 and 8 [all 64-bit]. I originally installed Ubuntu by making a new partition on my disk drive and booting from my flash drive which had the Ubuntu 12.10 iso burned on to it. I then installed Ubuntu 12.10 on to that partition.
What's the safest way to uninstall Ubuntu with my setup?
Please and thanks!

A:

Did you see this?
http://www.makeuseof.com/tag/how-to-safely-uninstall-ubuntu-in-windows-dual-boot-environment/
This requires you to have a working Windows installation disk.


Q:

How do I configure project properties using TortoiseSVN GUI to get the ignore list from a text file

I am using TortoiseSVN GUI. When I open a project's properties I am present with grid of two columns "Property" and "Value". I select "svn:ignore" for the property. In the Value I can enter multiple text strings separated by newlines.
How can I tell it to pull the ignore list from a text file? Is this possible in the properties popup dialog form, or is this only possible using command line tools?

A:

In the properties dialog you can see the Import option where you can specify a .svnprop file to import the properties from. Also, you can double click on a particular property or select Edit or New and hit load to similarly load the properties from a file.
If on the other hand you want a way of getting the ignore list from a file, like it is done in Git or Hg ( throught .gitignore and .hgignore ), you can't really do that with SVN / TortoiseSVN.


Q:

How to make plot of implicit function?

I try to produce a plot of
$$\frac{1}{2}-\left| y\right| =\sqrt{\left(\frac{1}{2}-\left| y\right| \right)^2+(y-\sin (x))^2} $$
through
ContourPlot[1/2 - Abs[y] ==Sqrt[(1/2 - Abs[y])^2+(y-Sin[x])^2],
{x,-Pi,  Pi}, {y, -1, 1}, PlotPoints -> 20]

, but I obtain an empty plot.

A:

ir = ImplicitRegion[
  FullSimplify[
   Reduce[{1/2 - Abs[y] ==
      Sqrt[(1/2 - Abs[y])^2 + (y - Sin[x])^2], -Pi < x < Pi, -1 < y <
      1}, {x, y}, Reals]], {x, y}]
RegionPlot[ir,
 GridLines -> {{-Pi, -5 Pi/6, -Pi/6, Pi/6, 5 Pi/6, Pi}, None}]

A:

This can be solved algebraically as follows:
$$\frac{1}{2}-\left| y\right| =\sqrt{\left(\frac{1}{2}-\left| y\right| \right)^2+(y-\sin (x))^2} $$
Firstly note that $\frac{1}{2}-|y|\ge0$ so $-\frac{1}{2}\le y\le\frac{1}{2}$.
Next square the equation:
$$\left(\frac{1}{2}-\left| y\right|\right)^2 =\left(\frac{1}{2}-\left| y\right| \right)^2+(y-\sin (x))^2 $$
$$0=(y-\sin(x))^2$$
$$0=y-\sin(x)$$
$$y=\sin(x)$$
So the solution is $y=\sin(x)$ such that $-\frac{1}{2}\le y\le\frac{1}{2}$.
Using Mathematica's Solve or Reduce gives the same result (it just gives restrictions on $x$ rather than $y$).
Solve[{1/2 - Abs[y] == Sqrt[(1/2 - Abs[y])^2 + (y - Sin[x])^2], Element[y, Reals], Element[x, Reals]}, y]

{{y -> ConditionalExpression[Sin[x], (C[1] \[Element] Integers && 2 \[Pi] C[1] <= x <= 1/6 (\[Pi] + 12 \[Pi] C[1])) || (C[1] \[Element] Integers && \[Pi] + 2 \[Pi] C[1] < x <= 1/6 (7 \[Pi] + 12 \[Pi] C[1])) || (C[1] \[Element] Integers && 1/6 (-\[Pi] + 12 \[Pi] C[1]) <= x < 2 \[Pi] C[1]) || (C[1] \[Element] Integers && 1/6 (5 \[Pi] + 12 \[Pi] C[1]) <= x <= \[Pi] + 2 \[Pi] C[1])]}}

Reduce[{1/2 - Abs[y] == Sqrt[(1/2 - Abs[y])^2 + (y - Sin[x])^2], Element[y, Reals], Element[x, Reals]}, y]

C[1] \[Element] Integers && (((2 \[Pi] C[1] <= x <= 1/6 (\[Pi] + 12 \[Pi] C[1]) || 1/6 (5 \[Pi] + 12 \[Pi] C[1]) <= x <= \[Pi] + 2 \[Pi] C[1]) && y == Sin[ x]) || ((1/6 (-\[Pi] + 12 \[Pi] C[1]) <= x < 2 \[Pi] C[1] || \[Pi] + 2 \[Pi] C[1] < x <= 1/6 (7 \[Pi] + 12 \[Pi] C[1])) && y == Sin[x]))

Plotting the solution from the algebraic solution is then straightforward:
Plot[Sin[x] && Abs[Sin[x]] <= 1/2, {x, -Pi, Pi}]


Q:

Rules & Regulations Of Hogwarts School Of Witchcraft & Wizardary

What do you think would be the requirements in getting admission in Hogwarts School of Witchcraft and Wizardry?
Would a child of 10 years old gain admission if he were to turn 11 in the months to come after July, for example December?
Will his/her relationships with anyone matter, like Draco Malfoy had relations with Death Eaters and other stuff like that?

A:

Would a 10 year old child gain admission if they were to turn eleven in a month after July (e.g. December)?
Hogwarts admission letters are sent to potential students shortly before their eleventh birthday (Harry started receiving letters in the week prior to his actual birthday, if I recall correctly). Given that the school year starts on the 1st of September it seems likely that any student who turned eleven on, or before, the 31st of August would be admitted to Hogwarts for the coming school year. However, if your eleventh birthday was after the 1st of September you'd have to wait until the next school year to gain admittance; for those with birthdays in September and October they'd be approaching their twelfth birthday when they finally started at the school.
There's no canon information to back that up but it reflects the way that school admission works in the UK. Mac Cooper pointed out that there is, in fact, canon information to support this in a FAQ on an old (archived) version of JK Rowling's site:

When Hermione arrived at Hogwarts, was she nearly eleven or nearly twelve? [also asked by vast numbers of people]
She was nearly twelve; you must be at least eleven to attend Hogwarts.
JK Rowling Official Site (Wayback machine)

As for the second half of your question: not in terms of admission. The opinion held by three of the four school founders was that any who wished to learn should be taught, and that's an opinion that was definitely shared by the Headmaster during Harry's time at the school, and I'd assume by most - if not all - of the other Headmasters. Considering that extended to Muggleborn witches and wizards, I can't see any reason that affiliations with suspected, or even proven, Death Eaters would have prevented them from attending the school.


Q:

What does "$(@:H)" do in MakeFile?

I was speaking with one of my fellow interns at lunch today who is working almost exclusively in Makefile this summer, and he mentioned that he has no idea what $(@:H) means or does. My google-fu is failing me, as I cannot find it anywhere on the web, and was hoping you guys could help me out.

A:

Assuming this is GNU make then that's just the expansion of the (oddly named) @:H variable. Which isn't a default variable (and isn't a variable that can be set with the normal assignment syntax) and would be an odd choice for a variable name to begin with as it is very close to real variable expansions.
It is much more likely that this is referring to BSD make where :H is a variable modifier which (excerpt from the man page):

:H
Replaces each word in the variable with everything but the last component.


Q:

How to store employee object in SQLite Database in android

I have create a Employee object, in that properties are name,lastname,phone etc..
Now i created object

Employee emp = new Employee();

Now i want store emp object into bytes in a SQLite in an andriod.
Please help me how to acheive?
I know how to insert values through ContentValues but I don't want to create a table with 50 cols. I just want to save the class Object and
I want to retrieve it later.

A:

you can use the json of your objects. it is so easy and you can use liberaries such as gson


Q:

sys.executable results are different in terminal and jupyter notebook

Because I face a problem: When from imageio import imread in my jupyter notebook, I get the error: ModuleNotFoundError: No module named 'imageio'
Whereas I can successfully import in my terminal, I try to figure out what happened.
When I execute sys.executable in jupyter notebook and in the terminal, the results are different:

So I tried:(from https://github.com/jupyter/notebook/issues/1524#issuecomment-229713719)
/Users/shinyuwu/anaconda3/bin/python -m pip install ipykernel
/Users/shinyuwu/anaconda3/bin/python -m  ipykernel install

But the sys.executable result in jupyter notebook and terminal are still different. Can anyone help me?

A:

I had faced this issue some time back
The way I solved this was

Deleting IPython and Jupyter from the system
rm -rf ~/.local/share/ipython
Reinstall IPython and Jupyter


Q:

Sitecore Commerce Analytics Errors

I have installed and configured the Sitecore Demo Retail site on top of Sitecore Commerce 8.2.1.
I have been having issues with the commerce page events and analytics. I cannot seem to get any data in the experience analytics reports tab
Below are the Error in Logs (This happens when Checkout process is completed)

ERROR Event custom value key 'ExternalId' could not be found. ERROR
  Event custom value key 'ShopName' could not be found. ERROR Event
  custom value key 'Total' could not be found. ERROR [Experience
  Analytics]: SegmentProcessor failed to process interaction
  '4c0f5d2b-8b18-41bc-bff8-50ade2db6ed0' segment
  '5505a370-dcb2-4772-8574-000f6c3ddb5c' -
  System.NullReferenceException: Object reference not set to an instance
  of an object. at
  Sitecore.Commerce.ExperienceAnalytics.Models.OrderModel..ctor(OrderGoalAnalyticsData
  analyticsData) at
  Sitecore.Commerce.ExperienceAnalytics.Dimensions.ByOrder.GetOrderModels(PageData
  pageData) at
  Sitecore.Commerce.ExperienceAnalytics.Dimensions.ByOrder.d__2.MoveNext()
  at System.Linq.Enumerable.WhereEnumerableIterator1.MoveNext() at
  Sitecore.ExperienceAnalytics.Aggregation.Pipeline.SegmentProcessor.ProcessSegments(AggregationPipelineArgs
  args, IEnumerable1 segments)

A:

I managed to find out the root cause of this issue
Sitecore Commerce has a lot of goals and events being triggered programatically, My issue was that the goal "Visitor Order Created" was checked on the "Order Confirmation Page" and this was causing the goal to be triggered twice (Once programatically and other through the UI)
I had to uncheck the goal in content editor and then this seem to solve the issue.
I have added detailed notes here in the blog post
https://blog.horizontalintegration.com/2017/11/25/sitecore-commerce-8-2-1-analytics-issue/


Q:

NatTable HoverStylingCommandHandler not being triggered by HoverStylingCommand

The issue that I am having is that I am attempting to execute a HoverStylingCommand by calling:
natTable.doCommand(new HoverStylingCommand(natTable, columnIndex, rowIndex, hoverLayer);

and the HoverStylingCommandHandler that is registered by the HoverLayer is never being triggered when the command is executed. However the handler does get hit when the exact same command is triggered from the SimpleHoverStylingBinding.

A:

It doesn't make sense to execute the HoverStylingCommand programmatically. It is intended to operate in combination with the mouse cursor position. IIRC the command handler performs a check on the mouse cursor position. So from the functional point of view it is correct that the command handler is not triggered.


Q:

How is $J^{PC}$ value experimentally determined for new types of particles?

How is $J^{PC}$ value experimentally determined for new types of particles?
For example, this paper says

... Angular correlations in B+→X(3872)K+ decays, with X(3872)→ρ0J/ψ, ρ0→π+π− and J/ψ→μ+μ−, > are used to measure orbital angular momentum contributions and to determine the JPC value > of the X(3872) meson.

What's a description of how it works suitable to advanced undergraduate students?

A:

Here is a nice late-undergrad or early-grad-school lab report on the determination of spin states in nuclear decays.  The references to that paper (from 1940 and 1950) are relatively accessible, too.
As your pullquote says, you get $J^{PC}$ from measuring angular correlations.  If a particle at rest decays into two daughters, the angular correlation is trivial: the two daughters must go out back-to-back to conserve momentum.  However if you have a more complicated decay, you can have correlations where some of the decay products tend to be emitted more parallel or more antiparallel than the others.  Add in the fact that the odd-$L$ spherical harmonics have negative parity and you start being able to eliminate possibilities. For example, that's the original argument for thinking the proton and neutron each obey the exclusion principle.
We can talk through the logic in your paper:

$X\to \gamma J/\psi$ implies $\hat CX = +X$.

Remember that charge conjugation, $\hat C$, is the operator which changes a particle to its antiparticle; only neutral particles may be eigenstates of $\hat C$, and the eigenvalues $C$ must have $C^2 = 1$.  You can look up that the photon and the $J/\psi$ both change sign under $\hat C$, so a state which contains only those two particles does not change sign under $\hat C$.

In decays like $X\to\pi^+\pi^-J/\psi$, the angular momentum of the two-pion subsystem must be odd.

By the same logic as before, the di-pion $\pi^+\pi^-$ must have negative $C$. For this composite system, charge conjugation is the same operation as having the two particles swap places, so the pion part of the wavefunction must have negative parity.  Only orbital angular momentum wavefunctions with odd $L$ have negative parity.

Dipion spins $J_{\pi\pi} \geq 3$ are ruled out because all the high-spin mesons are too heavy, so $J_{\pi\pi} = 1$.

Now we are into data analysis: you have to look at how the $J/\psi$ and the pions divvy up the energy available in decays of the $X$, and frown for a while at the Particle Data Group's list of mesons until you don't find anything and give up.  They go on to further state that the channels with two pions seem to be consistent with $X\to\rho^0\,J/\psi$.

That's as far as you can really get using only the types of particles emitted and the energies involved.
The next step is to actually look at decay correlation angles.
When the $X$ decays to a $\rho^0$ and $J/\psi$, the spins of those two pseudovector particles are correlated with each other, and the momenta are back-to-back in the rest frame of the $X$.
When those particles decay into their pairs,
the decay momenta are back-to-back in their rest frames;
but because of the correlated spins the two pairs of second-generation decay products aren't in independent planes.
An earlier paper considered more possible quantum numbers for the $X$, and included this better figure describing the decay angles:

That paper argues against any values for $J^{PC}$ other than $1^{++}$ or $2^{-+}$, using the same sorts of arguments but less data.
Your paper's final figure, below,

shows the number of events with a given $\theta_X$ and a smallish $\theta_\rho$.
The data, black points with error bars, are the repeated identically in each subplot.
The solid colored lines show the expected distributions of events for various internal values of $J^{PC}$.
These predictions are probably based on elaborate Monte Carlo simulations, rather than first-principles calculations like the electromagnetic correlations functions in my first couple of links, but the idea is the same.
You can see, for example, that the $J=0$ predictions have approximate spherical symmetry (uniform in $\cos\theta_X$),
while the large-$J$ predictions are strongly peaked with the $J/\psi$ being emitted either parallel or antiparallel to the momentum of the $X$.  One of those fits is not like the others, and so the spin is assigned.