text:
Q: Images in drawable of android I am trying to hide my private key in an image by changing its pixel value at random locations and hiding this process by writing this code in c++ using ndk. so my questions are
1) Will android change drawable images when app is used in different screen size      thus erasing or corrupting my keys?
2) How hard it will be to write image processing code in ndk?
3) Is there any better and more secure place to store my keys? (Don't say db, key-value etc all can be hacked if phone is rooted)
Thank you.


text:
Q: Copy Pivot Table Values and Format on another cell How do I copy and paste a value in a pivot table and also at the same time copying its format if combined with text. There will be like multiple concatenations on the destination cell.
I cannot seem to make it work (cell A7 is my try).
Please see below.

A: I can't think of an answer to referring to formatting of a cell without using vba, but indirectly you might get the desired result by using the camera tool/linked picture referring to the cell(s) you need.
This will exactly show what and how you want it.
Not sure if that's something you desire to work with.

A: Use this
=Round(GETPIVOTDATA("[Measures].[Sum of Sales Value in Euro]",$A$3)/1000,1)&"K Eur ("&Round(GETPIVOTDATA("[Measures].[Sum of Value % Chg YA]",$A$3),2)&"%)"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cause of a stack overflow in this method (floating-point math) I occasionally get a stackoverflow exception in this method.
double norm_cdf(const double x) {
    double k = 1.0/(1.0 + 0.2316419*x);
    double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k))));

    if (x >= 0.0) {
        return (1.0 - (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum);
    } else {
        return 1.0 - norm_cdf(-x);
    }
}

Any suggestions on why i might be getting it ? Any steps I can take to rectify the error ?

A: When x is NaN, the recursion will never terminate. Add a check: Either std::isnan in C++11, or the lazy x != x, or document-and-blame-user. If you choose to handle NaN, propagating it might be a sensible choice.

A: Your problem is when x is Not a Number. NAN >= 0.0 is false, -NAN >= 0.0 is also false.
You could check against NAN specially, as others have suggested, but I would suggest simplifying things:
static double norm_cdf_positive(const double x) {
    double k = 1.0/(1.0 + 0.2316419*x);
    double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k))));

    return (1.0 - (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum);
}

double norm_cdf(const double x) {
    if (x >= 0.0) {
        return norm_cdf_positive(x);
    } else {
        return 1.0 - norm_cdf_positive(-x);
    }
}

This has the advantage that compilers can make smarter assumptions about its behaviour. Note that I've marked the "internal" function static (which will limit its scope to the current compilation unit). You could also use unnamed namespaces. (edit: actually Timothy Shields has a simpler way of removing the recursion, which keeps everything in one function)

A: Likely this method is just the straw that breaks the camel's back. This function will only call itself at most once, so it's not the problem. (Edit: Or it's the NAN issue others point to, which will result in infinite recursion.)
You can easily make the function not recursive anyway, which might be a simpler option.
double norm_cdf(double x) {
    bool negative = x < 0;
    x = abs(x);
    double k = 1.0/(1.0 + 0.2316419*x);
    double k_sum = k*(0.319381530 + k*(-0.356563782 + k*(1.781477937 + k*(-1.821255978 + 1.330274429*k))));

    double result = (1.0/(pow(2*M_PI,0.5)))*exp(-0.5*x*x) * k_sum;
    if (!negative)
        result = 1.0 - result;
    return result;
}


text:
Q: CodeIgniter ZIP Add Data inaccurate I was creating a monitor script using CI and make it downloadable. The files were generated by reading the file and modify the anchor pre-entered in the .ini and .php file.
But I found that the strtr part is not modified.

Part of the controllers/monitor.php:

$post    = $this->input->post();
$this->load->helper('file');
$monitor_php = read_file('script/monitor.php');
$monitor_php = str_replace(array('___MONITOR_CODE___'), array($monitor['monitor_code']),  $monitor_php);

$monitor_ini = read_file('script/monitor.ini');
$monitor_ini = strtr($monitor_ini, $post);
$monitor_ini = str_replace(array('___MONITOR_HOST___'    , '___MONITOR_SCRIPT___'    , '___MONITOR_REPORT_INTERVAL___'),
                              array($monitor['monitor_host'], $monitor['monitor_script'], $monitor['monitor_report_erval']),
                              $monitor_ini);

$this->load->library('zip');
$this->zip->add_data('monitor.php', $monitor_php);
$this->zip->add_data('monitor.ini', $monitor_ini);
$this->zip->download('monitor');

The result of var_export($post);:

array (
  '___OPERATING_SYSTEM___' => 'CentOS 7.2',
  '___WEB_SERVICE___' => 'httpd',
  '___MYSQL_SERVICE___' => 'mariadb'
)

I have echo the $ping_ini and it appears to be fine, but the file is still nothing changed.

The result of echo $monitor_ini;:
[Analyser]
MonitorHost = "localhost"
MonitorScript = "monitor.php"
OperatingSystem = "CentOS 7.2" // Good
ReportInterval = "1800"

[Service]
WebService = "httpd" // Good
MySQLService = "mariadb" // Good

But actually the downloaded monitor.ini is:
[Analyser]
MonitorHost = "localhost"
MonitorScript = "monitor.php"
OperatingSystem = "___OPERATING_SYSTEM___" // nothing changed
ReportInterval = "1800"

[Service]
WebService = "___WEB_SERVICE___" // nothing changed
MySQLService = "___MYSQL_SERVICE___" // nothing changed


text:
Q: Spinning in a non-blocking app without gobbling up CPU time I have a UDP network application that reads packets sent to it and then processes them (same thread).  The reads are non-blocking so I'm not using poll or select.
Packets received are grouped by sessions.
Work is governed by whether there is a session in progress.  If there is no work to be done i.e. there are no sessions, or there are no packets to process then I need to spin.
I've been looking at the hybrid algorithm found here:
http://www.1024cores.net/home/lock-free-algorithms/tricks/spinning
Been playing with it. I'm told it's more for busy waits.  What methods do you use to prevent unnecessary processing and needlessly high CPU usage?
EDIT:
Thanks for all the answers and comments.
I'm now doing the following. When it comes to reading from the network I look to see if there is other work to be done.  If there is, then I call poll with a timeout of zero.  I then read as many packets as I can and place them into an in memory queue for processing.  If no other work then I poll indefinite (i.e. -1). It seems to work well, CPU is only high when things are busy, otherwise it drops to zero.

A: If you have nothing to do, you should be blocking - if not on the socket itself (i.e. if it's an event loop that processes more than one network socket or event type), then on a gate that gets signaled when something happens (the design depends on how your OS does async I/O).
Spinning is something you should only be doing when you're waiting for a very short period of time (usually only in kernel mode).

A: Since you have to read from a socket, you can just do a blocking read. Without a packet, you have no reason to be running, right?
If there is more than one socket, then the blocking read won't work, so you need pselect() to monitor multiple descriptors.
Am I missing something obvious?
It occurs to me that you may have some long-term processing after you do receive a datagram. If the reason you are going with non-blocking I/O is to avoid ignoring incoming traffic while working on a session, then in that case the obvious thing to do is to fork() the sessions.  (Hmm, so I still think I must be missing something...)

A: How many packets per second are you processing? How long does it take to process those packets? If you use blocking threads, what is the average CPU usage you get?
Unless blocking wait is close to 100% usage, where shaving a few bits of performance from the blocking itself can help, spinning will not improve but rather worsen performance. By spinning, you lock one core that will not be available to run other code (possibly including the code that feeds you with work: i.e. kernel code that reads network and passes up to your app the packets), you burn resources without performing any work at all...
Note that when the article says that it is harder to write blocking code than non blocking spin waits, the author is not talking about operations for which the blocking version is implemented in the system, but rather for situations where on thread must wait on a condition triggered by other threads (a shared variable value goes above/below a limit, a flag is changed...).
Also, if the cost of checking the condition is high, then spinning will incur in that cost for each and every iteration of the loop, and that might well exceed the cost of checking once and performing an expensive wait.
Remember that spinning is an active wait, it does not make sense to ask how to actively wait while not consuming processor, as the active wait approach implies consuming processor time. What can you do to avoid needless CPU usage? Use a blocking call to get the next packet. In the particular case of reading an UDP packet I doubt that two calls to the non-blocking read are not more expensive in processing time than a single call to the blocking read operation.
Again think on the questions in the beginning, that can be summed to: Is blocking proven to be the bottleneck? *Is this an scenario where active waits can actually help?*


text:
Q: tableView(canEditRowAt) no longer working with tableViewDiffableDataSource I created a fairly simple tableView for selecting a category for an item model. Everything was working fine yesterday. Today I have been trying to switch the tableView data source over to a UITableViewDiffableDataSource as I want to wrap my head around the API.  I have the entire tableView back up and running EXCEPT I can no longer edit my rows!
the setEditing logic works as the newCategoryButton is disabled when I tap the edit button in the navigation bar and is enabled when I tap it again. However, I am never able to swipe to delete and the delete icons do not show up next to my rows in editing mode.
I tried removing setEditing, emptying out commit editingStyle and simply setting canEditRow to return true and still nothing.
Any help would be greatly appreciate. Thank!
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    let section = dataSource.snapshot().sectionIdentifiers[indexPath.section]
    if section == .noneSelected {
        return false
    } else {
    return true
    }
}

override func setEditing(_ editing: Bool, animated: Bool) {
    super.setEditing(editing, animated: true)
    if editing == true {
        newCategoryButton.isEnabled = false
    } else {
        newCategoryButton.isEnabled = true
    }
}

override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
        categories.remove(at: indexPath.row)
        tableView.deleteRows(at: [indexPath], with: .automatic)
    }
}

override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
    return true
}

override func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
    let movedCategory = categories.remove(at: sourceIndexPath.row)
    categories.insert(movedCategory, at: destinationIndexPath.row)
}

screenShot after edit button is tapped

A: The trouble is that canEditRowAt is a data source method. You (the view controller) are now not the data source; the diffable data source is. You need to implement this method inside the diffable data source. That's typically done by subclassing the diffable data source class, so that you can override this method. Otherwise, the diffable data source just returns its default value — which is false, which is why you currently can't edit any rows.


text:
Q: running portable python3 under wine Installing python under wine generally means running a graphical installer, but I don't have that option, so instead I download Windows x86-64 embedded zip file from Python 3.6.0 and unpack it.
However, when I run wine python.exe I get errors:
wine: Call from 0x7b83c3ae to unimplemented function api-ms-win-crt-runtime-l1-1-0.dll._initialize_onexit_table, aborting
err:module:attach_process_dlls "python35.dll" failed to initialize, aborting
err:module:LdrInitializeThunk Main exe initialization for L"Z:\\<path>\\python.exe" failed, status 80000100

What can be done about it? Wine version is 1.8.

A: Few users need to run Python under Wine, since Python works very well natively on all the systems that Wine works on. However, there are reasons to do it and it seems you have one (building a Windows installer with PyInstaller).
Some versions of Python certainly can run on some versions of Wine. Unfortunately, you've run into a combination that doesn't work.

