text:
Q: How to Hide System Navigation Bar in Tablets? At my Tablet, it has following bar to control back, home etc. (I don't know the correct name, status bar? control bar? Action bar? or other)
In program, it use following method to have a full screen.
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
requestWindowFeature(Window.PROGRESS_INDETERMINATE_OFF);

But I don't know why the bar still in here. Because of it, I can't have the correct screen size.
Who can tell me how to remove it?

A: In Android 4.4 and above you can completely hide the navigation bar and have it remain hidden using a combination of fullscreen and immersion:
@Override
protected void onResume() {
    super.onResume();

    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

A: public class Utils {

public static void hideNavigations(Activity context) {
    View decorView = context.getWindow().getDecorView();
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
            | View.SYSTEM_UI_FLAG_FULLSCREEN
            | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}

}
In your Activity:
@Override
protected void onResume() {
    super.onResume();
    Utils.hideNavigations(this);
}

A: There seems to be a UNDOCUMENTED flag for this:
yourGreatView.setSystemUiVisibility(8);

*

*no black footer ("hidden" system bar)

*resizes view if keyboard shows up (no overlapped inputs)

Verified on Android 4.1.2 (API 16)
Verified on Android 4.1.1 (API 16)
Verified not working on Android 4.0.4 (API 15)
(all tablets)

A: A very nuclear option is to just delete the SystemUI.apk from /system/app/.  But warning this will remove it from the tablet completely.  I'm doing this on a tablet i'm using for a front panel kiosk, then i set the tablet to boot into my app.

A: In Tablets running Android 4+, it is not possible to hide the System / Navigation Bar.
From documentation (Controls for system UI visibility section) :

The SYSTEM_UI_FLAG_HIDE_NAVIGATION is a new flag that requests the
  navigation bar hide completely. Be aware that this works only for the
  navigation bar used by some handsets (it does not hide the system bar
  on tablets).

However, you could try to dim the system bar as done sometimes during gaming and video playback.

The SYSTEM_UI_FLAG_LOW_PROFILE flag replaces the STATUS_BAR_HIDDEN
  flag. When set, this flag enables "low profile" mode for the system
  bar or navigation bar. Navigation buttons dim and other elements in
  the system bar also hide. Enabling this is useful for creating more
  immersive games without distraction for the system navigation buttons.

A: As other people say use the command "pm disable com.android.systemui" in root mode, so the following code execute this command in your android app, just call the following method, your tablet needs to be rooted.
private void hideNavigationBar(){
        try {
            Process process = Runtime.getRuntime().exec("su");
            DataOutputStream os = new DataOutputStream(process.getOutputStream());
            os.writeBytes("pm disable com.android.systemui\n");
            os.flush();
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
            //////////////////////////////////////
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

This code hide the navigation bar on the android system, to reappear system bar use "pm enable com.android.systemui" instead of "pm disable com.android.systemui" in the previous code.

A: Since the system bar is used to navigate in android there is not an easy way to achieve this, you can dissable/dim the controls:
View v = findViewById(R.id.view_id);
v.setSystemUiVisibility(View.STATUS_BAR_HIDDEN);

But you can get the size of the screen without the systembar (not sure from what version, I think 3.1)
Method rawW = Display.class.getMethod("getRawWidth");
Method rawH = Display.class.getMethod("getRawHeight");
int width = (Integer)mGetRawW.invoke(dp);
int height = (Integer)mGetRawH.invoke(dp);

If your app has root access there is also a way to achieve it: http://ppareit.github.com/HideBar/

A: You can't hide it but you can simply disable it, except home. Try this link. . Using SYSTEM_UI_FLAG_LOW_PROFILE you can dim your system bar and using onWindowFocusChanged() can take the focus and collapse it.

A: Below code worked for me -
You can write it in onCreate() or onResume( if needed)
getWindow().getDecorView().setSystemUiVisibility( View.SYSTEM_UI_FLAG_IMMERSIVE
                            | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);


text:
Q: Laravel API testing unit vs feature I am using Laravel 5.6 to write a API with no views, just endpoints.
I am very new to testing and my understanding is that Unit tests are from a programmers perspective and Feature tests are from a users perspective.
As i am only creating an API, would I be right to assume that i will only be writing Unit tests? and i am safe to remove the tests/Feature directory all together?
My tests will consist of things like
public function it_authenticate_a_user()

Sorry if its a dull question, i am only trying to learn.
Thanks

A: No, it's not a good idea to write only unit tests.
A true unit test verifies that a single class or function works as expected. However, it does NOT verify that the whole application works as expected - it's perfectly possible for the application to have 100% coverage from unit tests, but not actually work because the components don't quite fit together as expected. You should also write functional tests for your endpoints. The majority of your tests should be unit tests, but it's a good idea to make sure every API method is covered by functional tests too, just to make sure the pieces fit together.
Put it this way, at Google they advocate a model called the testing pyramid, which gives a typical ratio of 70% unit tests, 20% functional tests, and 10% high level acceptance tests. It should not be seen as rigid, and for an API I see little need for acceptance tests, but it gives some idea as to a healthy mix of tests.
An API is in some ways easier to test than a conventional web app since it's stateless and each method is relatively simple, but it's just as important it has functional test coverage. It's straightforward to test API routes in Laravel - just do the setup, make the request and check the response is correct and any changes have been made.

redpajama_set_name: RedPajamaStackExchange


text:
Q: MySQL Community server 5.6.26 10.9 download has 10.8 in it? I am trying to get MySQL running on GM of El Capitan. When I go to MySQL downloads for the Community server there are 2 .DMG archives - one for Mac OS X version 10.9 and one for 10.8. However when I download the 10.9 .dmg archive and open it it contains the 10.8 server. If you look at the 2 MD5 hashes for the 2 .DMGs they are the same.
So is there no 10.9 version of MySQL? Is there no difference? I can install it, but when I try and start it it fails on El Capitan.
I just want to make sure I am not missing something given there is no 10.10 and certainly not yet a 10.11 .DMG archive.


text:
Q: How do defined methods work in Gradle? When I run my gradle task test, why are the tasks local, dev, and uat seem to be run as well? I am trying to only run test.
The actual output when I run gradle test is below (see pic). My desired output is below (see pic). What am I doing wrong in my code? I am new to Gradle/Groovy, so my apologies. thanks!
Code:

Actual Output:

Desired Output:

A: When you use
someTask {
    someMethod()
}

then it means to gradle that it must call someMethod() when configuring the task, in the first phase that parses the build script and decides which tasks exist and what depends on what.
To define what must happen when the task is executed, in the second phase, you must use the following syntax:
someTask << {
    someMethod()
}


text:
Q: Increasing laptop's speed I have an i3 processor laptop[i3-6006U CPU @ 2.00GHz] with 4GB RAM which is pre installed. I have used it for 3 years and it has slowed own to a considerable extent. I was thinking about increasing the speed by installing an 8 GB RAM from Crucial but was advised against it because the i3 processor would not be able to handle the 12 GB RAM installed and there would be no change in the sluggish space of my laptop. Is this true? I have primarily used it to download movies from torrent and make college projects.

A: Typical i3 computers come with a 5,400 rpm hard drive. That combination is a slow as can be. (Experience).
An SSD will help it a lot but it will still be an i3.
Memory beyond 8 GB will not help substantially if you are not running Virtual Machines (too slow for that).
So best investment:  Replace the drive with an SSD.
Note to followup:  Unless your data needs are huge, a 512 GB fast SSD should do.

A: RAM and SSD will definitely improve experience but there is a huge caveat.
Usually computers "slow down" because:

*

*They are loaded with unnecessary software starting with the system

*The dust is blocking air vents, or the heatsink vents are completely clogged reducing its ability to dispense the heat. When CPU overheats, it will throttle down to protect itself from damage.

*Another thermal issue is with the thermal paste. Usually the cheap paste will dry out and will lose its ability to transfer the heat efficiently.

In order to revive the computers I take following steps:
(depends on the outcome of troubleshooting, and the budget)

*

*Clean the fans and radiator/heatsink (if clogged)

*Clean up the startup, tasks scheduler, scan system etc,

*Apply fresh thermal paste (if laptop is over 2 years old)

*Upgrade RAM and switch HDD to SSD (if planing to do that, save time cleaning the OS)

As far as the RAM support, you need to look up how much will your motherboard support. Your CPU supports up to 32GiB
Edit
As per your comment, I am assuming there are no issue with CPU throttling.
When OS is running out of RAM it will start using virtual memory (also called paging file or swap). It means that OS will write content of the fast RAM into slow storage. Obviously upgrading the RAM will help with this issue. Especially considering that the Windows 10 requires minimum 2GB RAM
We still don't know what exactly is a brand and model of your laptop but for 3-4y old computer I would doubt it won't support 12GB.
Meanwhile you can improve the performance slightly by disabling windows effects:
In run window (press Win+R) enter SystemPropertiesAdvanced
Under Performance click on Settings...
Under Visual Settings tab select Adjust for best performance
You can decide for yourself if that will improve anything.
I would also try to tune up the OS with following steps:
Startup
Let's disable unnecessary software from startup:
Open Task Manager - press Ctrl+Shift+Esc
At the bottom of new window click More details
Select Startup tab.
You can safely disable all the application by right clicking and selecting Disable.
You can also simply use troubleshooting tool to disable all startup items.
Open Run window - press Win+R
Type msconfig and press Enter
Select Services tab
Before you do anything here, look at the bottom and select Hide all Microsoft services
Now all the essential services are hidden but you still have to be careful what you are disabling. I would recommend to leave all services by Intel AMD or NVIDIA. The safest approach is to disable services you are recognizing to be unnecessary. When done, restart the computer
Another place that automatically starts applications is Task Scheduler.
Open Run window again and type taskschd.msc and press Enter
In the window on the left select Task Scheduler Library. In the main window you can select all scheduled Tasks and Disable them or Delete them.
It is safe to do so, but you may disable some automatic update checking for some software. Your call.
Malware
Next step would be to run malware scan. There are many good scanners, but I like to use Hitman Pro currently owned by Sophos.
You can use its 30-day trial.Hitman Pro
You will need to fill the legal mambo jumbo and agree to EULA...
Check disk
After restarting clean system you can check if your system file is OK.
Open Command Prompt:
Press Win key and in menu type cmd don't press Enter.
Right click and select Run as Administrator, then if prompted by UAC press yes.
In command prompt execute command:chkdsk /f c:
If it will ask to schedule it for next system restart press y and Enter.
Now just restart the computer. System will run the scan, correct errors and it will restart again.
To see the outcome of the scan you can open Event viewer:
Win+R - > type eventvwr.msc and press enter.
In the window on the left, expand Windows Logs and select Applications
On the right hand side, under actions find Filter Current Log... Open it and in the window expand the Even sources: and scroll down to Wininit select it and press OK.
You can see if there were any issues and if all were resolved.
Checking System Files
Now we can scan protected system files for corruptions.
In the Command Prompt (opened as Administrator) type these commands:
DISM.exe /Online /Cleanup-image /Restorehealth

DISM uses Windows Update to provide the files that are required to fix corruptions.
When completed run sfc /scannow and press enter.
For more details about fixing corrupted system files go to:support.microsoft.com...

A: You need to provide the make and model for accurate advice, but that CPU can handle up to 32 gigs of memory (as per https://ark.intel.com/content/www/us/en/ark/products/91157/intel-core-i3-6006u-processor-3m-cache-2-00-ghz.html) so the claim it won't work with more memory is likely false. Crucial and Kingston websites both allow you to look up valid memory configurations for most equipment and are reliable sources.
Memory upgrades can make a massive difference and are a good idea.
There is also another thing to look at which is also a common bottleneck - if you have an hdd, its worth replacing it with an SSD.

A: Change your hard drive to ssd really helps out a lot whether you are gaming or just browsing, it would boost up your program opening speed. You could try to upgrade to 6g ram or 8g ram if possible, and last of all, it's always a good idea to upgrade your software, like using a smaller software and don't multitasking, and you could try to install some chrome extension like adblocker, I'm also college student, I know how important multitasking means to you, and other extension like great suspender, it will free up a lot of ram space, trust me, it will get faster.


text:
Q: Are HTTP GET variables indexable by Google Are HTTP GET variables indexable by Google?
e.g. if I link to http://myhomepage.com/show?id=14&awesome-calvin-and-hobbes-stuffed-zombies-i-made
will the part after the & be picked up by Google's search engine as having to do with Calvin and Hobbes?

A: Yes, you can see it from search results (e.g. search for "search q" - many of the results include HTTP GET variables). Some CMS systems e.g. Drupal use such URLs by default.

A: Yes. Google does index URLs with query strings and they do parse them for keywords. It doesn't mean you'll rank well for them, though.


text:
Q: Llamar a un servicio SOAP desde un servidor que usa REST en JAVA Buenas.
Tengo una aplicacion en JAVA que tiene definido servicios Rest y quiero consumir dentro de esta aplicacion servicios SOAP, esto es posible ???
Es decir al hacer una peticion GET a la URL http://localhost:8080/nombreServicio/doc?id=123 mi aplicacion internamente consuma un servicio SOAP para obtener cierta informacion y posteriormente responder a la solicitud.

A: Realizar una llamada a un servicio web que devuelve una respuesta en SOAP, desde una aplicación JAVA es posible.
Saludos.

A: Claro que es posible, con java existen diferentes tecnologias para generar un web service cliente con SOAP, entre ellas se encuentran:

*

*Axis - http://users.skynet.be/pascalbotte/rcx-ws-doc/present.htm

*SOAPClientSAAJ - https://stackoverflow.com/questions/15948927/working-soap-client-example.

En mi opinion, yo he utilizado SOAPClientSAAJ, ya que no es necesario crear stubs con codigo innecesario, como lo hace axis.
Axis genera clases que realizan la conexión, es facil entenderlas pero en ocasiones se hace un poco revoltoso el tema, mas aun cuando el endpoint contiene varias url (metodos) que puedes consultar.
Cabe mencionar que con SOAP, al menos hasta donde he visto (si no que alguien me corrija), no existen definiciones para los endopoints en protocolo HTTP (GET, POST, etc.), solo un descriptor (wsdl)  que contiene la firma de los metodos, este descriptor es una url el cual contiene el xml de la definicion de los metodos.
Espero te sirvan de ayuda.


text:
Q: How to delete a broken data in Python So I have a file that gets statistic data of an upload script. This is what I get.
    0K .......... .......... .......... .......... ..........   4% 72.83 KiB/s
  470K .......... .......... .......... .......... ..........   9% 84.67 KiB/s
 1088K .......... .......... .......... .......... ..........  15% 91.78 KiB/s
 1708K .......... .......... .......... .......... ..........  20% 90.17 KiB/s
  1250K .......... .......... ....   5% 85.29 KiB/s
  6150K .........  10% 64.32 KiB/s
  8350K .......... .......... ........... .......... .....  15% 55.12 KiB/s
...==> STOR test10.zip ... ....  20% 59.38 KiB/s
    0K ................. .......... ... ............. ............. ............  25% 66.21 KiB/s
 2845K ...... .......... ........... .............. . ................... ...   4% 32.62 KiB/s
  464K ................ ... ..................  29% 59.62 KiB/s
 3371K .. ................ ....... ...... ................ ....... ........... ......   8% 38.75 KiB/s
  963K ............ ................ ....  34% 51.58 KiB/s
2253K .......... .......... .......... .......... ..........  24% 99.92 KiB/s
 2787K .......... .......... .......... .......... ..........  29% 92.12 KiB/s
 3291K .......... .......... .......... .......... ..........  33% 84.42 KiB/s
 3821K .......... .......... .......... .......... ..........  38% 75.88 KiB/s
 4342K .......... .......... .......... .......... ..........  43% 73.12 KiB/s

Some have broken data that is caused by internet problems.
So what I want is to remove those broken data and it will look like this:
    0K .......... .......... .......... .......... ..........   4% 72.83 KiB/s
  470K .......... .......... .......... .......... ..........   9% 84.67 KiB/s
 1088K .......... .......... .......... .......... ..........  15% 91.78 KiB/s
 1708K .......... .......... .......... .......... ..........  20% 90.17 KiB/s
 2253K .......... .......... .......... .......... ..........  24% 99.92 KiB/s
 2787K .......... .......... .......... .......... ..........  29% 92.12 KiB/s
 3291K .......... .......... .......... .......... ..........  33% 84.42 KiB/s
 3821K .......... .......... .......... .......... ..........  38% 75.88 KiB/s
 4342K .......... .......... .......... .......... ..........  43% 73.12 KiB/s

NOTE: Not all the time, the data is the same of the example above.

A: One way to do this:
$ cat foo.py
data = '''
    0K .......... .......... .......... .......... ..........   4% 72.83 KiB/s
  470K .......... .......... .......... .......... ..........   9% 84.67 KiB/s
 1088K .......... .......... .......... .......... ..........  15% 91.78 KiB/s
 1708K .......... .......... .......... .......... ..........  20% 90.17 KiB/s
  1250K .......... .......... ....   5% 85.29 KiB/s
  6150K .........  10% 64.32 KiB/s
  8350K .......... .......... ........... .......... .....  15% 55.12 KiB/s
...==> STOR test10.zip ... ....  20% 59.38 KiB/s
    0K ................. .......... ... ............. ............. ............  25% 66.21 KiB/s
 2845K ...... .......... ........... .............. . ................... ...   4% 32.62 KiB/s
  464K ................ ... ..................  29% 59.62 KiB/s
 3371K .. ................ ....... ...... ................ ....... ........... ......   8% 38.75 KiB/s
  963K ............ ................ ....  34% 51.58 KiB/s
2253K .......... .......... .......... .......... ..........  24% 99.92 KiB/s
 2787K .......... .......... .......... .......... ..........  29% 92.12 KiB/s
 3291K .......... .......... .......... .......... ..........  33% 84.42 KiB/s
 3821K .......... .......... .......... .......... ..........  38% 75.88 KiB/s
 4342K .......... .......... .......... .......... ..........  43% 73.12 KiB/s
'''

import re
pattern = r".*\d+K\s+(\.{10}\s){5}\s*\d+%\s+\d+\.\d+\s+KiB\/s.*"

for line in data.split('\n'):
    if re.match(pattern, line) is not None:
        print(line)
$

Execution result:
$ python foo.py
    0K .......... .......... .......... .......... ..........   4% 72.83 KiB/s
  470K .......... .......... .......... .......... ..........   9% 84.67 KiB/s
 1088K .......... .......... .......... .......... ..........  15% 91.78 KiB/s
 1708K .......... .......... .......... .......... ..........  20% 90.17 KiB/s
2253K .......... .......... .......... .......... ..........  24% 99.92 KiB/s
 2787K .......... .......... .......... .......... ..........  29% 92.12 KiB/s
 3291K .......... .......... .......... .......... ..........  33% 84.42 KiB/s
 3821K .......... .......... .......... .......... ..........  38% 75.88 KiB/s
 4342K .......... .......... .......... .......... ..........  43% 73.12 KiB/s
$


text:
Q: DSolve gives 2 different solutions I am trying to solve below equation, but DSolve gives two different solutions an I don't know which one should I choose. Could anyone help me? My code is as below
DSolve[f'[r]/r + f''[r] == -A Exp[-B f[r]], f[r], r]

Boundary conditions are also known:
f'[R]= d
Integrate[r Exp[-B f[r]]= e,{r,0,R}]


text:
Q: iOS: Xcode projects relativity I often encounter several Xcode projects from the web that have another Xcode project within them.
What I mean is that there are another Xcode project included from another.
What does it do and how do it work? Just curiosity...

A: Projects or Xcode workspaces can include additional projects. Sometimes it is better to split parts of develompmet into different projects and not always is the result of the project an application. I can be a custom library you may use in the other project.
So if you make changes to the library only you don't have to compile the complete application. Just rebuild the library and link it to your application in the other project.


text:
Q: How can I filter out Java methods according to version? I need to generate a jar library in three different versions. Some methods of the classes are marked with annotations that specify the version when they were added. For example:
public class A {

  @SinceVersion(2)
  public int getTotal() {
    // do something...
  }

  @SinceVersion(5)
  public int getMax() {
    // do something...
  }

  @SinceVersion(4)
  public int getAverage() {
    // do something...
  }

}

Then:

*

*When I generate my-library-2.jar, only getTotal() should be included.

*When I generate my-library-4.jar, only getTotal() and getAverage() should be included.

*When I generate my-library-5.jar all three methods should be included.
This is a simplified example. The real problem spans 300 classes, 10 versions, with 6 subversions each.

A: You may wanna look into implementing an annotation processor.
Annotation processors run during compile time and are used to create and/or manipulate code, and I use them to create boilerplate code, as well as code that's otherwise tedious to maintain manually, but has a clear structure.

A: Why not use source control (git, etc.) to manage your releases?  when you tag a release with v2.0, then code up to that point will have only getTotal().  Then v4.0 comes a long, and the code up to that point will have getTotal() and getAverage(), and so on.
Each release can be managed and built independently, and produce the specific jar file for that specific release.
Your client will then include whichever version of the jar it needs.

A: I wanted to post the solution I found in case is of help for someone else.
After researching for a week I finally found Apache Commons BCEL. This library allows you to inspect and modify a class loaded in the JVM; once modified it can be written to the file system as a .class file.
A piece of code like this produces a new class file without some methods:
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.AnnotationEntry;
import org.apache.bcel.classfile.JavaClass;
import org.apache.bcel.classfile.Method;
import org.apache.bcel.generic.ClassGen;

JavaClass clazz = Repository.lookupClass("test.House");
ClassGen cg = new ClassGen(clazz);
Method m = findMethod(clazz, "close");
AnnotationEntry ae = m.getAnnotationEntries(); // process annotations here...
cg.removeMethod(m); // remove the method you want to remove
JavaClass modifiedClazz = cg.getJavaClass();
modifiedClazz.dump("./gen/test/House.class"); // save to a new file

By walking the whole tree of classes (or a subpackage tree) it's possible to find all affected classes, process their methods, and remove them if the annotation values match some criteria.


text:
Q: Python subprocess Error 22 - Works while debugging but not when running I am trying to call a python script from another using subprocess.Popen(). It works perfectly when I debug the program line-by-line, however when I run the program normally I get the following error:
C:\Python38\python.exe: can't open file '"<filepath>\thumbs.py"': [Errno 22] Invalid argument

I'm stumped as to what the issue is as it works without fault when the program is being debugged line-by-line so not sure what changes exactly when the program is run normally.
I am trying to pass a set of arguments into the subprocesses, and am then parsing these using argparse in the child process.
This is how I am calling the process:
cmd = ['python', "\"" + pythonPath + "thumbs.py\"", '-d', "\"" + outputdb + "\"", '-c', "\"" + path + cache + "\""]
subprocess.Popen(cmd).wait()

And here is how I am parsing the arguments in the child process:
if __name__ == '__main__':
    global session
    args = None
    parser = argparse.ArgumentParser()

    parser.add_argument("-d", "--database", action="store", dest="dbname", help="Database to output results to", required=True)

    parser.add_argument("-c", "--cache", action="store", dest="cachefile", help="Cache file to scrape.", required=True)

    while args is None:
        args = parser.parse_args()

Can anyone spot what I'm missing?

A: I've managed to fix this issue by creating my command and arguments as a string first and then using shlex.Split() to split it into an arguments list.
cmdStr = "python \"" + pythonPath + "thumbs.py\" -d \"" + outputdb + "\" -c \"" + path + cache + "\""
cmd = shlex.split(cmdStr)
subprocess.Popen(cmd).wait()

Further info here: https://docs.python.org/3.4/library/subprocess.html#popen-constructor


text:
Q: Find the shaded region and area of the shaded region
In the diagram below, $CAD$ is a sector with centre $A$ and $EBD$ is a semicircle with diameter $ED$. Given that $AB=18cm$ and angle $CAD=\pi/3$ radian.
  Find
(a) The perimeter of the shaded region.
(b) The area of the shaded region.

I'm assuming that $AB=CD$ and have worked out that $CD=37.704cm$
Please help as it is midnight in my region and I would need to hand in my homework tomorrow.

A: Hint. Let $O=(E+D)/2$ be the center of the semi-circle then $BO$ is orthogonal to $AB$.Then $\angle CAD=\pi/3$ implies that $\triangle ABO$ is a right triangle with angles $30^{\circ}-60^{\circ}-90^{\circ}$.  Moreover, $\triangle ACD$ is equilateral.
Can you take it from here?


text:
Q: IndexError on list.pop() in list comprehension To learn python I am implementing Bulls and Cows. So I need to generate a 'random' number. I tried this:
possibilities = range(10)
number = "".join([str(possibilities.pop(random.choice(possibilities))) for i in range(4)])

Which I thought was a nice solution to the problem, but once in every couple of runs I get an IndexError on that line: IndexError: pop index out of range
So it looks like random.choice() gives me a non existent index. How come?
Or am I making a wrong assumption and is the problem something else entirely?
Come to think of it, I haven't got a clue how to debug a statement like this, any pointers on that?
Edit
My first solution was of the procedural kind:
for i in range(4):
    idx = random.choice(possibilities)
    number = number + str(possibilities[idx])
    del possibilities[idx]

This code seems to do the exact same thing as the one-liner above, but has no problems whatsoever.

A: You aren't randomly choosing indices, you're choosing values from the list. What if you pick 9 after a lower number or two has been popped from the list?
Instead, use random.sample:
number = "".join(map(str, random.sample(range(10), 4)))


text:
Q: Imposing leads and lags into a sequence without a for loop Aside from writing a loop that yields values, is there a simple/clean functional way of creating a lag (previous value) within a sequence.
Eg.  If my sequence is 1 2 3 4 5 6 7 8 9 10 and my lag is 1 return a tuple that is
(Some(1), None), (Some(2), Some(1)), (Some(3), Some(2))...(Some(10), Some(9))

A lag of 2 would give (Some(1), None), (Some(2), None), (Some(3), Some(1))...
It's obviously easy to write this using a loop, but is that the right way?

A: One way is to use the functions in the Seq module:
let lag n sequence =
    sequence
    |> Seq.map Some
    |> Seq.append (Seq.init n (fun _ -> None))
    |> Seq.zip sequence

lag 2 [1..5] |> Seq.toList
> [(1, null); (2, null); (3, Some 1); (4, Some 2); (5, Some 3)]

A: petebu's answer (once a few mistakes are corrected) is a better answer. But I'll leave this here anyway.
let withLag n (source: seq<_>) =
  source
    |> Seq.windowed n
    |> Seq.append (Seq.init n (fun _ -> [||]))
    |> Seq.zip source
    |> Seq.map (fun (x, arr) ->
      let laggedValue = if arr.Length > 0 then Some arr.[0] else None
      (x, laggedValue))

let l = List.init 5 id
l |> withLag 2 |> Seq.toList |> printfn "%A"

> [(0, null); (1, null); (2, Some 0); (3, Some 1); (4, Some 2)]


text:
Q: Is it possible to perform some action BEFORE a JFrame is minimized? In Swing, there are several ways to capture the event of minimizing a frame (iconifying), but the event happens when the frame is ICONIFIED which means after the frame becomes invisible from the screen.
Now I wish to run some code before disappearance of the frame -- immediately when I click the taskbar button.
In other words, do something when the JFrame is "about to" (NOT AFTER) be minimized. Is it possible to do this?

A: Use WindowStateListener, and call WindowEvent#getNewState() and check against Frame.ICONIFIED.
Here is an example:
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Test {

    public Test() {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel panel = new JPanel() {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(300, 300);
            }
        };

        frame.add(panel);

        frame.addWindowStateListener(new WindowAdapter() {
            @Override
            public void windowStateChanged(WindowEvent we) {
                if (we.getNewState() == Frame.ICONIFIED) {
                    System.out.println("Here");
                }
            }
        });

        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new Test();
            }
        });
    }
}

A: Create your own JFrame and override setExtendedState method.
public class MyFrame extends JFrame{

   ....
    setExtendedState(JFrame.ICONIFIED);
   ....

@Override
public void setExtendedState(int state) {
    // your code

    super.setExtendedState(state);
   };

 }

A: Answer to the question "Is it possible to perform some action BEFORE a JFrame is minimized?"
I would say no unfortunately, I checked the native code for openjdk (windows) for frame and window that sends these events to java-space. And as I understand it, it is a callback from the windows API VM_SIZE message. And the SIZE_MINIMIZED is sent when "The window has been minimized" and is not getting any messages before the actual minimization.


text:
Q: What did the Pharros's Lockstone do in No-man's Wharf? I just bought a Pharros locks tone to use for the one in no mans wharf, but I'm not sure if it was a waste using it there, all I saw was a big light (and it's still here) go up then one of those crazy monsters look like when "Ahhhh! The sun it BURNS!!!!!!!"
Anyways, I just want to know what happened.

A: The function of the Lockstone contraption is to light the lantern that's hanging high up in the air. This will light up much of the area, making it less necessary to use your own torch.
Bloatheads (the spider-looking enemies) are also scared of light, which you may have noticed if you approached one with your torch out. When the lantern is lit via the Lockstone contraption, they will generally confine themselves to building interiors and other dimly-lit areas, which may make your travels through the area a little bit easier.


text:
Q: Replace nan values with the unique date (date in numpy array.) I have written a code in a for loop:
date = dit[x]["Time"].dt.date.unique()

output:
[datetime.date(2017, 6, 5)]

I am getting a numpy array.
I have a dataframe like this:
   Position  Values  Date
0       1.0  826.18   NaN
1      22.0  828.11   NaN
2      33.0  826.18   NaN
3      56.0  826.09   NaN

I want to replace Nan values with the unique date i am getting from the above code.
My approach:
peaks_df["Date"] = peaks_df["Date"].replace(np.nan, str(date))

there is an edit.
output:

   Position  Values                          Date
0       1.0  826.18  [datetime.date(2017, 6, 5)]
1      22.0  828.11  [datetime.date(2017, 6, 5)]
2      33.0  826.18  [datetime.date(2017, 6, 5)]
3      56.0  826.09  [datetime.date(2017, 6, 5)]

Expected Output:
   Position  Values    Date
0       1.0  826.18  6/5/2017
1      22.0  828.11  6/5/2017
2      33.0  826.18  6/5/2017
3      56.0  826.09  6/5/2017

Can anybody suggest me the correct way to do it?
Any help would be appreciated.

A: .unique() returns a list of all unique elements in the selection (there could be more than one).  If you are sure that there will only be one date given your data, just access the first (and only) element of the list.  I used a ternary in case the list is empty, in which case it returns a blank string.
.replace(np.nan, str(date[0]) if date else "")

You can probably notice the source of your problem via this:
>>> str([dt.date.today()])
'[datetime.date(2018, 1, 5)]'

Your date variable is a list containing a single date.  Converting it to a string results in the output above.
Taking the first element of this list, however, would result in your desired outcome:
>>> str([dt.date.today()][0])
'2018-01-05'


text:
Q: Protect image directory I`m looking for some solution which will make my directory with pictures secured.
In my page only Administrator have permission to upload the pictures. User have opportunity only to view a picture for products. I want to make directory more secured. I want to make it difficult to download all pictures from some kind of scripts.
For now I tried with .htpaccess and .htpasswd it work fine but when User trying to see the product page(where are available pictures form secured folder) htpaccess is requiring a username and password.
Is it possible to enter username and password to this directory from server side when user is watching the product page. And in case that he open a link of the picture in new window then user name and password is required?
Do you know some other solutions?
Cheers

A: Don't store the images in your web folder where everyone can access them. Instead, store them outside of the web path (for example in app/data or so) and use a symfony controller to deliver them. This way you can use the symfony security component.

A: In addition to good answer by @Pierre, you can use a filesystem abstraction layer. I'd recommend using Gaufrette. To integrate it with Symfony, you could use KnpGaufretteBundle.
It will give you way more flexibility as

*

*using external filesystems (ex. Amazon S3, FTP, sFTP)

*use Symfony Security component or ACL.

Everything depends on your need and your approach in the project. However, if you need some flexibility, I'd recommend try it out.


text:
Q: wordpress missing P tag I am creating a file outside of wordpress but i want to get wordpress post etc. I created the following which does whar i want it to do but it is missing th P tags. if i view this post through wp-admin it looks fine. if i view it through this function it doe snot look find
ini_set('display_errors','on');

//Global WordPress
global $wpdb;

if(!isset($wpdb))
{
    require_once('wp-config.php');
    require_once('wp-load.php');
    require_once('wp-includes/wp-db.php');
}

$args = array("post_title" => $_GET['name'],"category_name"=>"knowledge-map");
$query = get_posts( $args );

$posttitle = $_GET['name'];
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $posttitle . "'" );
$post = $getpost= get_post($postid);

$post_title = sanitize_post_field( 'post_title', $post->post_title, $post->ID, 'display' );
$post_content = sanitize_post_field( 'post_content', $post->post_content, $post->ID, 'display' );

//$postcontent= $getpost->post_content;
//setup_postdata( $getpost );
$data = $post->post_content;
//foreach ( $getpost as $post ) : setup_postdata( $post );
    //$data = get_the_title() . the_content();
//endforeach;
wp_reset_postdata();

echo $data;

A: post_content won't show proper formatting...basically ever. You need to apply the_content filter to it:
echo apply_filters('the_content', $data);

Here's where it's mentioned in the Codex.
While wpautop will only add paragraph tags where new lines exist, the_content runs a bunch of core filters (including wpautop). From the source, the_content includes:
add_filter( 'the_content', 'wptexturize'        );
add_filter( 'the_content', 'convert_smilies'    );
add_filter( 'the_content', 'convert_chars'      );
add_filter( 'the_content', 'wpautop'            );
add_filter( 'the_content', 'shortcode_unautop'  );
add_filter( 'the_content', 'prepend_attachment' );

A: you can also use wpauto, it uses in wordpress for auto formatting of text
echo wpautop( $post_content );

A: Not very techy, but I found that if I copy everything from the "text" area in a Wordpress post, then paste it into a markdown to HTML editor, then it results in  tags being added wherever Wordpress omits them!

*

*Copy the "Text" from a Wordpress post

*Paste into markdown/HTML editor

*View the HTML for that markdown


text:
Q: need assistance on constructing sql query i have three tables like follows:
this one table : m_application_resources
 resourceid resource_name   menu_group_id   menu_name   creation_date   last_created_by updation_date   last_updated_by

and the second table : m_roles
roleid  rolename    description creation_date   last_created_by updation_date   last_updated_by

and the third table is : m_access_matrix
accessid    resourceid  roleid  creation_date   last_created_by updation_date   last_updated_by

Relationship for the table is : resourceid and roleid
and this my query
select  am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am
where ar.resourceid=am.resourceid

this returns the following :
ccessid resource_name   rolename
1   DepartmentAction    Admin
1   DepartmentAction    Client
1   DepartmentAction    Doctors
2   PositionsAction     Admin
2   PositionsAction     Client
2   PositionsAction     Doctor

the result is wrong and i don't know how to go about.
Ex : DepartmentAction should come only once and the role name should be any one.
SqlfiddleFiddle
Please help

A: You do not have a condition on role_id:
select  am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am
where ar.resourceid=am.resourceid AND am.roleid = rls.roleid

I would convert the query to ANSI SQL syntax for joins for better clarity:
SELECT am.accessid, ar.resource_name,rls.rolename
FROM m_application_resources ar
JOIN m_access_matrix am ON ar.resourceid=am.resourceid
JOIN m_roles rls ON am.roleid = rls.roleid

A: It would be best to explicitly join the tables in your query.  I'm not 100% sure I understand your tables, but this should work:
SELECT am.accessid, ar.resource_name, rls.rolename
FROM (m_application_resources ar INNER JOIN m_access_matrix am
ON ar.resourceid = am.resourceid) INNER JOIN mroles rls ON am.roleid = rls.roleid


text:
Q: Can I use not only... but also... with two different subjects? As in this sentence:

Not only should you cook your meals, but also they should be healthy.

The first subject is "you", and the second subject is "meals". Can I use not only... but also... this way? Otherwise what's the best way to connect the two parts?

A: Not really. Not only . . . but also assumes parallel subjects.
The best way to connect them, in the example you gave, is simply to drop the also:

Not only should you cook your meals, but they should be healthy.

Alternatively, you could rewrite it to make the subjects parallel:

Not only should your meals be cooked by you, but they should also be healthy.

There you're getting into the passive voice, though, which a lot of people like to avoid. Personally, I would avoid it here, simply because it's too wordy.
One more possibility, again trying to make the subjects parallel:

Not only should you cook your meals, but you should make them healthy.

Slight change in meaning, but works better.

A: Well technically you can, but I think it sounds more flowing and connected if you say

Not only should you cook your meals, but they should also be healthy.

Putting the also right after the but sounds abrupt and choppy to my ear.


text:
Q: UI-Router does not register history before $onInit So I have a login scheme that only needs user login behind specific pages. Currently, I have the page checking if the user exists via the $onInit function, then firing the login (which redirects to a login page via Code Flow in OAuth 2). Then when I've logged in, the page redirects back to the previous page, instead of the page I fired the login even from.
I think this is due to ui-router not registering history with the browser before it redirects, thus the $state object in the OAuth 2 parameters, when decoded shows me the path: "redirectUrl":"http://localhost:3000/reservations" when it should be "redirectUrl":"http://localhost:3000/reservations/purchase".
So my question is two fold.

*

*Is $onInit an appropriate place to be doing this, or should I have some global routechange listener or use resolve? If I use either of those two methods, I think I will still have the route problem.

*If I keep using $onInit, is there some way to make sure the url is registered correctly so that it will redirect to the correct location post-login?

$onInit function:
function init() {
    var token = Meteor.call('getAccessToken');
    if (!token) {
        Meteor.loginWithOidc();
    }
}


text:
Q: Covariance of the product of a random scalar and a random vector What is the covariance matrix of the product of a random scalar and a random vector in general (if any) and in all special cases, in terms of the variance of the scalar and the covariance matrix of the vector?

A: Label the scalar $v_1$ and the vector $v = (v_2, \dots, v_{n+1})$ (assuming the vector has $n$ components). Then your covariance matrix between the scalar and the vector is just the covariance matrix of $n+1$ scalars. It would look like this :
$$
\begin{bmatrix}
\mathbb{C}\mathrm{ov}[v_1,v_1] & \mathbb{C}\mathrm{ov}[v_1,v_2] & \dots & \mathbb{C}\mathrm{ov}[v_1,v_{n+1}] \\
\mathbb{C}\mathrm{ov}[v_2,v_1] & \mathbb{C}\mathrm{ov}[v_2,v_2] & \dots & \\
\vdots & \vdots & \ddots & \\
\mathbb{C}\mathrm{ov}[v_{n+1},v_1] & & & \mathbb{C}\mathrm{ov}[v_{n+1},v_{n+1}]
\end{bmatrix}
$$
The $n \times n$ submatrix in the lower right corner would be the covariance matrix of $v$ and $\mathrm{\mathbb Cov}[v_1,v_1]$ would be on the top left corner. The only new information this matrix has is the relationships between $v_1$ and the components of $v$.
Hope that helps,


text:
Q: IOSXR Commands Output to JSON format I am trying to see if there is a convenient way to convert IOSXR commands to JSON format. I know you could parse the output string, but for my environment and the repeatability of the process it is less than ideal. From what I have seen there is some support for this with show run | json and I see there is some generalized json support for junipers, but this syntax has not been successful in other commands. Thanks for any help.
This is in an ansible environment. I am using the iosxr_command library.
I have tried to run show interface summary | json but got back a syntax error. I was expecting back a JSON formatted string.


text:
Q: How to retrieve unique data from Mysql database table I have a table with four columns namely core,domain, Prog_StdName, LP_Prj_Desc.
I want to retrieve unique the data, where LP_Prj_Desc column is dependent on Prog_StdName and Prog_StdName is dependent on domain, and domain, is dependent on  `core.
Below image which Ihave tried using the select statement.
SELECT `core`,`domain`,`Prog_StdName`,`LP_Prj_Desc`
FROM `cf_ls`
WHERE `core` <> 'PS'

this show the duplicate rows   enter image description here
Actually I need to retrieve the data like below imageenter image description here

A: SELECT distinct `core`,`domain`,`Prog_StdName`,`LP_Prj_Desc`
FROM `cf_ls`
WHERE `core` <> 'PS' ;

Try this one


text:
Q: Removing an object from array of objects swift 3 I'm trying to remove an object from array of objects
I tried different scenarios, but instead of removing item it has been added 2 times to the array, I'm going out of my mind and couldn't find any reason for that
 let pages = surveyData.pagerItems; // Pages is a model which contains an array of another model called question
 let questions = self.pages[indexPath.section].questionItems.filter{$0.id != questionId};
 self.pages[indexPath.section].questionItems = questions;

I tried to remove all questions items first also before assigning it to pages object
self.pages[indexPath.section].questionItems.removeAll();
self.pages[indexPath.section].questionItems = questions;

also tried this
self.pages[sourceIndex.section].questionItems.remove(at: sourceIndex.row)

Also when I try to insert object, it adds more than once.
please help.

A: Use below code, I hope it may work:-
self.pages[indexPath.section].questionItems.removeAll(keepingCapacity: false)
self.pages[indexPath.section].questionItems.append(questions)

A: To remove an object from array:
var array = ["First Object", "Second Object", "Third Object"]

if let index = array.index(of:"Third Object")
{
    array.remove(at: index)
}

A: I have tried your scenario, its working fine. I created a Modal named page having array variable as questions. And fill values as given below.
class Page {
    var questions = [String]();
}

Getting sample values filled.
    let page1 = Page();
    page1.questions.append("P1->First Element");
    page1.questions.append("P1->Second Element");
    page1.questions.append("P1->Third Element");
    page1.questions.append("P1->Fourth Element");
    page1.questions.append("P1->Fifth Element");

    let page2 = Page();
    page2.questions.append("P2->First Element");
    page2.questions.append("P2->Second Element");
    page2.questions.append("P2->Third Element");
    page2.questions.append("P2->Fourth Element");

    let page3 =  Page();
    page3.questions.append("P3->First Element");
    page3.questions.append("P3->Second Element");
    page3.questions.append("P3->Thirs Element");

    var pages = [Page]();
    pages.append(page1);
    pages.append(page2);
    pages.append(page3);

Now we will see output before removing item and after removing item.
    print("p1.question \(pages[0].questions)");
    print("p2.question \(pages[1].questions)");
    print("p3.question \(pages[2].questions)");

    pages[1].questions.remove(at: 2);

    print("p1.question \(pages[0].questions)");
    print("p2.question \(pages[1].questions)");
    print("p3.question \(pages[2].questions)");

Now you can see output as expected.
p1.question ["P1->First Element", "P1->Second Element", "P1->Third Element", "P1->Fourth Element", "P1->Fifth Element"]
p2.question ["P2->First Element", "P2->Second Element", "P2->Third Element", "P2->Fourth Element"]
p3.question ["P3->First Element", "P3->Second Element", "P3->Thirs Element"]

p1.question ["P1->First Element", "P1->Second Element", "P1->Third Element", "P1->Fourth Element", "P1->Fifth Element"]
p2.question ["P2->First Element", "P2->Second Element", "P2->Fourth Element"]
p3.question ["P3->First Element", "P3->Second Element", "P3->Thirs Element"]

As you can see third Item from page at index 1 has been removed successfully.
I think you are confusing between let and var. In swift let is immutable object where as var is mutable one.


text:
Q: Where can I play poker? I know that you can play poker in the game. Do I have to unlock a mission to enable it ? Where are the location I could play ?

A: Poker locations unlock like other "activity" locations, when you take over enemy outposts. When you open one, you'd receive a notification.
They look like a spade on your map. You can go to your map and check the legend to filter for poker locations specifically.


text:
Q: What does aggregation mean in statistics? Im a programmer who is currently studying to become a data scientist.
I was reading this https://seaborn.pydata.org/tutorial/relational.html#emphasizing-continuity-with-line-plots in this there is a topic 'Aggregation and representing uncertainty'
Can anyone explain what aggregate means in simple English, with an example?

A: An aggregate is just a clumping together of values according to some aggregation principle(s). For example, there is an aggregate() function in R language. This applies to a time series method or data frame method, and the organizing or aggregating formula might just be addition, or finding a mean value, for example, presidential popularity by year from daily popularity data, or Compute the averages for the variables in 'state.x77', grouped
according to the region (Northeast, South, North Central, West) that each state belongs to. In the OP's reference default aggregation appears to refer to finding the mean and confidence intervals of a time series with multiple $y$-values at each time, with another choice being a mean with $\pm$standard deviations. For machine learning, the aggregate is the output of Ensemble learning; "In statistics and machine learning, ensemble methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone." Aggregation is the method used for forming an aggregate. This usage is seen in the title Ensemble aggregation methods for relocating models of rare events.
Let's put this in more human terms. What ensemble learning methods do is aggregate (to combine 'a vote democratically') from several learning algorithms to make choices. To see why this works, let us construct an example.
One could ask, "Why is the word  tribunal in common usage?" To make a long story short, tribunals composed of three adjudicators are more likely (because the best two of three opinions is also the median opinion) to make a best decision than any single judge's opinion would. Also, many people voting for something, is more likely to be constitutionally better than if fewer vote that way.
To see the improvement, let us assume that each judge has a 2/3 probability of being correct (a '1') and a 1/3 probability of being wrong (a '0'). Then to see the improvement a tribunal opinion would have for deciding correctly (a '1'), we choose taking the median as the aggregation method, where the aggregate output is the median, and list out all the equal possibilities:

This shows that the improvement of getting the correct answer has gone from 66.67% (2/3) for odds of correctness for individual judges to 74.07% (20/27) for the median judge's answer. For a more mathematically complete description see "The dirty coins and the three judges"
question and answer. Summarizing, as long as the judges have an opinion better than 50-50 (which would be perfect cluelessness), taking the median (an aggregate, or combined value) of three independent opinions (which is what a tribunal supposedly does) will increase the odds of getting the right answer.
In other contexts, aggregates are made when the aggregation increases precision/accuracy and/or to create representative values for subsets (e.g., sort and add).

A: https://en.wikipedia.org/wiki/Aggregate_data

In statistics, aggregate data are data combined from several
  measurements. When data are aggregated, groups of observations are
  replaced with summary statistics based on those observations.

In your link the aggregation is done by:

The default behavior in seaborn is to aggregate the multiple
  measurements at each x value by plotting the mean and the 95%
  confidence interval around the mean

Thus

*

*the 'aggregate data' is the 'mean' and the '95% confidence interval'

*which is created from the 'several measurements' at each x value.

aggregation is the process to reduce the many measurements into a few values/statistics.
You can do this aggregation in many different ways, the mean and 95% confidence interval is just one of many options to summarize the several measurements. See also https://en.wikipedia.org/wiki/Summary_statistics


text:
Q: UIPopoverController popoverControllerDidDismissPopover not working I am presenting a popover controller on an iPad from a uibutton. I set the UIPopoverController's delegate to the main view controller. The "popoverControllerShouldDismissPopover" and the "popoverControllerDidDismissPopover" are both not being called. Am I missing something?
class MainVC: UIViewController,UIPopoverControllerDelegate

@IBAction func btnTPD(sender: UIButton) {

    var vc = MyXIB(nibName: "MyXIB",bundle: nil)

    var nav = UINavigationController(rootViewController: vc)

    var popover = UIPopoverController(contentViewController: nav)
    popover.delegate = self
    popover.popoverContentSize = CGSize(width: 283, height: view.bounds.height * 0.6)
    popover.presentPopoverFromRect(sender.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: false)

}

func popoverControllerShouldDismissPopover(popoverController: UIPopoverController) -> Bool {

    println("SHOULD DISMISS")

    return true

}

func popoverControllerDidDismissPopover(popoverController: UIPopoverController) {

    println("DID DISMISS")

}

A: It seems my UIPopoverController instance (var popover) needs to be declared outside the "btnTPD" function for the delegate functions to work.
class MainVC: UIViewController,UIPopoverControllerDelegate {

var popover: UIPopoverController!

@IBAction func tapped(sender: UIButton) {

    var vc = MyXIB(nibName: "MyXIB",bundle: nil)

    var nav = UINavigationController(rootViewController: vc)

    popover = UIPopoverController(contentViewController: nav)
    popover.delegate = self
    popover.popoverContentSize = CGSize(width: 283, height: view.bounds.height * 0.6)
    popover.presentPopoverFromRect(sender.frame, inView: self.view, permittedArrowDirections: UIPopoverArrowDirection.Any, animated: false)

}

func popoverControllerShouldDismissPopover(popoverController: UIPopoverController) -> Bool {

    println("SHOULD DISMISS")

    return true

}

func popoverControllerDidDismissPopover(popoverController: UIPopoverController) {

    println("DID DISMISS")

}

}


text:
Q: Which data type of fragment to use if I want to remove it dynamically I am trying to get instance of the dynamically currently appearing or showing fragment as follows:
fragment = getSupportFragmentManager().findFragmentById(R.id.fragmentContainer);

but this code returns the following type android.support.v4.app.Fragment
and later I want to remove that fragment which I earlier obtains an instance of as follows:
mFragmentTransaction.remove(fragment);

but this method does not accept this type android.support.v4.app.Fragment
How to solve this issue please.

A: Your variable mFragmentTransaction should be initialized with the getSupportFragmentManager().beginTransaction() method. Maybe you have used the getFragmentManager() object, witch would be incorrect in your case.

A: Check your imports. If you see the following import:
import android.app.Fragment;

you will want to change it to the support library version to maintain consistency as follows:
import android.support.v4.app.Fragment;

A: Check your import statements and be sure you are not mixing "Support" fragments and "Native" fragments. You must use a consistent fragment and many recommend the "Support" version over the "Native" version, in which case you should be using getSupportFragmentManager.
Also, since you wish to remove a fragment, make sure the fragment container is not hard coded in XML. If you intend to replace or remove a fragment, then the initial fragment should be loaded dynamically by your code (you typically will load into a FrameLayout using the id as yourR.id.{frameLayoutId}), else it will not work.


text:
Q: setLevel okhttp LoggingInterceptor deprecated setLevel(okhttp3.logging.HttpLoggingInterceptor.Level)' is deprecated
what should replace with setLevel? to remove the deprecated issue

A: According to the documentation "Moved to var. Replace setLevel(...) with level(...) to fix Java",
Replace setLevel(...) with level(...) will fix this issue
in Java:
HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
logging.level(HttpLoggingInterceptor.Level.BODY);

in Kotlin
val logging = HttpLoggingInterceptor()
logging.level = HttpLoggingInterceptor.Level.BODY

Happy coding :)