What's happening
It looks like you're running into Bug #39437: "Visual Studio 2015-compiled C++ programs do not run".
The program you're running uses a function called _initialize_onexit_table from a library called api-ms-win-crt-runtime-l1-1-0.dll.
Wine provides its own version of api-ms-win-crt-runtime-l1-1-0.dll but it did not support the _initialize_onexit_table function until relatively recently (mid-2016). Wine 2.0 is the first Stable release that supports this function, although Development versions have supported it since 1.9.9.
Wine 2.0 will probably be released in the next couple of weeks, but release candidates are already available. Wine 2.0 was released a couple of weeks after this question was posted.
Can't upgrade Wine?
On a Windows computer, you'd be using Microsoft's version of that library. If you have a copy of Microsoft's version, you can configure Wine to use it instead of its builtin version.
You can use Wine's override system to achieve this (using winecfg or setting the WINEDLLPATH and WINEDLLOVERRIDES environment variables).
There is a project called Winetricks which can download Microsoft's libraries and configure your Wine to use them.
In conclusion
Upgrade your Wine version, or downgrade your Python version.
There are ways around it if you can't upgrade, but upgrading is probably your best option.


text:
Q: gwtp can't deserialize response Im grafting the code from the carstore example into my prototype app and having a strange problem.  I can't get the thing to deserialize the json response.
Heres the error:
com.gwtplatform.dispatch.shared.ActionException: Unable to deserialize response.
    at com.gwtplatform.dispatch.client.rest.RestResponseDeserializer.getDeserializedResponse(RestResponseDeserializer.java:60)
    at com.gwtplatform.dispatch.client.rest.RestResponseDeserializer.deserialize(RestResponseDeserializer.java:38)
    at com.gwtplatform.dispatch.client.rest.RestDispatchAsync$1.onResponseReceived(RestDispatchAsync.java:124)
    at com.google.gwt.http.client.Request.fireOnResponseReceived(Request.java:258)
    at com.google.gwt.http.client.RequestBuilder$1.onReadyStateChange(RequestBuilder.java:412)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessagesWhileWaitingForReturn(BrowserChannelServer.java:338)
    at com.google.gwt.dev.shell.BrowserChannelServer.invokeJavascript(BrowserChannelServer.java:219)
    at com.google.gwt.dev.shell.ModuleSpaceOOPHM.doInvoke(ModuleSpaceOOPHM.java:136)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNative(ModuleSpace.java:571)
    at com.google.gwt.dev.shell.ModuleSpace.invokeNativeObject(ModuleSpace.java:279)
    at com.google.gwt.dev.shell.JavaScriptHost.invokeNativeObject(JavaScriptHost.java:91)
    at com.google.gwt.core.client.impl.Impl.apply(Impl.java)
    at com.google.gwt.core.client.impl.Impl.entry0(Impl.java:242)
    at sun.reflect.GeneratedMethodAccessor246.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at com.google.gwt.dev.shell.MethodAdaptor.invoke(MethodAdaptor.java:103)
    at com.google.gwt.dev.shell.MethodDispatch.invoke(MethodDispatch.java:71)
    at com.google.gwt.dev.shell.OophmSessionHandler.invoke(OophmSessionHandler.java:172)
    at com.google.gwt.dev.shell.BrowserChannelServer.reactToMessages(BrowserChannelServer.java:293)
    at com.google.gwt.dev.shell.BrowserChannelServer.processConnection(BrowserChannelServer.java:547)
    at com.google.gwt.dev.shell.BrowserChannelServer.run(BrowserChannelServer.java:364)
    at java.lang.Thread.run(Unknown Source)
Caused by: com.google.gwt.user.client.rpc.SerializationException: com.google.gwt.json.client.JSONException: "[{"empno":0,"firstName":"Edith","lastName":"Fisher","reportsTo":0}]" represents invalid json data!
    at com.gwtplatform.dispatch.client.rest.JsonSerializer.deserialize(JsonSerializer.java:40)
    at com.gwtplatform.dispatch.client.rest.RestResponseDeserializer.getDeserializedResponse(RestResponseDeserializer.java:58)
    ... 29 more
Caused by: com.google.gwt.json.client.JSONException: "[{"empno":0,"firstName":"Edith","lastName":"Fisher","reportsTo":0}]" represents invalid json data!
    at name.pehl.piriti.json.client.AbstractJsonReader.read(AbstractJsonReader.java:226)
    at com.gwtplatform.dispatch.client.rest.JsonSerializer.deserialize(JsonSerializer.java:37)
    ... 30 more

My service interface:
@Path(ResourcesPath.JACKSON)
public interface EmployeeService extends RestService {
    /**
     * calls the get employees service.
     *
     * @param num
     * @return GetResults<Employee>
     */
    @GET
    Action<GetResults<Employee>> getEmployees(@QueryParam("num") Integer num);
}

The GetResults class:
public class GetResults<T extends Dto> implements Result {
    ArrayList<T> results;

    @SuppressWarnings("unused")
    protected GetResults() {
    }

    public GetResults(ArrayList<T> results) {
        this.results = results;
    }

    public ArrayList<T> getResults() {
        return results;
    }
}

the Dto class:
public interface Dto extends IsSerializable {
}

and my entity:
public class Employee implements Dto {

    public int empno;
    public String firstName;
    public String lastName;
    public String extension;
    public String eMail;
    public String officeCode;
    public int reportsTo;
    public String jobTitle;

    /**
     * The key provider that provides the unique ID of a contact.
     */
    public static final ProvidesKey<Employee> KEY_PROVIDER = new ProvidesKey<Employee>() {
        @Override
        public Object getKey(Employee item) {
            return item == null ? null : item.getEmpno();
        }
    };

    /**
     * Example of how to create an instance of a JsonEncoderDecoder for a data
     * transfer object.
     *
     * public interface EmployeeJED extends JsonEncoderDecoder<Employee> {
     *
     * }
     *
     * @param empno
     * @param firstName
     * @param lastName
     * @param extension
     * @param eMail
     * @param officeCode
     * @param reportsTo
     * @param jobTitle
     */
    public Employee(
            int empno,
            String firstName,
            String lastName,
            String extension,
            String eMail,
            String officeCode,
            int reportsTo,
            String jobTitle) {
        this.setEmpno(empno);
        this.setFirstName(firstName);
        this.setLastName(lastName);
        this.setExtension(extension);
        this.seteMail(eMail);
        this.setOfficeCode(officeCode);
        this.setReportsTo(reportsTo);
        this.setJobTitle(jobTitle);
    }

    public Employee(int empno, String firstName, String lastName, int reportsTo) {
        this.setEmpno(empno);
        this.setFirstName(firstName);
        this.setLastName(lastName);
        this.setReportsTo(reportsTo);
    }

and for good measure, my caller from the presenter
@Override
    protected void onReveal() {
        // ActionBarVisibilityEvent.fire(this, true);
        // ChangeActionBarEvent.fire(this, Arrays.asList(ActionType.ADD), true);

        dispatcher.execute(employeeService.getEmployees(1), new AbstractAsyncCallback<GetResults<Employee>>() {
            @Override
            public void onSuccess(GetResults<Employee> result) {
                getView().displaySearchGrid(result.getResults());
            }
        });

    }

and my module file:
<module rename-to='gwtptabsample'>
    <!-- Inherit rest dispatch stuff. Order matters here, rest needs to be before mvp -->
    <inherits name="com.gwtplatform.dispatch.DispatchRest" />
    <inherits name="com.gwtplatform.mvp.MvpWithEntryPoint" />

    <!-- GinUiBinder allows injecting widgets in UiBinder -->
    <inherits name="com.google.gwt.uibinder.GinUiBinder" />

    <!-- debugging
    <inherits name="com.google.gwt.logging.Logging"/>
    <inherits name="com.google.gwt.user.Debug"/>
    <set-property name="gwt.logging.logLevel" value=INFO/>
    <set-property name="gwt.logging.enabled" value="TRUE"/> -->

    <!-- Inherit the default GWT style sheet. You can change -->
    <!-- <inherits name='com.google.gwt.user.theme.standard.Standard'/> -->
    <!-- <inherits name='com.google.gwt.user.theme.chrome.Chrome'/> -->
    <inherits name="com.google.gwt.user.theme.dark.Dark" />

    <!-- Specify the paths for translatable code -->
    <source path="client" />
    <source path="shared"/>

    <extend-configuration-property name="gin.ginjector.modules"
        value="com.gwtplatform.samples.tab.client.gin.ClientModule" />

    <set-configuration-property name="gin.ginjector.extensions"
        value="com.gwtplatform.samples.tab.client.gin.GinjectorExtension" />
</module>

The number in the parameter is just telling my service how many random employees to generate.  I get the same error if i call one result or multiple.  Again, this is based on the model that is used in the CarStore example in the GWTP source tree.  Any ideas why this isn't working?


text:
Q: Creating shortcut for Firefox add-on options I want to easily switch how Firefox works, using an Add-on feature either toggled on or off, based on which one of us is using a particular computer. Currently, to toggle that, we are having to do this tedious sequence each time:

*

*Tools

*Add-ons*

*Options (of the add-on I need)

*Uncheck checkbox to toggle the thing I wanted to toggle.

*Click OK

*Close the tab that was opened

(*And yes, I know I can get to 3 by either Ctrl+Shift+A or putting a favorite in the favorites bar to the Add-ons Manager screen...but even steps 3-6 are still tedious enough.)
Instead, what I'd love to have is either (best) an icon in the menu bar that can indicate the toggle state of that option--a helpful reminder--and that you can click on to toggle it, OR a simple shortcut key sequence I can assign, or both.
Is it reasonably possible to do that?


text:
Q: How to remove same session value for different sessions? I received an error from the Security testing team as follows:
It was observed that same session value is used for different sessions. After logout, session value should be cleared and the user should be provided a new session value every time user logs in.
It was observed that every time user login the session value was set to the following value "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
How to rectify this? What would be the best approach to avoid these kind of issues?

A: ASP.NET does not always give a unique session ID.  If no data is written to the session, ASP.NET may reuse the ID.
Here is an article explaining this: http://weblogs.asp.net/bsimser/archive/2004/09/13/228713.aspx
I would advise working with the sec. team to try to get a replicable (simple) example of when this occurs to identify why the session Ids are being reused.
Check for trends such as web browser, time logged in etc.

A: Check this out : Setting the Login Token Expiration Correctly for SharePoint 2010 SAML Claims Users


text:
Q: Blitting an image directly on top of another image in pygame So I am trying to make a space-invaders game, and decided to have a missile weapon that would have a trigger. If you didn't hit the trigger, whatever alien it hit died and nothing else. If you do trigger it, the code would teleport the missile away and replace it with an explosion image. anything within the image would die. However, while the detonation button works and only one alien dies when it doesn't detonate, the detonation does not summon the explosion image, or do anything to the aliens. The missile just disappears and plays the detonation noise.
This is my code:
import pygame
from pygame import mixer
import random
import math
import time

pygame.init()

screen = pygame.display.set_mode((800, 600))
explosion_Sound = mixer.Sound('explosion.wav')

background = pygame.image.load('Background.jpg')
background = pygame.transform.scale(background, (800, 600))

mixer.music.load('background.wav')
mixer.music.play(-1)

pygame.display.set_caption("Space Invaders")
icon = pygame.image.load('ufo.png')
pygame.display.set_icon(icon)

playerImg = pygame.image.load('spaceship.png')
playerX = 370
playerY = 480
playerX_change = 0

enemyImg = []
enemyX = []
enemyY = []
enemyX_change = []
enemyY_change = []
num_of_enemies = 6

for i in range(num_of_enemies):
    enemyImg.append(pygame.image.load('ufo.png'))
    enemyX.append(random.randint(0, 750))
    enemyY.append(random.randint(50, 200))
    enemyX_change.append(0.5)
    enemyY_change.append(40)

bulletImg = pygame.image.load('bullet.png')
bulletX = 0
bulletY = 480
bulletX_change = 0
bulletY_change = 1
bullet_state = "ready"

missileImg = pygame.image.load('missile.png')
missileX = 0
missileY = 0
missileX_change = 0
missileY_change = 0.7
missile_state = "ready"

explosionImg = pygame.image.load('explosion.png')
explosionX = missileX
explosionY = missileY
explosionX_change = 0
explosionY_change = 0
explosion_state = "ready"

score_value = 34
font = pygame.font.Font('freesansbold.ttf', 32)

textX = 10
textY = 10

over_font = pygame.font.Font('freesansbold.ttf', 64)

level_up_font = pygame.font.Font('freesansbold.ttf', 64)

instructions = pygame.font.Font('freesansbold.ttf', 32)

def missile_instructions():
    instruction = instructions.render("Press the M key to shoot missile", True, (255, 255, 255))
    screen.blit(instruction, (200, 350))

def show_score(x,y):
    score = font.render("Score : " + str(score_value), True, (255, 255, 255))
    screen.blit(score, (x,y))

def game_over_text():
    over_text = over_font.render("GAME OVER", True, (255, 255, 255))
    screen.blit(over_text, (200, 250))

def level_up():
    levelup_text = level_up_font.render("LEVEL UP!", True, (255, 255, 255))
    screen.blit(levelup_text, (200, 250))

def player(x,y):
    screen.blit(playerImg,(x, y))

def enemy(x,y, i):
    screen.blit(enemyImg[i],(x,y))

def fire_bullet(x,y):
    global bullet_state
    bullet_state = "fire"
    screen.blit(bulletImg,(x + 16, y + 10))

def fire_missile(x,y):
    global missile_state
    missile_state = "fire"
    screen.blit(missileImg, (x + 16, y + 10))

def explosion(x,y):
    global explosion_state
    explosion_state = "fire"
    screen.blit(explosionImg, (x,y))

def create_enemies(new_enemies):
    global num_of_enemies
    enemy_image = pygame.image.load('ufo.png')
    for i in range(new_enemies):
        enemyImg.append(enemy_image)
        enemyX.append(random.randint(0, 750))
        enemyY.append(random.randint(50, 200))
        enemyX_change.append(0.5)
        enemyY_change.append(40)
    num_of_enemies += new_enemies

def isCollision(enemyX, enemyY, bulletX, bulletY):
    distance = math.sqrt((math.pow(enemyX-bulletX,2)) + (math.pow(enemyY-bulletY,2)))
    if distance < 27:
        return True
    else:
        return False

def isCollision2(enemyX, enemyY, missileX, missileY):
    distance2 = math.sqrt((math.pow(enemyX-missileX,2)) + (math.pow(enemyY-missileY,2)))
    if distance2 < 27:
        return True
    else:
        return False

def isCollision3(enemyX, enemyY, explosionX, explosionY):
    distance3 = math.sqrt((math.pow(enemyX-explosionX,2)) + (math.pow(enemyY-explosionY, 2)))
    if distance3 < 128:
        return True
    else:
        return False

running = True
while running:

    screen.fill((0, 0, 0))

    screen.blit(background,(0,0))

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
            running = False

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_LEFT:
                playerX_change = -1
            if event.key == pygame.K_RIGHT:
                playerX_change = 1
        if event.type == pygame.KEYUP:
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                playerX_change = 0
            if event.key == pygame.K_SPACE:
                if bullet_state == "ready":
                    bullet_sound = mixer.Sound('laser.wav')
                    bullet_sound.play()
                    bulletX = playerX
                    fire_bullet(bulletX,bulletY)
            if event.key == pygame.K_m:
                if score_value >= 35:
                    if missile_state == "ready":
                        missile_sound = mixer.Sound('laser.wav')
                        missile_sound.play()
                        missileX = playerX
                        fire_missile(missileX,missileY)
            if event.key == pygame.K_n:
                if score_value >= 35:
                    if missile_state == "fire":
                        explosion_state = "fire"
                        explosion_Sound.play()
                        explosionX = missileX
                        explosionY = missileY
                        missile_state = "ready"
                        missileX = bulletX
                        missileY = bulletY

    playerX += playerX_change

    if playerX <= 0:
        playerX = 0
    elif playerX >= 768:
        playerX = 768

    for i in range(num_of_enemies):

        if enemyY[i] > 440:
            for j in range(num_of_enemies):
                enemyY[j] = 2000

            game_over_text()
            break

        enemyX[i] += enemyX_change[i]
        if enemyX[i] <= 0:
            enemyX_change[i] = 0.5
            enemyY[i] += enemyY_change[i]
        elif enemyX[i] >= 768:
            enemyX_change[i] = -0.5
            enemyY[i] += enemyY_change[i]

        collision = isCollision(enemyX[i], enemyY[i], bulletX, bulletY)
        if collision:
            explosion_Sound.play()

            bulletY = 480
            bullet_state = "ready"
            score_value += 1
            print(f"score = {score_value}")
            enemyX[i] = random.randint(50, 768)
            enemyY[i] = random.randint(50, 200)

        collision2 = isCollision2(enemyX[i], enemyY[i], missileX, missileY)
        if collision2:
            explosion_Sound = mixer.Sound('explosion.wav')
            explosion_Sound.play()
            missileY = 480
            missile_state = "ready"
            score_value += 1
            print(f"score = {score_value}")
            enemyX[i] = random.randint(50, 768)
            enemyY[i] = random.randint(50, 200)

        enemy(enemyX[i], enemyY[i], i)

    if bulletY <= 0:
        bulletY = 480
        bullet_state = "ready"
    if bullet_state == "fire":
        fire_bullet(bulletX,bulletY)
        bulletY -= bulletY_change

    if missileY <= 0:
        missileY = 480
        missile_state = "ready"
    if missile_state == "fire":
        fire_missile(missileX, missileY)
        missileY -= missileY_change

    player(playerX, playerY)

    show_score(textX, textY)

    if score_value == 20:
        create_enemies(4)
        score_value += 1
    if score_value == 21:
        level_up()

    if score_value == 35:
        level_up()
        missile_instructions()

    if score_value == 50:
        create_enemies(5)
        score_value += 1
    if score_value == 51:
        level_up()