A: for Kotlin
replace :
val logger: HttpLoggingInterceptor =
HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)  //Logging Interceptor

with :
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BODY

Add your inceptor to okHttpClient
val okkHttpclient = OkHttpClient.Builder()
                .addInterceptor(networkConnectionInterceptor)
                .addInterceptor(logger)
                .build()

Happy Coding...

A: For Kotlin, use the apply function and then setLevel using the level property.
 private val loggingInterceptor = HttpLoggingInterceptor().apply {
        level = HttpLoggingInterceptor.Level.BODY
    }

    var client : OkHttpClient = OkHttpClient.Builder().addInterceptor(loggingInterceptor).build()


text:
Q: How to model N threads doing same thing with activity diagram? I want to draw uml-correct activity diagram representing process of my raytracer.
I know I should use black rectangles to model fork/join. But in my application I spawn N threads doing the same thing (which is not simple and will be modeled via multiple activity elements). How can I draw such activity diagram without having the same thing without knowing number of threads?
My explanation is poor, image may help understand what I want to model with activity diagram

A: You can use the expansion region element.

A: There is no way I know of to model a fork of N control flows and I found none in three UML2 books nor the UML2.4.1 formal specification (http://www.omg.org/spec/UML/2.4.1/Superstructure).
That said, using an expansion region with the 'parallel' keyword, you can fork N object flows, processing N objects in parallel.
I am, however, not fully satisfied with this solution because I suspect that you don't create N threads because you have N objects to process but because you have N processor cores and that each thread processes a lot of frames (or whatever objects that need processing).
You can, of course, work around this by using the processor cores as objects.


text:
Q: Why is select on two channel much slower than 2x of the time to select on single channel? This benchmark with single channel only take 2.545 ns/op:
func BenchmarkSingleSelect(b *testing.B) {
    ch := make(chan interface{}, 1)
    for i := 0; i < b.N; i++ {
        select {
        case <-ch:
        default:
        }
    }
}

But this benchmark with two channel takes 35.85 ns/op:
func BenchmarkMultiSelect(b *testing.B) {
    ch := make(chan interface{}, 1)
    ch2 := make(chan interface{}, 1)
    for i := 0; i < b.N; i++ {
        select {
        case <-ch:
        case <-ch2:
        default:
        }
    }
}

Why is it non-linear?

A: Usually the difference between one and multiple is a big jump. Your first construct may involve optimizations that are only possible when only a single channel is monitored. You'll see this if you add further benchmarks for 3 and 4 channels involved: benchmark time will roughly go linear, but having a single channel is special.
This is really an implementation detail, for specifics, you must check / analyze Go's source code. One thing from the Spec: Select statements:

Execution of a "select" statement proceeds in several steps:

*

*For all the cases in the statement, the channel operands of receive operations and the channel and right-hand-side expressions of send statements are evaluated exactly once, in source order, upon entering the "select" statement. The result is a set of channels to receive from or send to, and the corresponding values to send. Any side effects in that evaluation will occur irrespective of which (if any) communication operation is selected to proceed. Expressions on the left-hand side of a RecvStmt with a short variable declaration or assignment are not yet evaluated.

[...]

Channels of each cases are evaluated, and the result is a set of channels to receive from or send to. Since there is a default case, the compiler has to check if any of the communication ops are ready to proceed. In the general case when there are multiple channels involved, this requires a loop, and some data structure (e.g. a slice or a bitmap) that gathers the ready cases. In case of a single channel, the compiler may generate a more efficient code that doesn't involve a loop, and doesn't need a set to gather the ready cases, the generated code just has to check a single channel.


text:
Q: troubleshooting dns resolution, packet dropping, and dig/nslookup I've been trying to troubleshoot an issue where using a curl lookup command takes a long time (sometimes) and is quick some other time.
TL;DR
Question: how do i troubleshoot further.
Connecting directly to an ip-address has no issues.
I've tried two different locations, multiple machines (RPi, debian vm, Windows10).
I've tried to set nameservers to both 1.1.1.1 and to 8.8.8.8 with the same result
i've changed the /etc/resolv.conf so that it contains (and yes. i've writeprotected it)
options timeout:1