    pygame.display.update()

I don't receive any error messages, and the game doesn't crash, it simply continues as if the missile was never there, and the missile is also available for use as soon as it has been detonated.


text:
Q: Why does parahydrogen have a lower energy than orthohydrogen? I found this on the wikipedia page on spin isomers of hydrogen:

Parahydrogen is in a lower energy state than is orthohydrogen.

It seem almost like it is obvious but I am having trouble reasoning it out.
Does it have to do with some magnetic dipole coupling?
Is the difference in energy explained by the exchange energy?

A: I dont think we should consider the energy of the electrons. For both para- and ortho- hydrogens, the two electrons are sitting in the same ground state molecular orbital of the hydrogen molecule, so I dont think there is a difference.
The energy of a hydrogen molecule arises from its translational, rotational and vibration kinetic energy. At room temperatures, the vibrational kinetic energies are "frozen out", while the translational kinetic energy of ortho- and para- hydrogen are more or less equal. So we'll consider only the rotational kinetic energy.
According to this:

The lowest parahydrogen level is lower than the lowest orthohydrogen level by $\Delta E / k_b \simeq 175 K$

This suggests that there are actually many energy levels of parahydrogen and orthohydrogen. When that wikipedia statement was comparing energy levels, it was probably referring to the lowest energy levels.
But why is the lowest parahydrogen energy level lower than the lowest orthohydrogen energy level?... Because the parahydrogen can reach a lower energy rotational state than orthohydrogen!
To understand this, first, frame the problem as a quantum rigid rotor. Next, realize that the wavefunction solution must be antisymmetric under particle exchange because the wavefunction describes two identical fermions (the hydrogen nuclei).
Now, wash away the idea that we are dealing with two nuclei and focus on the wavefunction.
The wavefunction consists of two parts: the spin part and the spatial part. If the spatial part is antisymmetric, the spin part must be symmetric, in which case we call the molecule a orthohydrogen. If the spatial part is symmetric, the spin part must be antisymmetric, in which case we call the molecule a parahydrogen.
The rotational hamiltonian is
$$\hat{H} = \frac{\hat{\mathbf{J}}^2}{2I}$$
The wavefunction solutions are the spherical harmonics $Y_{J,M}$, and the energy eigenvalues are
$$ E_J = \frac{\hbar^2J(J+1)}{2I}$$
with a degeneracy of $2J+1$
(I used to think that spherical harmonics are amplitudes of an electron around a nucleus. But now that they are used to represent two rotating particles surprised me.)
The lowest energy spherical harmonic is the $J=0$ state, which is symmetric, followed by the $ J = 1,2,3...$ states. So the lowest energy level will be a parahydrogen, followed by a orthohydrogen, then a parahydrogen....
PS: I am answering my own question, so there is a high chance I got something wrong

A: The average separation of the electrons (integrated over time) in parahydrogen state is more than the average separation of the electrons in orthohydrogen state. And whenever electrons are away from each other, by nature, they would feel less Coulomb force and hence a lower energy state. This handwaving explanation can be justified in quantum mechanics more rigorously.

A: This can also be understood in terms of the Pauli exclusion principle, according to the practice physics GRE answer key.


text:
Q: Formatar array de datas Tenho uma aplicação Laravel com o seguinte código:
private function todosRegistros($id, $colunas = ['data', 'nivel'])
{
    return Leitura::select($colunas)->where('estacao_id', $id);
}

public function _24horas($estacao_id)
{
    return $this->todosRegistros($estacao_id)
        ->where('data', '>', Carbon::now('America/Sao_Paulo')
            ->subDay())->get();
}

Ao executar o método _24horas recebo um array com o valor dos níveis e a data de cadastro correspondente.
Acontece que a data retornada vem no formato americano (YYYY-mm-dd) e gostaria que viesse no formato brasileiro (dd/mm/YYYY). Usando Carbon::parse consigo modificar data a data no array mas gostaria de uma alternativa onde modifico todas de uma vez. Alguém tem ideia de como fazer isso?
Obrigado.

A: Da maneira mais simples, faria um appends e um método para esse campo destinado a pegar a data e passar para formato d/m/Y H:i:s (ou d/m/Y), exemplo:
Model
<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Leitura extends Model
{

    protected $fillable = ['name'];

    protected $appends = ['created_at_br'];

    public function getCreatedAtBrAttribute()
    {
        $value = date_create($this->attributes['created_at']);
        if ($value)
        {
            return $value->format('d/m/Y H:i:s');
        }
        return null;
    }
}

ou seja, nesse exemplo no array de appends foi inserido o nome created_at_br e foi também criado um acessor com o nome getCreatedAtBrAttribute sendo que o get significa resgatar o valor e o nome do appends com as iniciais em maiusculos e por fim Attribute no final, que é o padrão para métodos acessor.
Após fazer a pesquisa observe o exemplo:
>>> App\Models\Leitura::find(1)->toArray()
=> [
     "id" => 1,
     "name" => "Stackoverflow",
     "created_at" => "2018-10-17 20:25:32",
     "updated_at" => "2018-10-17 20:25:32",
     "created_at_br" => "17/10/2018 20:48:18",
   ]

Nesse exemplo os dados obtidos não interferem naqueles que fazem relação com a base de dados, não atrapalham os formatos que é utilizado por exemplo em um CRUD.
Referencia: Eloquent: Serialization - Appending Values To JSON

No seu caso poderia ser:
protected $appends = ['data_br'];

public function getDataBrAttribute()
{
    $value = date_create($this->attribue['data']);
    if ($value)
    {
        return $value->format('d/m/Y H:i:s');
    }
    return null;
}

Se o seu banco for MySQL uma outra solução é na SQL:
Leitura::select(\DB::raw("date_format(`data`,'%d/%m/%Y'),`nivel`"))
       ->where('estacao_id', $id)
       ->get();


text:
Q: Flutter Search bar not refreshing the initial list i'm having a little trouble in getting back the initial list in my app, after searching an item.
I have a list car and i'm using code from tutorials, if i let the text in the formfield and change tabs, when i back the filter continues and the bar is empty.
I already tried 100 forms and keeps getting the same result.
Here's parts of the code.
List<Car> car = cars;
final _pesquisaController = TextEditingController();

I have a default textformfield with this controller above and a onchange calling the method below.
  void pesquisarCarro(String query) {
var carrosPesquisados = {
  ...car.where(
    (cars) {
      var nomedoCarro = cars.nomeCarro.toLowerCase();
      var input = query.toLowerCase();

      return nomedoCarro.contains(input);
    },
  ),
  ...car.where(
    (cars) {
      var codigodoCarro = cars.codigo.toLowerCase();
      var input = query.toLowerCase();

      return codigodoCarro.contains(input);
    },
  )
}.toList();

setState(
  () {
    cars = carrosPesquisados;
  },
);

}
Already tried putting the list on the initState but not work, can someone give me a light?
Like said, the search filters perfectly, the problem is when i let text in the form and change tabs in the bottomtabbar.

A: is your problem is initial value always empty?
@override
  void initState() {
    onInit();
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((callback) {
      // set your list here
    });
  }


text:
Q: TYPO3 Powermail double opt-in for newsletter only I've got a contact form. In this form I want to add a "newsletter Opt-In".
This Opt-In has to be double opt-in.
The Problem:

*

*I can set double opt-in

*Once this is set, the whole form becomes double opt in

*

*The user has to confirm the form, not the newsletter opt in

*Only when the user confirms the form, the contact form mail is sent

So obviously this is the wrong behaviour. I want the formdata to be sent immediately, but a second mail for the newsletter opt-in.

A: As far as I remember the TypoScript setup plugin.tx_powermail.settings.setup.main.optin=1 or =0 will enable or disable Optin in powermail.
Together with a condition where you listen to a GET/POST if a checkbox is set, you can enable or disable it.

A: I only know of a solution for the following behaviour:
If the user does not check the Option checkbox, the formdata will be sent immediately to the receiver. If the Optin checkbox is checked, the formdata won't be sent before the user confirms the email. After confirmation the email with the formdata (containing the fielddata newslettersubscription = 1) will be sent to the receiver.
You can use a typoscript condition to check if the newsletter Opt-In checkbox was checked. If the markername of your checkbox is for example newslettersubscription you could use the follwing condition in your typoscript setup.
#disable option
plugin.tx_powermail.settings.setup.main.optin = 0
#enable option if option checkbox is checked
[globalVar = GP:tx_powermail_pi1|field|newslettersubscription|0 > 0]
  plugin.tx_powermail.settings.setup.main.optin = 1
[end]

For this to work you have to setup your form with the following settings.

*

*"Double Optin" must not be set in the flex form settings

*Within the tab "Mail to User" the fields "Sender Name" and "Sender Email" have to be filled

*Your checkbox has to use the markername newslettersubscription


text:
Q: How i can achive the best sensitivity for the user location? I'm writing an app that take (after user approvation) the user position form 5 minutes and then write a path over a map. I'm using Standard Location services
if (nil == locationManager)

 locationManager = [[CLLocationManager alloc] init];

locationManager.delegate = self;
locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;

[locationManager startUpdatingLocation];

In my paths i see some "accurancy mistake", so my question is, how i can achive the best result in sensitivity from user location? There's a way to communicate with phone gps outside the CLLocationManager (naturally i don't think so...)?

A: You could set the locationManager's desiredFilter member to a suitable distance as per your requirement.
locationManager.desiredFilter = 200;//200mtr

This can be used in conjunction with "startMonitoringForRegion" api, where you can define an geo fencing region depending on the kind of accuracy you are looking for and get notified when the user crosses over the region.


text:
Q: Simulating the C++ Command-Line Parameters with Variables I'm trying to convert a C++ source code to dll . For this I change wmain to MyMethod and change the Configuration Type of this source into a Dynamic Library (.dll) .
Now MyMethod is like :
int MyMethod(int argc, wchar_t* argv[])
{    }

After this I pass args to this file like :
   MyFile.exe -a arg1 -b "arg2"

Now I want to do the same way into dll manually so as someone describes here I change my code to :
  int MyMethod(int argc, wchar_t* argv[])
{
    int argc1 = 2;
    wchar_t *argv1[2] = { L"-a arg1",L"-b arg2" };
    argc = argc1;
    argv = argv1;
}

But the above code doesn't have the same effects as Command-Line.
What makes this code wrong ?!(I mean do the command-line assign variables something different ?)
Update 1 :
My wmain method is :
    int wmain(int argc, wchar_t* argv[])
    {
        int argc1 = 3;
        wchar_t *argv1[3] = { L"" , L"-a arg1",L"-b arg2" };

        argc = argc1;
        argv = argv1;

        if (!ArgTranslate(argc, argv))
        {
            MessageBoxA(0, "Error", "Not valid args", 0);
            return -1;
        }
    MessageBoxA(0, "Valid", "It is valid", 0);
    return 0;
}

bool ArgTranslate(int argc, wchar_t* argv[])
{

    wchar_t* Parm1= NULL;
    wchar_t* Parm2= NULL;

    for (int i = 1; (i < argc) && ((i + 1) < argc); i += 2)
    {
        if (wcscmp(argv[i], L"-a") == 0)
            Parm1 = argv[i + 1];
        else if (wcscmp(argv[i], L"-b") == 0)
            Parm2 = argv[i + 1];
    }
    if (Parm1 == NULL || Parm2 == NULL)
        return false;
    else
    return true;
}

A: The first parameter to the main function is the name of the executable itself.
From cppreference:

argv[0] is the pointer to the initial character of a null-terminated multibyte strings that represents the name used to invoke the program itself (or an empty string "" if this is not supported by the execution environment)

If it's not used, you can just provide an empty string - so in your case you will have argc1 = 3 and argv1[3] = {L"", L"-a arg1",L"-b arg2" };

Edit
I provided the simple fix in the comments. Here's a version which is slightly closer to C++11 and also doesn't use the unnecessary temporaries and assignment to main's arguments
#include <array>

bool ArgTranslate(int argc, wchar_t const* argv[])
{
    wchar_t const* Parm1 = nullptr;
    wchar_t const* Parm2 = nullptr;

    for (int i = 1; (i + 1) < argc; i += 2)
    {
        if (wcscmp(argv[i], L"-a") == 0)
            Parm1 = argv[i + 1];
        else if (wcscmp(argv[i], L"-b") == 0)
            Parm2 = argv[i + 1];
    }
    if (!Parm1 || !Parm2)
        return false;
    else
        return true;
}

int wmain(int argc, wchar_t* argv[])
{
    std::array<wchar_t const*, 5> args{L"" , L"-a", L"arg1", L"-b",  L"arg2"};

    if (!ArgTranslate(static_cast<int>(args.size()), args.data()))
    {
        MessageBoxA(0, "Error", "Not valid args", 0);
        return -1;
    }
    MessageBoxA(0, "Valid", "It is valid", 0);
    return 0;
}


text:
Q: select element inside an arraylist and swap to the next element and previous element My doubt is how to select an element in an ArrayList so that I can swap with the next element in the case I want to move the element down and swap to the previous element in the case, move the item up.
public class ShapesFX{

        private ArrayList <Shape> shapes;

        public ShapesFX() {
            this.shapes= new ArrayList <> ();
    }

  / **
     * Swap positions with the immediate previous element. The method can not
     * Be successful if the reference element is the last.
     *
     * @ Param element element reference to the exchange
     * @ Return true if the exchange was successful. false, d.c.
     * @ Throws Exception if the element does not exist
     * /

    @ Override
    public boolean moveUP (Shape element) throws Exception {
        if (element != null) {
            throw new Exception ("Element does not exist");
        } else if (element != Null) {
            for (FormaGeometrica sh : this.shapes) {
                if (sh == element) {
                    Collections.swap ((List<Shape>) element, 0, 0);
                }
            }
            return true;
        }
        return false;
    }

  / **
     * Swap positions with the next immediate element. The method can not
     * Be successful if the reference element is the first.
     *
     * @ Param element element reference to the exchange
     * @ Return true if the exchange was successful. false, d.c.
     * @ Throws Exception if the element does not exist
     * /

    @ Override
    public boolean moverDown (Shape element) throws Exception {
        if (element != null) {
            throw new Exception ("Element does not exist");
        } else if (element != Null) {
            for (Shape sh : this.shapes) {
                if (sh == element) {
                    Collections.swap ((List<Shape>) element, 0, 0);
                }
            }
            return true;
        }
        return false;
    }

and if this methods is correctly, one example of the output is
--- List of Figures ---
F1
F2
F3
F4

--- Move F2 UP ---
F2
F1
F3
F4

F2 change position with F1

--- Move F3 DOWN ---
F2
F1
F4
F3

F3 change position with F4


text:
Q: Hotmail Folders Is there a linux mail client I can use that will let me see my folders in Hotmail and persist the changes back to the server? Kind of like the Hotmail connector for Outlook, or Windows Live Mail?
I'm using openSuse and KDE desktop, with Gnome application support.

A: Thunderbird and http://webmail.mozdev.org/setup.html.
see this for the same question.

A: Doesn't any IMAP client do that?
Edit: Whoops, I'm sorry, it looks like Hotmail doesn't support that (at least for any client except their own Outlook). Maybe trying to protect their investments?
According to this site, however, you can get the features of IMAP on your iPhone or iPod. Email tutorial: Hotmail At least that's something.


text:
Q: How to disable Java's SSL Reverse DNS Lookup I have a server in development and a few developers connecting to it.
This server uses Java's TLS implementation with SSLEngine.
We saw that, at first, every new connection would have a long delay (30-40 seconds). We narrowed it down to reverse DNS lookups timing out. We solved that by putting all our IPs in the HOSTS file.
Now, the problem is that we are going to widen progressively our user base and I don't want to edit the HOSTS file, especially since we can't guarantee that they're going to have static IPs.
Is there any way to disable the reverse DNS lookup step in Java's SSL/TLS?
I'd like to have this as a configurable parameter, so that we can turn it off during development.

A: This question came up in 2006 on the Sun JSSE forums. The bottom line is that it seems to occur only in the Windows java runtime. In this bug report, towards the bottom, is one proposed solution. And here is another proposed solution:

Basically, a reverse DNS lookup during the SSL handshake causes a long
  timeout.
To fix the problem, cache your server address as an InetAddress object
  and reuse it in the Socket constructor whenever you are making a new
  connection to your server.

Hopefully one of these will work for you.

A: I faced this same problem today when I tried to create a SSL socket connection by IP address only. That resulted in reverse DNS lookup attempt, and therefore it was really slow...
To me the solution was simply to pass a dummy empty string as the host name, when creating the InetAddress for the SSL connection. That is, I changed
InetAddress.getByAddress(addrBytes)

to
InetAddress.getByAddress("", addrBytes)

and it no longer does the reverse DNS lookup.

A: Ari's solution of passing an empty hostname to the InetAddress worked for connecting to a single host, but it had some side effects when connecting to multiple hosts by IP address. Java caches the SSLSession object using the tuple <remote-hostname, port>. This can be seen in the OpenJDK here. Thus, TLS settings for a previous connection (specifically TLS protocol version in my case), were applied to a new connection to a different host (since both shared the same empty hostname). In my case, the new host rejected the downgraded TLS v1 protocol negotiated by the previous host, causing TLS handshake errors.
The solution was to construct a unique hostname based on the remote IP address instead like so:
String hostname = String.format("host-%s", BaseEncoding.base16().encode(address.getAddress()));
InetAddress newAddress = InetAddress.getByAddress(hostname, address.getAddress());

Thus the reverse DNS lookup Java performs was disabled, but cached TLS settings to remote hosts were only applied to the same remote host and port without the crosstalk effect.


text:
Q: Check internet connection with Connectivity I want to check the internet connection through out my application in following manner:

A: here is the exactly what you are looking for https://pub.dartlang.org/packages/flutter_offline


text:
Q: The cellClass property defined in columnDefinitions is not working I'm using ag-grid with no frameworks. The cellClass property defined in columnDefinitions is not working. I defined a function as shown below, but it is never called. I tested it in ag-grid-react and it was working fine.
cellClass: function (params) {
        console.log(params)
        if (params.colDef.colId === "") {
          return "border-top";
        }
        if (params.value === undefined) {
          return "border-right";
        }
      }


text:
Q: If the n-body problem is chaotic, why isn't it used as a RNG? I'm probably missing something pretty basic here, but if the n-body problem yields chaotic results (except in specific highly-symmetric conditions), couldn't it be used as a "true" random number generator (with initial pseudo-random seeds for masses and velocities) given its non-deterministic nature?

A: It's still deterministic, because the outcome is directly based on the inputs - same inputs, same output. Thus, it's no more random than whatever randomness you use for your inputs.

A: Just because a system is nondeterministic doesn't make it a useful source of random numbers, it would be nontrivial to extract such a source from a n-body solver. In addition with the same input you would get the same output, so this would still be pseudorandom at best.


text:
Q: Convert to polar and evaluate I have
$$z= x^2 + y^2$$
$$z=2x$$
I set them equal to get their intersection,
I get
$$2x= x^2 + y^2$$
$$0= x^2 -2x +y^2$$
by completing square I get
$$y= \pm \sqrt{1-(x-1)^2}$$
I need to put this into polar coordinates and then evaluate the integral. I was trying to shift back to the origin.

A: Your circle is centered at $(1,0)$ and radius $1$ .Put $x=r\cos \theta$ and $y=r\sin \theta$ in your equation of circle .You will get $r$ bounds from there .Your $\theta$ bounds will be from $-\dfrac{\pi}{2}$ to $\dfrac{\pi}{2}$ since your circle lies in $1$st and $4$th quadrant.No need to shift origin

For further help, you can refer this playlist. Lecture 8 and 9 contains multiple integration


text:
Q: what's wrong with my class definition? Why won't this class compile?
class Exam {

private int score;

    // constructor initializes score to 99
    public  void Exam() {
        score = 99;
    }

    // returns the current value of score
    private int getScore() {
       return score;
    }