So now it nolongertakes 5 seconds before it succeeds in dns_resolution.. but 1.00xx seconds (sometimes) and sometimes 0.00xxx seconds.
For me it first looked like a firewall dropping packets issue or a ipv6-try issue. however i've disabled ipv6 on the machines, with no luck.
I've used this command to do the lookups:
while :; do curl --max-time 10 -w "time_namelookup: %{time_namelookup}, time_connect: %{time_connect}, time_appconnect: %{time_appconnect}, time_pretransfer: %{time_pretransfer}, time_redirect: %{time_redirect}, time_starttransfer: %{time_starttransfer}, time_total: %{time_total}\n" -o /dev/null -s "https://www.google.com"; sleep 1; done

and here is some sample result:
time_namelookup: 1.059151, time_connect: 1.083971, time_appconnect: 1.129219, time_pretransfer: 1.129803, time_redirect: 0.000000, time_starttransfer: 1.191138, time_total: 1.198772
time_namelookup: 1.058956, time_connect: 1.084363, time_appconnect: 1.130112, time_pretransfer: 1.131392, time_redirect: 0.000000, time_starttransfer: 1.291702, time_total: 1.300107
time_namelookup: 1.057719, time_connect: 1.083355, time_appconnect: 1.128083, time_pretransfer: 1.128726, time_redirect: 0.000000, time_starttransfer: 1.190859, time_total: 1.198635
time_namelookup: 0.018382, time_connect: 0.043042, time_appconnect: 0.077228, time_pretransfer: 0.077517, time_redirect: 0.000000, time_starttransfer: 0.142618, time_total: 0.150624
time_namelookup: 1.058276, time_connect: 1.082821, time_appconnect: 1.127496, time_pretransfer: 1.128083, time_redirect: 0.000000, time_starttransfer: 1.188930, time_total: 1.197614
time_namelookup: 0.023630, time_connect: 0.047877, time_appconnect: 0.079810, time_pretransfer: 0.080053, time_redirect: 0.000000, time_starttransfer: 0.136007, time_total: 0.141614
time_namelookup: 0.018607, time_connect: 0.043160, time_appconnect: 0.079620, time_pretransfer: 0.079966, time_redirect: 0.000000, time_starttransfer: 0.139617, time_total: 0.145728
time_namelookup: 1.059191, time_connect: 1.084436, time_appconnect: 1.127247, time_pretransfer: 1.127825, time_redirect: 0.000000, time_starttransfer: 1.189962, time_total: 1.199934
time_namelookup: 1.058040, time_connect: 1.083303, time_appconnect: 1.127172, time_pretransfer: 1.128314, time_redirect: 0.000000, time_starttransfer: 1.194481, time_total: 1.202276
time_namelookup: 0.018539, time_connect: 0.043664, time_appconnect: 0.079772, time_pretransfer: 0.080074, time_redirect: 0.000000, time_starttransfer: 0.141406, time_total: 0.147358
time_namelookup: 1.060180, time_connect: 1.084996, time_appconnect: 1.130302, time_pretransfer: 1.131054, time_redirect: 0.000000, time_starttransfer: 1.197778, time_total: 1.205363
time_namelookup: 0.031891, time_connect: 0.058458, time_appconnect: 0.097752, time_pretransfer: 0.098055, time_redirect: 0.000000, time_starttransfer: 0.157533, time_total: 0.188634
time_namelookup: 1.059059, time_connect: 1.083472, time_appconnect: 1.126565, time_pretransfer: 1.127196, time_redirect: 0.000000, time_starttransfer: 1.189149, time_total: 1.195730
time_namelookup: 0.023647, time_connect: 0.048197, time_appconnect: 0.082277, time_pretransfer: 0.082772, time_redirect: 0.000000, time_starttransfer: 0.143120, time_total: 0.149757
time_namelookup: 0.017073, time_connect: 0.041658, time_appconnect: 0.081927, time_pretransfer: 0.082310, time_redirect: 0.000000, time_starttransfer: 0.144873, time_total: 0.152739
time_namelookup: 0.017251, time_connect: 0.042056, time_appconnect: 0.079905, time_pretransfer: 0.080475, time_redirect: 0.000000, time_starttransfer: 0.141332, time_total: 0.147886