    // returns the String representation of the Object
    public String toString() {
        return "The score is " + getScore();
    }
}

A: Your constructor shouldn't have a return type. Not even void.
public Exam() {
    score = 99;
}

A: A construct should not contain the void keyword:
public Exam() {
    score = 99;
}

A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.

A: Constructors don't need return types.  Remove void and you should be set.

A: In a constructor you don't use void.
Write the constructor as:
public Exam() {
    score = 99;
}

A: The main problem is the missing package declaration.
package yourpkg;

class Exam {

Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.

A: Just a suggestion not related to the concrete problem:
private int score;

// returns the current value of score
private int getScore() {
   return score;
}

There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the @Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
@Override
public String toString() {
    return "The score is " + getScore();
}


text:
Q: Does FileVault encrypt my BootCamp partition? If I enable the new FileVault feature in Mac OS X Lion, will it also encrypt my existing Windows bootcamp partitions? (And/or any new bootcamp partition I create?)
Update: If not, where can I get information about using FileVault and BootCamp? I'm looking for info on how to enable FileVault 2 with an existing BootCamp installation, and also for creating a BootCamp installation after FileVault 2 is already installed.

A: No, Windows does not support FileVault (so it would not boot if it was encrypted thus!) The Windows option would be BitLocker.
(perhaps it is more correct to say FileVault does not support anything but Mac OS Extended (Journaled) partitions)
If you need a great, free, cross-platform, open-source, strong encryption tool check out VeraCrypt.
Can you use FileVault on your Mac OS X partition and BitLocker on your Boot Camp Windows partition at the same time?
Theoretically it should be fine but I don't think I would do it for two reasons.

*

*There are quite a few mentions (if you google) of the Boot Camp partition failing to boot if FileVault isn't enabled in a very specific way. That could be from early FileVault and everything might be fine now but it makes me nervous enough. If you do it clone your drive first.

*It's really useful to be able to share information between operating systems. If you have both encrypted using a method the other can't handle you lose that ability. However, if you use VeraCrypt, you can host a partition file on either OS and access it from both, and mount it as required - as well as back it up, archive it etc. If you're worried about encryption strength, VeraCrypt is also the better option as you can configure it for truly paranoid security. I also like the thought that crypto experts are able to look at the source and would have blown the whistle on it by now if it claimed to be something which it was not.

A: I documented how to enable Bitlocker on Bootcamp (and I have FV2 enabled too) here: Enabling BitLocker without TPM on MacBook Pro with Bootcamp


text:
Q: Require verification of both email and phone If a user provides both an email and phone, I need to require both to be verified. It looks like there isn't a way to do this without extra steps as described here
https://docs.aws.amazon.com/cognito/latest/developerguide/user-pool-settings-email-phone-verification.html
Is there a way to require both verifications?
Currently it looks like I have to wait for phone number to be verified, verify phoneNumbber first. After that call initiateAuth to get an access token to retrieve the userInfo and check if email needs verification, and send verification code out. From testing I saw that email verification does not block the initiateAuth request so a getUser request would need to be made before every initiateAuth request to see if verification is needed and not return an access token if email still needs verification.

A: I am on the Cognito team. The scenario described is not possible at this point (requiring email and phone number verification before sign in). If both phone number and email require verification, if a phone number is present in the user attributes, the verification code is sent to the phone number, it is prioritized. Also, the calls to verifyUserAttribute which would enable you to verify email require an AccessToken to mark email as verified.

A: Unfortunatelly, Cognito will only send you an email verification link if you do not provide a phone number when registering. If you provide an empty phone number property value, and a valid email address, in this case it'll send the email.
This is really awful, because SMS messages sometimes don't reach the endpoint in real time.

A: If you want to verify the two contact methods in the registration flow for example, you could do this (you must have your own otp verification flow for example):

*

*Create the user with admin powers without notifying the user of the registration

https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-create-user.html
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminCreateUser.html
aws cognito-idp admin-create-user --user-pool-id us-east-2_fggdfg --username 117979111  --user-attributes Name=email,Value=calderonr.robinson@gmail.com Name=phone_number,Value="+5732085654" Name=custom:id,Value="1179791" Name=name,Value="Robinson C" --message-action SUPPRESS

(This can be programmed after the otp verification that you develop)

*Then assign the password to be confirmed

https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-set-user-password.html
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminSetUserPassword.html
aws cognito-idp admin-set-user-password --user-pool-id us-east-2_fggdfg --username 117979111 --password "loquesea" --permanent

*Assigns as true the contact method that was verifying

https://docs.aws.amazon.com/cli/latest/reference/cognito-idp/admin-update-user-attributes.html
https://docs.aws.amazon.com/cognito-user-identity-pools/latest/APIReference/API_AdminUpdateUserAttributes.html
aws cognito-idp admin-update-user-attributes --user-pool-id us-east-2_fggdfg --username 117979111 --user-attributes Name="email_verified",Value="true"

You can do all this perfectly with the aws SDK 2


text:
Q: PHP: get next 13 dates from date? I am trying to get an array of a date plus the next 13 dates to get a 14 day schedule starting from a given date.
here is my function:
$time = strtotime($s_row['schedule_start_date']); // 20091030
$day = 60*60*24;
for($i = 0; $i<14; $i++)
{
    $the_time = $time+($day*$i);
    $date = date('Y-m-d',$the_time);
    array_push($dates,$date);
}

But it seems to be repeating a date when the month switches over..
this is what I get:

2009-10-30|2009-10-31|2009-11-01|2009-11-01|2009-11-02|2009-11-03|2009-11-04|2009-11-05|2009-11-06|2009-11-07|2009-11-08|2009-11-09|2009-11-10|2009-11-11

Notice that 2009-11-01 is repeated. I cannot figure out why?
What am I doing wrong?
Thanks!!

A: You have the same date because of daylight saving time switch. It's not safe to add 24*60*60 seconds to find next day, because 2 days in the year have more/less seconds in them. When you switch from summer to winter time you are adding 1 hour to a day. So it'll be 25*60*60 seconds in that day, that's why it's not switched in your code.
You can do your calculation by mktime(). For example:
## calculate seconds from epoch start for tomorrow
$tomorrow_epoch = mktime(0, 0, 0, date("m"), date("d")+1, date("Y"));
## format result in the way you need
$tomorrow_date = date("M-d-Y", $tomorrow_epoch);

Or the full version for your code:
$dates = array();
$now_year = date("Y");
$now_month = date("m");
$now_day = date("d");
for($i = 0; $i < 14; $i++) {
    $next_day_epoch = mktime(0, 0, 0, $now_month, $now_day + $i, $now_year);
    array_push(
        $dates,
        date("Y-m-d", $next_day_epoch)
    );
}

A: I would use strtotime
$start = strtotime($s_row['schedule_start_date']);
$dates=array();
for($i = 1; $i<=14; $i++)
{
    array_push($dates,date('Y-m-d', strtotime("+$i day", $start)));
}
print_r($dates);

A: I recommend something like:
for($i=1;$i<=14;$i++){
     echo("$i day(s) away: ".date("m/d/Y",strtotime("+$i days")));
}


text:
Q: Lightdm display-setup-script with if-else-construct To configure my displays for lightdm, I use the display-setup-script option in /etc/lightdm/lightdm.conf
If I point it to an actual script
if xrandr | grep -q "HDMI-1 connected"; then
    xrandr --output eDP-1 --mode 1920x1080 --output HDMI-1 --mode 1920x1080 --same-as eDP-1
else
    xrandr --output eDP-1 --mode 1920x1080
fi

it works just fine.
But if I use a one-liner like
display-setup-script=if xrandr | grep -q "HDMI-1 connected"; then xrandr --output eDP-1 --mode 1920x1080 --output HDMI-1 --mode 1920x1080 --same-as eDP-1; else xrandr --output eDP-1 --mode 1920x1080; fi

this fails. Why does this happen?


text:
Q: PDO SQLSTATE[07002]:COUNT field incorrect or syntax error Estou com problemas para fazer um decremento no sql com pdo. estou recebendo o seguinte erro

SQLSTATE[07002]: [Microsoft][ODBC Driver 11 for SQL Server]COUNT field incorrect or syntax error

código
<?php
ob_start();
include'../../classes/config.php';
session_start();
$username = $_SESSION['ID'];

$creditosplayer = (float)$_POST["creditos"];

try {
  $pdo = new PDO($pdoconnection, $user, $pass);
  $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

  $query = $pdo->prepare("UPDATE [omegashop].[dbo].[cad_users] SET                         [creditos] = :creditosplayer WHERE [userid] = :user");
  $query->bindValue(':creditosplayer', $creditosplayer);
  $query->execute();

  echo 1;
} catch(PDOException $e) {
  echo 'Error: ' . $e->getMessage();
}

Como deve ser o parâmetro correto para o tipo float ?

A: Parece que você esqueceu de definir o valor para :user
Está setando somente o valor para :creditosplayer em:

$query->bindValue(':creditosplayer', $creditosplayer);

Faça:

$query->bindValue(':creditosplayer', $creditosplayer);
$query->bindValue(':user', $username);


text:
Q: Flash AS3 debug animation in browser (html)? Is there a way to debug a application in the browser (html)?
I have a small app that functions perfectly in flash and as a swf, but as soon as I get it in a html, online or off, it doesen't work. I know it is embebed properly because I tried changing the background color and it changes in the html as well, but aparently doesen't load.
It comunicates with a online text file, but I discarded any crossdomain problems, since they are on the same server (and it works in flash, as I mentioned earlier).
So, I'm really stumped. The main problem is that I don't even know the error, so I can't figure out what's wrong. Is there a way to do a "catch any error that comes up and show it in a text box"?

A: Firefox with flashfirebug plugin will show flash errors in the console.
It is also possible to debug a swf in a browser with Flash Develop using remote debugging(Debug>Start Remote Session).


text:
Q: Is it possible to save a record to a XML file without saving the fields separately? I have a big record which is consist of many fields with different types and also dynamic arrays. I want to save it to a file and then read it back. Imagine this simple record:
TCustomRecord = Record
   Field1 : array of integer;
   Field2  : Integer;
   Field3 : String;
end;

Normally I have to use something like this to save this record to a file:
var
   f : File of TCustomRecord;
   cr : TCustomeRecord;
 begin
   Write(f, cr);
 end;

But it doesn't work because of dynamic array and string type.
So the question is:
Is there a way to save (export) it to a TXMLDocument without going through all the fields? (I mean adding field-by-field using addChild())

A: Your XML library obviously needs to know what the fields' values are, or else it cannot serialize them, so you're going to have to go "through all the fields" at some point. Whether you do it manually or have some way of traversing your data structure automatically (like with RTTI) makes no difference. Something has to look at all the fields.

A: I'll cautiously say "No", although I have no idea what you mean by "going through all the fields".
Another answer links to a workable way of iterating the fields in your record using RTTI.  Then you must make sure your records are not going to use any type that your RTTI-iterator code doesn't understand, or it won't get saved.
As far as "not having to call AddChild yourself", you could simply store everything in XML attributes, without any child nodes.  I don't know if you know this, but there is not only one way to map fields in a record to  possible XML content that could result.
Here's an example record:
TMyData = record
           Name:String;
           Age:Integer;
           Money:Double;
end;

If you wanted to not call AddChild at all you could just write to the attributes, producing one entity like this:
  <MyData  Name="Warren" Age="48" Money="100.00"   />

There's nobody saying you even HAVE to use child nodes:
  <MyData>
    <Name>Warren</Name>
    <Age>48</Age>
    <Money>100.00<Money/>
  </MyData>

So it seems to me you're avoiding the fact that XML provides you lots of ways to do them, and that an MSXML DOM like API gives you more than one way to map any record to a file.


text:
Q: New matrix of mean submatrix - Python I have a matrix of [n x m], and I wish to create a new matrix, in which each cell equal to the sum of the 3x3 cells around this cell in the original matrix. The first/last row and column should be equal to the sum of 2x2 cells...
What is the most effective way to do this in Python? (The matrices are awfully large)

A: You can use scipy.ndimage.convolve for doing this. If all you want is the sum of the elements of each 3x3 window, the kernel will be np.ones((3,3)). If you want the average, divide by 9. Note that the mode='constant' option means pad with zeros to compute the sum at the boundaries.
import numpy as np
from scipy import ndimage

data = np.arange(0,25).reshape(5,5)

kernel = np.array([[1,1,1],[1,1,1],[1,1,1]])
avg_data = ndimage.convolve(data, kernel, mode='constant')

For this small example, you get:
data
[[ 0  1  2  3  4]
 [ 5  6  7  8  9]
 [10 11 12 13 14]
 [15 16 17 18 19]
 [20 21 22 23 24]]

avg_data
[[ 12  21  27  33  24]
 [ 33  54  63  72  51]
 [ 63  99 108 117  81]
 [ 93 144 153 162 111]
 [ 72 111 117 123  84]]


text:
Q: How to scan multiple string from a long string and store it in a char *word[20]?             int res, charRead;
            char *ptr = buff;
            char *searchWord[20];
            int j = 0;
            while(1)
            {
                res = sscanf(ptr, "%s%n", searchWord[j] ,&charRead);
                if(res != 1)
                {
                    break;
                }

                printf("%s\n", searchWord[j]);
                j++;
                ptr = ptr + charRead;

            }

The buff array has some strings included. For example, if buff contains "hello world". The result should be that searchWord[0] = "hello", searchWord[1] = "world". I am trying to move each word from that long array to another pointer array. However I am getting seg faults and invalid writes. Thank you for your help.
            int j = 0;
            char searchWord[20][20];
            char *ptr;
            ptr = strtok(buff, " ");
            while(ptr != NULL)
            {
                strncpy(searchWord[j][], ptr, 20);
                j++;
                ptr = strtok(NULL, " ");
            }

This is a changed one, however how do I initialize it so it does not cause any problem.

A:
@abhiarora Could you please guide how to allocate that space in the heap using malloc?

I have written a small code to illustrate three ways of doing the same thing. The code aren't optimised, efficient and I haven't freed the memory that has been allocated dynamically over heap. I have skipped some of the required checking in the beginning of these methods. I am assuming that you have better idea of your problem statement and figure out most of the things best suited for your application.
I have tested and compiled the code below on my Ubuntu 18.04 machine with gcc (gcc (Ubuntu 8.2.0-7ubuntu1) 8.2.0).
The compilation command was gcc test.c -o test -Wall -Wextra.
#include <stdio.h>
#include <string.h>

#include <stdlib.h>

int method1(const char *buffer, char *arrayOfPtr[50], const int MAX_NUM)
{
    int ndx = 0;

#define MAX_SIZE                    200
    char temp[MAX_SIZE + 1];

    // Method 1
    while (ndx < MAX_NUM) {
        int charRead = 0;
        if (sscanf(buffer, " %s%n", temp, &charRead) != 1)
            break;

        arrayOfPtr[ndx] = malloc(strlen(temp) + 1);
        if (arrayOfPtr[ndx] == NULL)
            break;

        memcpy(arrayOfPtr[ndx], temp, strlen(temp) + 1);
        buffer += charRead;
        ndx++;
    }

    return ndx;
}

int method2(const char *buffer, char *arrayOfPtr[50], const int MAX_NUM)
{
    char *temp = malloc(strlen(buffer) + 1);
    memcpy(temp, buffer, strlen(buffer) + 1);

    int ndx = 0;
    // Method 2
    while (ndx < MAX_NUM) {
        arrayOfPtr[ndx] = strtok(ndx ? NULL : temp, " ");
        if (arrayOfPtr[ndx] == NULL)
            break;
        ndx++;
    }

    return ndx;
}

#define MAX_NUMBER_OF_SUBSTRING             100
#define MAX_SUBSTRING_SIZE                  100

char gBuffer[MAX_NUMBER_OF_SUBSTRING][MAX_SUBSTRING_SIZE];

int method3(const char *buffer, char *arrayOfPtr[50], const int MAX_NUM)
{
    int ndx = 0;
    // Method 3
    while (ndx < MAX_NUM) {

        int charRead = 0;
        if (sscanf(buffer, " %s%n", gBuffer[ndx], &charRead) != 1)
            break;

        arrayOfPtr[ndx] = gBuffer[ndx];
        buffer += charRead;
        ndx++;
    }

    return ndx;
}

int main(int argc, char *argv[])
{
    char *bfr = "Hello World Stack Overflow";
    char *arrayOfPtr[50];

    int i;
    int size = method1(bfr, arrayOfPtr, sizeof(arrayOfPtr) / sizeof(arrayOfPtr[0]));

    for (i = 0; i < size; i++)
        printf("String: %d is \"%s\" of size %lu\r\n", i + 1, arrayOfPtr[i], (unsigned long)strlen(arrayOfPtr[i]));

    return 0;
}

Below are the explanations of each method:

*

*Method Number 1: In this method, I have been allocating memory dynamically using malloc. I have been using a temp array of characters of size 200 to hold the current c-string. After that, I allocate the memory dynamically of the required size and copy the string from temp using memcpy. This method doesn't handle the case when substring of size more than 200 has been feeded to the function.

*Method Number 2: In this method, I have been using strtok function declared in #include <string.h>. Using well-tested c-standard function reduced the number of lines of code required.

*Method Number 3: In this memory, I have allocated a global buffer for holding strings so that we don't require allocating dynamic memory. I have skipped some checking in the beginning of this method. This method has various limitations. It can't work on strings that have substrings of size more than 100 (MAX_SUBSTRING_SIZE) and can't handle string that have more than 100 (MAX_NUMBER_OF_SUBSTRING) substring in it. Also, if your particular substring has only 5 characters (like Hello), then 95 characters memory has been wasted. So, it's not an efficient method.

However I am getting seg faults and invalid writes.

I would suggest have a look at the compiler's warnings. Make sure you have enabled the warning in you IDE or using command-line flags.
I have learned tools like valgrind and gdb. They were very helpful to me while debugging my code for seg faults.


text:
Q: M.2 NVMe Adapter not working I have an EZCast S8000 Adapter for my old SSD, which is working fine on my Windows partition on my Lenovo 720-15ikb, but on the Ubuntu 19.10 partition it just shows up for a second and unmounts immedately.
How can I run the USB-Adapter on Ubuntu?

A: The manufacturer used wrong product id (re-used from another product) and it messes up the USB flip mode (USB devices can go through 2 modes). The usb-modeswitch package takes care of this in Ubuntu.
There is a temporary fix. Edit your /etc/usb_modeswitch.conf file and disable the switching mode:
DisableSwitching=1

Then when you insert the device it should work. It works fine for me, I could re-format the partitions and use the device. I'm using the USB-C port though. Not sure it matters.
Package maintainers are looking at a way to distinguish this device using other properties. I've open a bug there:
https://bugs.launchpad.net/ubuntu/+source/usb-modeswitch/+bug/1878921


text:
Q: Retrieve DOM target from drag callback when `this` is not available The documentation for d3.drag states the DOM element target of the drag event will be available in this to the callback:

When a specified event is dispatched, each listener will be invoked with the same context and arguments as selection.on listeners: the current datum d and index i, with the this context as the current DOM element.

But my call back is an object instance and this points to that object. So I need another way of accessing the current DOM element that is normally passed in this. How can I do it?

A: Use the second and the third arguments together to get this when this is not available:
d3.drag().on(typename, function(d, i, n) {
  //here, 'this' is simply n[i]
})

For a detailed explanation, have a look at the article below that I wrote to deal with this in arrow functions. The issue is different from yours, but the explanation is the same.
Here is a basic demo, try to drag a circle and look at the console:

var data = d3.range(5)
var svg = d3.select("body")
  .append("svg")
  .attr("width", 400)
  .attr("height", 100);
var circle = svg.selectAll(null)
  .data(data)
  .enter()
  .append("circle")
  .attr("cy", 50)
  .attr("cx", function(d) {
    return 50 + 50 * d
  })
  .attr("r", 10)
  .attr("fill", "tan")
  .attr("stroke", "black")
  .call(d3.drag()
    .on("start", function(d, i, n) {
      console.log(JSON.stringify(n[i]))
    }))
<script src="https://d3js.org/d3.v4.min.js"></script>

PS: I'm using JSON.stringify on the D3 selection because Stack snippets freeze if you try to console.log a D3 selection.

Using "this" with an arrow function
Most of functions in D3.js accept an anonymous function as an argument. The common examples are .attr, .style, .text, .on and .data, but the list is way bigger than that.
In such cases, the anonymous function is evaluated for each selected element, in order, being passed:

*

*The current datum (d)

*The current index (i)

*The current group (nodes)

*this as the current DOM element.

The datum, the index and the current group are passed as arguments, the famous first, second and third argument in D3.js (whose parameters are traditionally named d, i and p in D3 v3.x). For using this, however, one doesn't need to use any argument:
.on("mouseover", function(){
    d3.select(this);
});

The above code will select this when the mouse is over the element. Check it working in this fiddle: https://jsfiddle.net/y5fwgopx/
The arrow function
As a new ES6 syntax, an arrow function has a shorter syntax when compared to function expression. However, for a D3 programmer who uses this constantly, there is a pitfall: an arrow function doesn't create its own this context. That means that, in an arrow function, this has its original meaning from the enclosing context.
This can be useful in several circumstances, but it is a problem for a coder accustomed to use this in D3. For instance, using the same example in the fiddle above, this will not work:
.on("mouseover", ()=>{
    d3.select(this);
});

If you doubt it, here is the fiddle: https://jsfiddle.net/tfxLsv9u/
Well, that's not a big problem: one can simply use a regular, old fashioned function expression when needed. But what if you want to write all your code using arrow functions? Is it possible to have a code with arrow functions and still properly use this in D3?
The second and third arguments combined
The answer is yes, because this is the same of nodes[i]. The hint is actually present all over the D3 API, when it describes this:

...with this as the current DOM element (nodes[i])

The explanation is simple: since nodes is the current group of elements in the DOM and i is the index of each element, nodes[i] refer to the current DOM element itself. That is, this.
Therefore, one can use:
.on("mouseover", (d, i, nodes) => {
    d3.select(nodes[i]);
});

And here is the corresponding fiddle: https://jsfiddle.net/2p2ux38s/


text:
Q: Android Java Notification This code isn't working for me it should make notification every 2 sec the app runs with no errors and then after 2 sec keeps giving me messages you're app has stopped working.
I added these codes:
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <service android:name="NotificationService" android:exported="false"/>
            <receiver android:name="BootReceiver">
                <intent-filter>
                    <action android:name="com.company.app"/>
                    <action android:name="android.intent.action.BOOT_COMPLETED"/>
                </intent-filter>
            </receiver>

MainActivity.java
startActivity(new Intent(this,NotificationService.class));

NotificationService.java
public class NotificationService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mTimer=new Timer();
        mTimer.schedule(timerTask,2000,2*1000);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {

        }catch (Exception e){
            e.printStackTrace();
        }
        return super.onStartCommand(intent, flags, startId);
    }
    private Timer mTimer;
    TimerTask timerTask=new TimerTask() {
        @Override
        public void run() {
            Log.e("log","Running");
            notifiy();
        }
    };

    @Override
    public void onDestroy() {
        try {
            mTimer.cancel();
            timerTask.cancel();
        }catch (Exception e){
            e.printStackTrace();
        }
        Intent intent=new Intent("com.company.app");
        intent.putExtra("your value","torestore");
        sendBroadcast(intent);
    }
    public void notifiy(){
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("RSSPullService");

        Intent mIntent=new Intent(Intent.ACTION_VIEW, Uri.parse(""));
        PendingIntent pendingIntent=PendingIntent.getActivity(getBaseContext(),0,mIntent,Intent.FLAG_ACTIVITY_NEW_TASK);
        Context context=getApplicationContext();

        Notification.Builder builder=new Notification.Builder(context)
                .setContentTitle("T")
                .setContentText("M")
                .setContentIntent(pendingIntent)
                .setDefaults(Notification.DEFAULT_SOUND)
                .setAutoCancel(true)
                ;//.setSmallIcon();

        Notification notification=builder.build();
        NotificationManager notificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1,notification);

    }
}

BootReceiver.java
public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("Service stops","ohhhhhhh");
        context.startService(new Intent(context,NotificationService.class));
    }
}


text:
Q: How to install PHP, Pear, PECL, and APC with Homebrew on Mac OS X? I'm trying to install APC for PHP 5.3 in the easiest way possible. I love Homebrew so I started down that route. I was able to install PHP 5.3.6 with this command:
brew install https://github.com/adamv/homebrew-alt/raw/master/duplicates/php.rb --with-mysql

I think this is supposed to install PHP, Pear, and PECL. It seems to install these just fine.
Now when I try to install APC:
$ pecl install apc
downloading APC-3.1.9.tgz ...
Starting to download APC-3.1.9.tgz (155,540 bytes)
.................................done: 155,540 bytes

Warning: require_once(Archive/Tar.php): failed to open stream: No such file or directory in PackageFile.php on line 305

Warning: require_once(Archive/Tar.php): failed to open stream: No such file or directory in /usr/local/Cellar/php/5.3.6/lib/php/PEAR/PackageFile.php on line 305

Fatal error: require_once(): Failed opening required 'Archive/Tar.php' (include_path='/usr/local/Cellar/php/5.3.6/lib/php') in /usr/local/Cellar/php/5.3.6/lib/php/PEAR/PackageFile.php on line 305

How can I fix this?

A: pecl and pear are provided with Homebrew's version of PHP:
brew install php
pecl install apcu

If you're weary that pecl and pear are provided by php, try this:
ls -al $(which pecl)
ls -al $(which pear)

Both locations should symlink to Cellar/php/...
Note, macOS provides a php version which is generally behind that of Homebrew.  To make sure you're running the Homebrew version, prefix your php commands with $(brew --prefix php)/bin.
Example for Composer:
$(brew --prefix php)/bin/php composer.phar install

The reason this is important is because common extensions -- such as ext-intl and ext-gettext are provided automatically and will fix these automatically.
Notice, for php-fpm, use brew reinstall php --with-fpm.  The php-fpm path will be... $(brew --prefix php)/sbin/php-fpm.

A: Below command should help
curl -s -O https://pear.php.net/install-pear-nozlib.phar

sudo php install-pear-nozlib.phar -d /usr/local/lib/php -b /usr/local/bin

A: Now homebrew-php has been migrated to homebrew-core and by default, PECL should be installed along with your PHP.
Here are the suggested steps:

*

*Reinstall PHP via: brew install php.

*Check pecl command by: which -a pecl.

To see which files were installed, see: brew list php.
To install PHP extensions, you need to use PECL as a recommended way.

With the migration to Homebrew-core the php formula has stopped taking over the role of PECL. Installing xdebug can (and should) be done through PECL. Source: GH-26007

For example: pecl install apc or pecl install xdebug.
If you've got some problem installing the extension, you need to report it to its maintainer. Check PECL website for more details.

A: Homebrew PHP's GitHub site says that:

Pear is no longer compiled by default, instead you need to install php with the --with-pear option, such as: brew install php56 --with-pear.

So, to make PHP 7.0 work, use the following installation command:
brew install php70 --with-pear
You can of course use this with other versions of PHP, too.

A: You do not need install apc.
Just add
apc.enabled=on
apc.shm_size=64M
apc.enable_cli=on

to your php.ini and make sure that your apcu is ok.