Doing a dig command however is VERY fast:
 $ dig @dns.google google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u8-Raspbian <<>> @dns.google google.com
; (2 servers found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 13497
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 512
;; QUESTION SECTION:
;google.com.                    IN      A

;; ANSWER SECTION:
google.com.             221     IN      A       172.217.19.78

;; Query time: 25 msec
;; SERVER: 8.8.4.4#53(8.8.4.4)
;; WHEN: Thu Feb 16 10:44:24 UTC 2023
;; MSG SIZE  rcvd: 55

$ dig @1.1.1.1 google.com

; <<>> DiG 9.11.5-P4-5.1+deb10u8-Raspbian <<>> @1.1.1.1 google.com
; (1 server found)
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 54885
;; flags: qr rd ra; QUERY: 1, ANSWER: 6, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1232
;; QUESTION SECTION:
;google.com.                    IN      A

;; ANSWER SECTION:
google.com.             65      IN      A       142.250.147.101
google.com.             65      IN      A       142.250.147.113
google.com.             65      IN      A       142.250.147.138
google.com.             65      IN      A       142.250.147.139
google.com.             65      IN      A       142.250.147.100
google.com.             65      IN      A       142.250.147.102

;; Query time: 13 msec
;; SERVER: 1.1.1.1#53(1.1.1.1)
;; WHEN: Thu Feb 16 10:44:33 UTC 2023
;; MSG SIZE  rcvd: 135

This is similar across multiple internet connection outgoing originating from Denmark
I also had some findings where there was no issues at all. dns resolution was fast etc on one device while there was issues on a other device running though the same ASN-no but different sub ip-range.
MTR/traceroute shows no signs of issues. im just not sure why it goes to 100.x.x.x ip address, but there must be some kind of routing. This does not happen on the other connections
                         My traceroute  [v0.92]
devicename (xx.x.x.xxx)                          2023-02-16T11:50:47+0000
Keys:  Help   Display mode   Restart statistics   Order of fields   quit
                               Packets               Pings
 Host                        Loss%   Snt   Last   Avg  Best  Wrst StDev
 1. xx.x.x.x                  0.0%   211    3.0   2.2   1.4   8.3   0.8
 2. 31.3.xx.xxx               0.0%   211    1.7   2.1   1.4   7.3   0.7
 3. 100.64.x.xxx              0.0%   211    6.8   8.1   6.1  37.8   3.5
 4. 94.127.48.17              1.4%   211    7.4   8.3   6.1  48.0   6.3
 5. xe-2-1-0-311.alb2nqe10.d  0.0%   211    6.9   9.4   6.3  46.4   6.3
 6. ae0-0.stkm2nqp7.se.ip.td  0.0%   211   15.7  16.4  14.8  35.1   2.8
 7. 72.14.214.162             0.0%   211   17.4  17.1  15.3  33.4   2.7
 8. 209.85.254.3              0.0%   211   16.1  17.0  15.4  48.7   3.8
 9. 108.170.253.181           0.9%   211   18.4  17.8  15.2  60.1   6.2
10. 108.170.227.249          10.0%   211   20.6  17.8  15.4  41.2   4.2
    209.85.246.61
11. 142.251.51.215            2.8%   211   26.7  26.4  24.0  54.7   4.6
    209.85.248.7
12. 142.250.214.184           1.4%   210   44.6  25.9  23.7  48.6   4.1
    142.251.239.219
13. 172.253.70.203            0.5%   210   25.1  24.8  23.9  28.2   0.6
    142.250.46.23
14. ???
15. ???
16. ???
17. ???
18. ???
19. ???
20. ???
21. ???
22. ???
23. rd-in-f139.1e100.net     38.3%   210   24.8  25.0  24.1  30.7   0.7

Traceroute shows that it goes to one actual ip address and then to a bogus (100.x.x.x) ip adddress.
traceroute to google.com (142.250.147.102), 30 hops max, 60 byte packets
 1  xx.x.x.x (xx.x.x.x)  2.436 ms  2.624 ms  2.510 ms
 2  31.3.xx.xxx (31.3.xx.xxx)  2.392 ms  2.941 ms  2.834 ms
 3  100.64.x.xxx (100.64.x.xxx)  6.451 ms  6.629 ms  6.519 ms
 4  94.127.48.17 (94.127.48.17)  6.403 ms  6.600 ms  6.762 ms
 5  xe-2-1-0-311.alb2nqe10.dk.ip.tdc.net (87.48.169.225)  6.653 ms  8.382 ms  8.074 ms
 6  ae0-0.stkm2nqp7.se.ip.tdc.net (83.88.2.128)  16.956 ms  16.121 ms  15.401 ms
 7  72.14.214.162 (72.14.214.162)  16.827 ms  16.741 ms  16.650 ms
 8  * * *
 9  108.170.254.33 (108.170.254.33)  17.564 ms 209.85.242.10 (209.85.242.10)  16.346 ms 108.170.253.161 (108.170.253.161)  17.412 ms
10  108.170.254.38 (108.170.254.38)  17.255 ms 108.170.253.182 (108.170.253.182)  17.105 ms 108.170.254.54 (108.170.254.54)  16.645 ms
11  209.85.246.61 (209.85.246.61)  16.484 ms 72.14.234.107 (72.14.234.107)  17.352 ms 142.250.235.228 (142.250.235.228)  17.045 ms
12  108.170.236.41 (108.170.236.41)  26.269 ms  26.088 ms 142.251.51.217 (142.251.51.217)  26.110 ms
13  142.251.239.219 (142.251.239.219)  24.352 ms 142.250.214.198 (142.250.214.198)  26.021 ms 142.250.214.178 (142.250.214.178)  26.295 ms
14  142.250.214.229 (142.250.214.229)  25.056 ms 142.250.215.9 (142.250.215.9)  25.494 ms 142.250.229.93 (142.250.229.93)  25.310 ms
15  * * *
16  * * *
17  * * *
18  * * *
19  * * *
20  * * *
21  * * *
22  * * *
23  * rd-in-f102.1e100.net (142.250.147.102)  25.956 ms *


text:
Q: is it a good practice to inject all my services in root? We have some services that don't hold state but we inject all our service in root, i noticed that has effect on the script evaluation time of our bundle, so should we get rid of this practice?

A: The problem with Singleton services (the problem that you are experiencing) is caused by the fact that those services will be active and stored in memory as long as the application works, while with a non-Singleton you can use the OnDestroy() lifecycle hook and garbage collect stuff to clean the memory.
That being said, if a service needs to be a singleton, it needs to be a singleton.
This is a pattern that is used in every programming language.
If you misuse (or abuse) the pattern, the app is going to be slower for sure.
For example, if you need a service only in a module, you should declare the service in the module level (in the provider's array of the module) and not as a singleton.
If you can use multiple instances of a service (aka you don't need to share the same instance between different components), then don't use a singleton.
But if you really need a singleton, there is no other choice.


text:
Q: ArcMap PostgreSQL unique sequence I have connected my ArcMap to my PostgreSQL db using the Create Enterprise Geodatabase tool in ArcMap. I have multiple feature classes and the relevant relationships between them loaded into the db correctly.
However, I am attempting to add a unique sequence to the feature classes using the postgres sequence function as below:
CREATE SEQUENCE my_sequence;

I then set the default for an integer colum in my tables and assign the sequence as below:
SET DEFAULT nextval('my_sequence');

However, the sequencer works perfectly if I insert data inside PostgreSQL using a SQL statement. If I edit the same table in ArcMap I get the following error when trying to save my edits:
ERROR: duplicate key value violates unique constraint
DETAIL: Key(uniq_id)=(0)already exists

Where am I overlooking something?


text:
Q: URLComponents @ is not encoded import UIKit

func createUrl() {
    var components = URLComponents()
    components.scheme = "https"
    components.host = "services-test.abc.pippo.com"
    components.path = "/first/second/third"
    components.queryItems = createQueryItems()

    // Getting a URL from our components is as simple as
    // accessing the 'url' property.
    let url = components.url
    print("createUrl: \(String(describing: url!))\n\ncomponents: \(components), queryItems: \(components.queryItems)")
}

func createQueryItems() -> [URLQueryItem] {
    var items: [URLQueryItem] = [
        URLQueryItem(name: "amznToken", value: "asfdsfadfasads"),
        URLQueryItem(name: "UID", value: "sdsadasdasdasd"),
        URLQueryItem(name: "login_ID", value: "pippo.pluto@gmail.com"),
        URLQueryItem(name: "ssoEnabled", value: "true"),
    ]

    items.append(URLQueryItem(name: "country", value: "IT"))

    return items
}

createUrl()

This prints:
createUrl: https://services-test.abc.pippo.com/first/second/third?amznToken=asfdsfadfasads&UID=sdsadasdasdasd&login_ID=pippo.pluto@gmail.com&ssoEnabled=true&country=IT

components: https://services-test.abc.pippo.com/first/second/third?amznToken=asfdsfadfasads&UID=sdsadasdasdasd&login_ID=pippo.pluto@gmail.com&ssoEnabled=true&country=IT

queryItems: Optional([amznToken=asfdsfadfasads, UID=sdsadasdasdasd, login_ID=pippo.pluto@gmail.com, ssoEnabled=true, country=IT])

So the @ is not encoded, if I use Alamofire it is encoded.
If I try to encode the string passed in the query item its encoded two times, so how to encode the @?

A: According to RFC 3986, the "@" character is valid in a query string, so the correct behavior would be not to encode it. Refer to Apple's queryItems docs and Wikipedia's Percent Encoding for more information
The solution in your case would be to either encode the queryItems manually,
components.percentEncodedQuery = components.percentEncodedQuery?
    .replacingOccurrences(of: "@", with: "%40")

or alter the behavior of Apple's percent encoding APIs
var urlQueryAllowedCharacters = CharacterSet.urlQueryAllowed
urlQueryAllowedCharacters.remove("@")

components.percentEncodedQuery = createQueryItems().map {
    // Unwrap safely if needed
    let name = $0.name.addingPercentEncoding(withAllowedCharacters: urlQueryAllowedCharacters)!
    let value = $0.value!.addingPercentEncoding(withAllowedCharacters: urlQueryAllowedCharacters)!
    return "\(name)=\(value)"
}.joined(separator: "&")


text:
Q: Child of div to be the same height minus top and bottom paddding Looking to set the height of a child divs to be the same as the parent divs. As it stands the divs gets larger and larger as the page resizes. It's for a search result so there are lots of the same blocks of code.
function legendHeight() {
    $result = $('.search-result');
    $resultHeight = $result.height();
    if($result.find('.legend-lead').length != 0) {
      $(this).children('.legend').height($resultHeight);
    }
};

$(window).load(function () {
    equalheight('.search-result');
    legendHeight();
});
$(window).resize(function () {
    equalheight('.search-result');
    legendHeight();
});

Here is a JSFiddle to show what I mean: https://jsfiddle.net/o0nzo47k/
Although the boxes should resize onload (not why that is not working), if you resize the window you will see the blue divs get taller and taller.

A: OK here is your example working fine https://jsfiddle.net/3wnLeoyd/
the inner divs height(.legend-lead-key and .legend-lead-address) I handled them using css only and I used jquery on the outer height ( to make the height of each div is the same )
The css :
.search-result{
  border-top: none;
  margin-top: 0 !important;
  padding: 20px;
  padding: 1.25rem;
  margin-left: 2.34741784%;
  margin-bottom: 1.875rem;
  background: red;
  width: 25%;
  display:inline-block;
  vertical-align:top;
}

.search-result:nth-child(3n+1) {
  margin-left: 0;
}

.legend-lead{
  display:table;
}

.legend-lead-key {
  background: blue;
  border-right: 1px solid #c7cada;
  display:table-cell;
}

.legend-lead-address{
  display:table-cell;
}

js :
function equalheight(){
    var maxHeight = 0;
  $('.search-result .legend-lead').height('auto');
    $('.search-result').each(function(){
    if($(this).height()>=maxHeight){
        maxHeight = $(this).height();
    }
  })
  return maxHeight;
}

$(window).load(function(){
    $('.search-result .legend-lead').height(equalheight());
})

$(window).resize(function(){
    $('.search-result .legend-lead').height(equalheight());
})


text:
Q: What is the maximum number of hearts you can get? In Zelda: A Link to the Past, it is possible to get additional hearts by completing dungeons (which gives you a full heart), by finding very rare full hearts out in the game world, and by collecting pieces of heart in order to create a new, full heart.
What is the maximum number of hearts you can get?

A: There are 24 heart pieces, yielding 20 max hearts total.
Their locations are shown in detail here.

A: I recall 3 hearts at the beginning, a full heart after you rescue zelda,(four), a full heart for each pendant,(7),a full heart for each crystal, (14), and each row was even, so I believe 20 is correct , leaving 6 hearts to heart pieces, or 24 pieces.


text:
Q: Is there a way to make a DVD screensaver-like HTML element without the marquee tag? My code is as such:

    <marquee behavior="alternate" direction="down" width="100%" height="100%">
        <marquee behavior="alternate" width="100%">
            <button onClick="addPoints(1)">+1</button>
        </marquee>
    </marquee>

This makes it bounce around perfectly within a box container (border). However, the Marquee tag is depreciated and it doesn't give me enough control of the box. Is there an alternate solution, using jquery, javascript, CSS, or HTML? I need to be able to control the speed, detect when it hits a side, and find the X and Y of the button.
I had a working solution before, but it wouldn't let me stop and resume the animation at the same point (I need to be able to). I've seen other alternatives for Marquee but none seem to work the way I want them to, because they use the regular use of marquee rather than the behavior="alternate" setting. I'm experienced in javascript but jquery is new to me so any explanation is appreciated. Thanks!

A: You can also use CSS animations. I'm not familiar with CSS, so I can't make it not exceed the bounds of the container, but this should give you a starting point.

.bounds {
  border: 5px red solid;
  width: 200px;
  height: 300px;
}

@keyframes hor-movement {
  from {
    margin-left: 0%;
  }
  to {
    margin-left: 100%;
  }
}

@keyframes ver-movement {
  from {
    margin-top: 0%;
  }
  to {
    margin-top: 100%;
  }
}

.image {
  animation-name: hor-movement, ver-movement;
  animation-duration: 3.141s, 1.414s;
  animation-iteration-count: infinite;
  animation-direction: alternate;
  animation-timing-function: linear;
}

A: After few minutes of research I've found an open-source repo on github: https://github.com/AlessioMaddaluno/bouncing-dvd-logo. It is a bouncing DVD logo written in vanilla JS. You can control speed and it kinda detects (I'm not really sure if it's the kind of detection you meant). Hovewer, it works only for images.


text:
Q: double free or corruption (!prev) occured using the vector in C++ When I was writing the Iteration Merge Sort Code using the vector in C++,I met the error double free or corruption (!prev) when the vector size n is between 17 and 30;When n is smaller than 17 or larger than 30,there is no error.And the code Implemented sorting function.But I didn't use free or delete,why this error will occur?

#include <iostream>
#include <vector>
#include <cstdlib>
#include <random>
using namespace std;
// v1[left...middle] and v1[middle+1...right] are Ordered,merge them to v2;
void Merge(vector<int> &v1, vector<int> &v2, int left, int middle, int right)
{
    int i = left, j = left, k = middle + 1;
    while (i <= middle && k <= right)
    {
        if (v1[i] <= v1[k])
            v2[j] = v1[i++];
        else
            v2[j] = v1[k++];
        ++j;
    }
    while (i <= middle)
    {
        v2[j++] = v1[i++];
    }
    while (k <= right)
    {
        v2[j++] = v1[k++];
    }
}

// Merge adjacent subsequences of length interval in v1 into v2
void MergePass(vector<int> &v1, vector<int> &v2, int interval)
{
    int i = 0, k = v1.size() - 2 * interval + 1;
    while (i < k)
    {
        Merge(v1, v2, i, i + interval - 1, i + 2 * interval - 1);
        i += 2 * interval;
    }

    /*for (i = 0; i < v1.size() - 2 * interval + 1; i += 2 * interval)
    {
        Merge(v1, v2, i, i + interval - 1, i + 2 * interval - 1);
    }*/
    if (i < v1.size() - interval)
        Merge(v1, v2, i, i + interval - 1, v1.size() - 1);
    else
    {
        for (; i < v1.size(); i++)
        {
            v2[i] = v1[i];
        }
    }
}
void MergeSort(vector<int> &v)
{
    int k= v.size();
    vector<int> v1(k);
    int i = 1;
    while (i < v.size())
    {
        MergePass(v, v1, i);
        i *= 2;
        MergePass(v1, v, i);
        i *= 2;
    }
}

int main()
{

    vector<int> v;
    int n;
    cout << "input the size:";
    cin >> n;
    for (int j = 0; j < n; j++)
    {
        v.push_back(rand() % 1000 + 1);
    }
    MergeSort(v);

A: I have solved this problem.
In MergePass function
if (i < v1.size() - interval)
        Merge(v1, v2, i, i + interval - 1, v1.size() - 1);

the size() returns std::size_t,when v1.size()<interval,v1.size()<interval will get a very large positive integer,Merge(v1, v2, i, i + interval - 1, v1.size() - 1) will still be run.So there is out-of-bounds.I change it to
if (i < (int)v1.size() - interval)
        Merge(v1, v2, i, i + interval - 1, v1.size() - 1);

Thanks to @PaulMcKenzie and everyone helped me.


text:
Q: Transforming/pivoting a DataFrame Instance I have the following pandas data frame:
import pandas as pd
data = dict(store=['A', 'B', 'B'], color=['red', 'black', 'black'], size=['small', 'medium', 'small'], quantity=[2, 4, 1])
df = pd.DataFrame(data)

which looks like this:
  store  color    size  quantity
0     A    red   small         2
1     B  black  medium         4
2     B  black   small         1

What I want to do is the pivot function to create a new data frame that uses the store column as a header and the the quantity value for each of the unique row values of the color and size columns. So it should look like this:
       A   B
black  0   5
red    2   0
small  2   1
medium 0   4

Can this be done? Something like df.pivot(columns='store') seems to be the way to go ...

A: You can use melt and pivot_table():
m=df.melt(['store','quantity'])

m.pivot_table(index='value',columns='store',values='quantity',aggfunc='sum',fill_value=0)

store   A  B
value
black   0  5
medium  0  4
red     2  0
small   2  1


text:
Q: GetWindowDC works not correctly I am running the code sample in Charles Petzold's "Programming Windows" book, the "Bitmaps and BitBlts" chapter. The program is supposed to display the IDI_INFORMATION icon on the left top corner of the program window on its client area multiple times. But it seems like there are some problems with the GetWindowDC() function, because the program display some area outside its entire window instead. Can someone help please? Sorry if my English were bad.
/*−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
BITBLT.C −− BitBlt Demonstration
(c) Charles Petzold, 1998
−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−*/
#include <windows.h>

LRESULT CALLBACK WndProc (HWND, UINT, WPARAM, LPARAM) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance, PSTR szCmdLine, int iCmdShow)
{
    static TCHAR szAppName [] = TEXT ("BitBlt") ;

    HWND hwnd ;
    MSG msg ;
    WNDCLASS wndclass ;

    wndclass.style = CS_HREDRAW | CS_VREDRAW ;
    wndclass.lpfnWndProc = WndProc ;
    wndclass.cbClsExtra = 0 ;
    wndclass.cbWndExtra = 0 ;
    wndclass.hInstance = hInstance ;
    wndclass.hIcon = LoadIcon (NULL, IDI_INFORMATION) ;
    wndclass.hCursor = LoadCursor (NULL, IDC_ARROW) ;
    wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH) ;
    wndclass.lpszMenuName = NULL ;
    wndclass.lpszClassName = szAppName ;

    if (!RegisterClass (&wndclass))
    {
        MessageBox (NULL, TEXT ("This program requires Windows NT!"),
        szAppName, MB_ICONERROR) ;
        return 0 ;
    }

    hwnd = CreateWindow (szAppName, TEXT ("BitBlt Demo"),
        WS_OVERLAPPEDWINDOW,
        CW_USEDEFAULT, CW_USEDEFAULT,
        CW_USEDEFAULT, CW_USEDEFAULT,
        NULL, NULL, hInstance, NULL) ;

    ShowWindow (hwnd, iCmdShow) ;
    UpdateWindow (hwnd) ;

    while (GetMessage (&msg, NULL, 0, 0))
    {
        TranslateMessage (&msg) ;
        DispatchMessage (&msg) ;
    }

    return msg.wParam ;
}

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    static int cxClient, cyClient, cxSource, cySource ;

    HDC hdcClient, hdcWindow ;
    int x, y ;
    PAINTSTRUCT ps ;

    switch (message)
    {
        case WM_CREATE:
            cxSource = GetSystemMetrics (SM_CXSIZEFRAME) + GetSystemMetrics (SM_CXSIZE) ;
            cySource = GetSystemMetrics (SM_CYSIZEFRAME) + GetSystemMetrics (SM_CYCAPTION) ;
            return 0 ;

        case WM_SIZE:
            cxClient = LOWORD (lParam) ;
            cyClient = HIWORD (lParam) ;
            return 0 ;

        case WM_PAINT:
            hdcClient = BeginPaint (hwnd, &ps) ;
            hdcWindow = GetWindowDC (hwnd) ;
            for (y = 0 ; y < cyClient ; y += cySource)
                for (x = 0 ; x < cxClient ; x += cxSource)
                {
                    BitBlt (hdcClient, x, y, cxSource, cySource, hdcWindow, 0, 0, SRCCOPY) ;
                }
            ReleaseDC (hwnd, hdcWindow) ;
            EndPaint (hwnd, &ps) ;
            return 0 ;

        case WM_DESTROY:
            PostQuitMessage (0) ;
            return 0 ;
    }

    return DefWindowProc (hwnd, message, wParam, lParam) ;
}

This is the link to the program output


text:
Q: Extracting the first formatted line from some RTF/HTML text OK, I painted myself into a corner on this one and haven't decided the way out yet.
My web application hosts a series of documents written by users, and edited with the CLEditor editor via PrimeFaces.   The documents can be any size and have any formatting the user chooses.
What I want to do is treat the first line of the document as a title, so that when I create a listing of those documents I show only the title, then the user can click on that table row to see the whole document.  I show the title with
<h:outputText value="#{backBean.doc}" escape="false" />

What I did is pull the substring of the document out up until but not including the first pattern of the br tag.   That works unless the user applies formatting that spans past that.  The resulting string has unclosed HTML tags usually div or span) and when they are output without escaping they interfere or even blank out the rest of the page.
So I am looking for an easy solution to fix the HTML fragment.  I would rather not import a huge library such as JTidy because it pulls in all sorts of dependencies I don't have right now like a DOM parser, etc.  Can anyone suggest a cheaper yet robust solution?  Is there any way to clean this up on the client side?

A: I'd suggest Jsoup.
To parse the HTML and get its <body> content, it's a matter of this oneliner:
String htmlBody = Jsoup.parse(userInput).body().html();

By the way, since you seem to intend to redisplay user-controlled HTML unescaped, I strongly recommend to whitelist it to prevent XSS. E.g.
String safeHtmlBody = Jsoup.clean(htmlBody, Whitelist.basic());

This way you can safely redisplay it without worrying about a XSS attack hole:
<h:outputText value="#{bean.safeHtmlBody}" escape="false" />

See also:

*

*What are the pros and cons of the leading Java HTML parsers?

*How to implement a possibility for user to post some html-formatted data in a safe way?

*CSRF, XSS and SQL Injection attack prevention in JSF

A: You should be escaping the partial contents of the document somehow, otherwise users can upload documents containing HTML/JavaScript code that will compromise your site. As you can see, even simple formatting can break it.  One solution could be to remove all tags (via regex, string replace, etc) and then escape the title.

A: I figure out the JTidy way of doing it.  This seems very heavy-handed to me but I'm going with it until something better is suggested.  Also if someone else is in this situation it might be useful:
public class TitleRTF {

private static final Pattern pTidy = Pattern.compile("<body>(.*)</body>");

public TitleRTF() {}

public static String getTitle(String rtfSource) {

    org.w3c.tidy.Tidy tidy = new org.w3c.tidy.Tidy();
    tidy.setQuiet(true);

    ByteArrayInputStream bais = new ByteArrayInputStream(rtfSource.getBytes());
    org.w3c.dom.Document doc = tidy.parseDOM(new BufferedInputStream(bais), null);
    try {
        Transformer tr = TransformerFactory.newInstance().newTransformer();
        StreamResult result = new StreamResult(new StringWriter());
        NodeList list = doc.getElementsByTagName("body");
        if (list.getLength() > 0) {
            DOMSource source = new DOMSource(list.item(0));
            tr.transform(source, result);
            String text = result.getWriter().toString();
            Matcher m = pTidy.matcher(text);
            if (m.find()) return m.group(1);
        }
    } catch (TransformerException ex) {        }
    return "(not parsable)";
}
}