text:
Q: gnuplot function not plotting - Order of Operation Issue? The gnuplot (Version 5.4 Windows patchlevel 5) for the function described in the first line below does not work, the second one does. What is going on?
plot  [0:2] [0:4] f(x) = 1/2/(pi*d)**0.5*exp(-1*(1-x)**2/(4*d)), d = 0.0065, f(x)
#plot  [0:2] [0:4] f(x) = 1/(2*(pi*d)**0.5)*exp(-1*(1-x)**2/(4*d)), d = 0.0065, f(x)

The above two lines are the narrowed down version from several alternatives involving sqrt instead of **2.

A: This is the "everlasting" gnuplot pitfall: integer division, i.e. 1/2=0. Use for example f(x) = 1.0/2/... instead.


text:
Q: How to add sticker overlay to camera photo I'm trying to emulate what Celebrity Clicks does: add a celebrity sticker to camera feed, position it and scale it, and than take the photo. This should give you a photo with the sticker applied, which is what Celebrity Click does. However, I'm having trouble merging the camera photo with the sticker. There are a few issues: the sticker scale and position is wrong when applied on the final camera image, because the image taken from the camera is actually much larger both in resolution and in size than the picture shown on the live camera feed when you set up the sticker.
Here is what I'm doing now:
[(GPUImageStillCamera *)videoCamera capturePhotoAsImageProcessedUpToFilter:selectedFilter withCompletionHandler:^(UIImage *processedImage, NSError *error) {
    selectedImage = [self imageByCombiningImage:processedImage withImage:celebOverlayView.imageView.image];
}];

- (UIImage*)imageByCombiningImage:(UIImage*)firstImage withImage:(UIImage*)secondImage {
UIImage *image = nil;
CGSize newImageSize = CGSizeMake(MAX(firstImage.size.width, secondImage.size.width),            MAX(firstImage.size.height, secondImage.size.height));
if (UIGraphicsBeginImageContextWithOptions != NULL) {
    UIGraphicsBeginImageContextWithOptions(newImageSize, NO, [[UIScreen mainScreen] scale]);
} else {
    UIGraphicsBeginImageContext(newImageSize);
}
[firstImage drawInRect:cameraView.frame];

[firstImage drawAtPoint:CGPointMake(roundf((newImageSize.width-firstImage.size.width)/2),
                                    roundf((newImageSize.height-firstImage.size.height)/2))];
[secondImage drawAtPoint:CGPointMake(roundf((newImageSize.width-secondImage.size.width)/2),
                                     roundf((newImageSize.height-secondImage.size.height)/2))];
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return image;
}

I have attached the before and after photo, so that you can see my problem.
Camera setup screen:

Photo taken with camera with the sticker applied:

I'm guessing that there is a better way to merge the two images or to simply apply the sticker at given coordinates to the camera captured image. Any suggestions?

A: It is easiest if you save the relative frame of the added view in the picker and then compute the new frame when applying the added image combining the two images.
One of the many ways to do so is to divide all the parameters of the frame with the superview width and height respectively when taking the photo and then multiplying the same frame coordinates with the image width and height when trying to merge the two images.
Also for what you are doing I suggest you lose the core graphics to draw the image content and rather just use the image view: Crate the image view with the size of the background image, set the image then add another image view with the added image and set the frame as described above. Then simply create a screenshot of the view and your image is done. This way you will have no issues with scaling, transforms and such.


text:
Q: A variable seems to be de-referencing when I use it in a dynamic array (C++) Here we are once again good people of the internet.
This is the code I'm using:
//This is what is in the header file
int *myArr[]; // A two-dimensional array representing holding the matrix data

//This is what is in the definition file
Matrix::Matrix(int n, int m)
{
    myRows = n;
    myColumns = m;
    initialize();
}

void Matrix::initialize()
{
    *myArr = new int[myRows];

    for (int i=0; i < 3; i++)//Only set to 3 since myRows is acting crazy
    {
        myArr[i] = new int[myColumns];
    }
}

For some reason when I use myRows variable to create the myArr array it just seems to stop referencing the value it was pointing towards before.
For instance I give it the value 3 and after the *myArr = new int[myRows] has been executed it changes the value of myRows to 9834496, which I don't understand.
Does the "new" de-reference the variable or something?
Or am I doing something wrong?
Oh and since this is a school practice project (so I won't blame you if you don't answer) I would prefer an answer over working code, so that I could know what I did wrong for future projects.

A: int *myArr[];

This is wrong! You've to tell the compiler the size also, of your array of pointer. How about if you declare int a[]. You're telling the compiler to create an array of int, of unknown size, which is not allowed in C++. That is why you cannot do that.
I would suggest you to do this:
int **myArr;

void Matrix::initialize()
{
    myArr = new int*[myRows]; //note int* here!

    for (int i=0; i < myRows; i++)
    {
        myArr[i] = new int[myColumns];
    }
}

This should work now.

A: You should use std::vector<>. It deals with all the problems of memory allocation and deallocation.
And it does so without any bugs.
And then you focus yourself on the real goals of your algorithm. Not on memory management :-)
typedef std::vector<int> Ints;
typedef std::vector<Ints> Matrix;
Matrix myArray;

A: Try replacing:
*myArr = new int[myRows];

by
myArr = new int*[myRows];

A: I'm not sure if you're project requires you to use multi-level pointers, if it doesn't another way you can approach this problem is to just treat the multi-dimensional array as one big flat array.
That means when you reach the end of a row, the index after that would be the first element of the next row. Here's how the code might look:
// In this approach the double pointer int**
// is replaced with just a simple int*
int *myArr;

// Here's your Matrix ctor. Note the use of the initializer list
Matrix::Matrix(int n, int m) : myRows(n), myColumns(m)
{
    initialize();
}

void Matrix::initialize()
{
    myArr = new int[myRows * myColumns];

    /* This loop is no longer needed since we're allocating
       one big chunk at once.
    for (int i=0; i < 3; i++)//Only set to 3 since myRows is acting crazy
    {
      myArr[i] = new int[myColumns];
    }
    */
}

// To retrieve stuff from your array
// you would do something like this:
int Matrix::operator() (const int x, const int y)
{
  return myArr[x * myRows + y];
}


text:
Q: A module with a store It happens quite often that it is costly to calculate a property from a value. So it would be better to be able to store the property once it is calculated. I am wondering how to code this properly.
Let's take an example. Assume we have a type integer, and very often we need to calculate prime factors of a value of such type (let's assume the prime factors of a negative integer is None):
module I =
struct
  type t = C of int
  type pf = (int list) option

  let calculate_prime_factors (x: t) : pf =
    (* a costly function to calculate prime factors *)
    ... ...

  let get_prime_factors (x: t) : pf =
    calculate_prime_factors x
end

let () =
  let v = I.C 100 in
  let pf_1 = I.get_prime_factors v in
  let pf_2 = I.get_prime_factors v in
  let pf_3 = I.get_prime_factors v in
  ...

At the moment, get_prime_factors just calls calculate_prime_factors, as a consequence, all the calculations of pf_1, pf_2, pf_3 are time consuming. I would like to have a mechanism to enable storing prime factors inside the module, so that as long as the integer does not change, the second and third times of get_prime_factors just read what have been stored.
Does anyone know how to modify the module I to achieve this?
It is possible that we need references to make this mechanism possible (eg, let vr = ref (I.C 100) in ...). It is OK for me to use references. But I don't know how to trigger automatically calculate_prime_factors if the hold value (ie, !vr) is changed.

A: What you want to do is memoization, no ?
You could try this :
module I =
  struct

  type t = C of int
  type pf = (int list) option

  let calculate_prime_factors (x: t) : pf =
    (* a costly function to calculate prime factors *)
    ... ...

  module HI = Hashtbl.Make (struct
    type t = C of int
    let equal = (=)
    let hash (C x) = x
  end)

  let get_prime_factors =
    let h = Hashtbl.create 17 in
    fun x ->
      try Hashtbl.find h x
    with
      Not_found -> let pf = calculate_prime_factors x in
                   Hashtbl.add h x pf;
                   pf
end

let () =
  let v = I.C 100 in
  let pf_1 = I.get_prime_factors v in
  let pf_2 = I.get_prime_factors v in
  let pf_3 = I.get_prime_factors v in
  ...

You could adapt it for negative integers (with exceptions, for example, which is better than options) but I hope you get the idea.

A: I would do the following :
let get_prime_factors x =
  match get x  with
  | None ->
    let res = calculate_prime_factors x
    in
    begin
      set x res ;
      res
    end
  | Some res -> res
;;

You need a mutable data structure accessed by get and set. For instance, with a reference on a list (but you may prefer a hashtable) :
let my_storage = ref [] (* or something mutable *)

let get x =
  if List.mem_assoc x !my_storage
  then Some (List.assoc x !my_storage)
  else None

let set x r =
  my_storage := (x,r) :: !my_storage ;;

You can also use exceptions instead of the option type (None and Some _).

A: Looks like, that you're looking for this solution:
module I = struct
  type t = {
     c : int;
     mutable result : int option;
  }

  let create c = {c; result = None}

  let calculate_prime_factors t = match t.result with
    | Some r -> r
    | None ->
       let r = do_calculate t.c in
       t.result <- Some r;
       r
end

This is called memoizing. And this particular example can be solved even easier, with Lazy computations.
  module I = struct
    type t = int Lazy.t
    let create c = lazy (do_calculate c)
    let calculate_prime_factors = Lazy.force
  end


text:
Q: PHP CSV file issues(part 2)
*

*continue on PHP duplicate staffID

*code
$data[0] = 0001,Ali,N,OK
$data[1] = 0002,Abu,N,OK
$data[2] = 0003,Ahmad,N,OK
$data[3] = 0004,Siti,Y,Not OK. Only one manager allowed!
$data[4] = 0005,Raju,Y, Not OK. Only one manager allowed!
I write it as following:
for($i = 0; $i < 5; $i++)
{
    $data[i] = $staffID[$i].','.$staffname[$i].','.$ismanager[$i].','.$remark[$i];
}

*Next I go to write csv file.
$file_format = "staffreport.csv";
$file = fopen($file_format,"w");
foreach($data as $line)
{
    $replace = str_replace(",","|", $line);
    fputcsv($file, array($replace));
    echo $replace.'<br />';
}
fclose($file);

*output (echo $replace)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
0004|Raju|Y|Only one manager allowed!
0005|Siti|Y|Only one manager allowed!

*In CSV file (staffreport.csv)
0001|Ali|N|OK
0002|Abu|N|OK
0003|Ahmad|N|OK
"0004|Siti|Y|Only one manager allowed!"
"0005|Raju|Y|Only one manager allowed!"

*Why my csv file have double quote("")? How do I solve it?

A: change this bit like so.
for($i = 0; $i < 5; $i++)
{
    $data[i] = array($staffID[$i],$staffname[$i],$ismanager[$i],$remark[$i]);
}

fputcsv wants an array of columns it will then insert the separators and quote marks as needed.
fputcsv usually uses commas for separators, if you want pipes: do this:
 fputcsv($file, $line,'|');

why the quotes? probably because of the spaces.
if you must avoid the quotes,
 fputcsv($file, $line,'|','');

hope that helps.