One thing that needs to be added to this is a way of keeping JTidy from logging what it sees as HTML errors.  The setQuiet(true) doesn't seem to do it.


text:
Q: how to mark cell when the row data is changing on ssrs I have a SSRS report.
I have an order columns.
I want to mark both rows where order is changing in yellow

How to do like this?

A: Give this a try. Make a Parent Group on your STR_ORDER_ID. Don't create a header and remove the column only (after you create the group). The only issue here is that you'll get the coloring on the first and last row of the report.
    =IIF(RowNumber("GroupName") =  CountRows("GroupName"), "LightBlue",
 IIF(RowNumber("GroupName") = 1, "LightBlue","Silver"))


text:
Q: JQuery how to listen for a element attribute/property change event JQuery 1.12.1 (inherited and can't be updated to 3)
$('#subBut').onchange(function() {
    if($('#subBut').prop('disabled')) {
        $('#reasons').slideDown();
    }
    else {
        $('#reasons').slideUp();
    }
});

How can I check for when the property of the element changes, and run the change to #reasons based on that change?
This seems surprisingly hard to do natively and some people point to plugins which I want to avoid and other (very old) questions on here relate to simply not being able to do it!
I need the event to fire when a property on an element changes; the change is caused by a range of other parts of JQuery code so it's best this is seperate and listens independant of what causes the change.
I tried things like $('#subBut').prop().onchange(function() { and similar but these are bad syntax.
It is NOT the value of the element that changes.

A: For reference, PrettyinPink's Comment was what was needed; looking up Mutation Observer rather than the older and more prolific Mutation Event was what was needed:
// Here we watch for new elements
const observer = new MutationObserver(function () {
    console.log('observed!');
    if($('#subBut').prop('disabled')) {
        $('#reasons').slideDown();
    }
    else {
        $('#reasons').slideUp();
    }
});

// Param 1 of observe() must be a Node - document is a valid Node,
// but not advisable, limit the watcher to as small a context as possible
// Important here to set attributes to be true to check these.
observer.observe(document.getElementById('subBut'), {
   attributes: true
});


text:
Q: Can an Android (Java not C/C++) plugin alter unity textures? I'm trying to use an Android plugin to get around the fact that Unity does not support Video Textures on mobile. I do this by getting the texture ID of the texture that will be used for video (supplied by Texture2D.GetNativeTextureID()) which i then pass into the Java Plugin.
The plugin then follows a standard MediaPlayer implementation to play the video into a Surface Texture, which has been assigned the aforementioned texture ID.
When i call the MediaPlayer.Start() method, LogCat outputs as if the media player is working normally/as hoped, however the texture never changes in the app. I'm calling the plugin (and even initializing it) from the OnPreRender() method of a monobehaviour script, along with making sure to call GL.InvalidateState() too.
Here's a look at the relevant code:
Constructor:
public VideoPlayer(String _path, Context _cont) {
    m_MediaPlayer = new MediaPlayer();
    try {
        Uri uri = Uri.parse(_path);
        m_MediaPlayer.setDataSource(_cont, uri);
        m_MediaPlayer.setOnPreparedListener(this);
    }
    catch (IOException e) {
        Log.e(TAG, "Error setting data source: " + e.getMessage());
    }
}

Surface Texture Prep:
public void PrepareVideo(int _texPtr) {
    try {
        m_SurfTex = new SurfaceTexture(_texPtr);
        m_SurfTex.setOnFrameAvailableListener(this);
        Log.i(TAG, "Surface Texture ready");
        Surface surface = new Surface(m_SurfTex);
        m_MediaPlayer.setSurface(surface);
        Log.i(TAG, "Surface Ready");
        surface.release();
        m_Ready = true;
        m_MediaPlayer.prepare();
    }
    catch (IOException | IllegalStateException e) {
        Log.e(TAG, "Error preparing player: " + e.getMessage());
        m_Ready = false;
    }
}

I'd like to know if this type of process is possible with my current setup, or will have to look into writing something using the NDK instead? Specifically, can a surface texture alter a texture produced in Unity?

A: Did you try creating the surfacetexture in the unity rendering thread, for example by overriding runglthreadsjobs in an extended UnityPlayer? That would make sure it bound to the correct glcontext AFAIK.
I have tried sharing contexts, but couldn't get it to work as documentation is sparse and unity is pretty closed down.
In unity 4.2 its a lot easier apparently.

A: It would appears that while i have found nothing explicitly states that this CAN be done, there is no real information or any examples of it having been done before.
I'll be attempting a re-working of this in native C++ code.