text:
Q: alternative for function preg_replace e/ modifier Anybody knows how to change this function with preg_replace and the e/ modifier
The e/ modifier will be depreciated.
function charset_decode_utf_8 ($string) {
      /* Only do the slow convert if there are 8-bit characters */
    /* avoid using 0xA0 (\240) in ereg ranges. RH73 does not like that */
    if (! preg_match("/[\200-\237]/", $string) and ! preg_match("/[\241-\377]/", $string))
        return $string;

    // decode three byte unicode characters
    $string = preg_replace("/([\340-\357])([\200-\277])([\200-\277])/e",
    "'&#'.((ord('\\1')-224)*4096 + (ord('\\2')-128)*64 + (ord('\\3')-128)).';'",
     $string);

    // decode two byte unicode characters
    $string = preg_replace("/([\300-\337])([\200-\277])/e",
    "'&#'.((ord('\\1')-192)*64+(ord('\\2')-128)).';'",
    $string);

return $string;
}

A: <?php
$string = preg_replace_callback("/([\340-\357])([\200-\277])([\200-\277])/",
    function($arr) {
        $val = (ord($arr[1]) - 224) * 4096
                + (ord($arr[2]) - 128) * 64
                + (ord($arr[3]) - 128);
        return "&#" . $val . ";";
    }, $string);

$string = preg_replace_callback("/([\300-\337])([\200-\277])/",
    function($arr)
    {
        $val = (ord($arr[1]) - 192) * 64 + ord($arr[2]) - 128;
        return "&#" . $val . ";";
    }, $string);


text:
Q: before_filter running out of order, working fine in dev and staging env. but not working on qa env
We have following filters in controller:

  before_action :authenticate_api_request!, except: [:reply_messages]
  before_action :community_uuid
  before_action :is_user_blocked?, only: [:create, :like, :dislike, :flag, :reply_message]
  before_action :user_confirmed_email?, only: [:create]
  before_action :get_message, only: [:like, :dislike, :flag, :remove, :get_message_json, :reply_message, :reply_messages]
  before_action :get_reply_message, only: [:reply_message]
  before_action :get_group, only: [:create]
  before_action :is_blocked_from_group?, only: [:create, :like, :dislike, :reply_message]

and order in which they are executed is:
user_confirmed_email?
get_message
get_reply_message
authenticate_api_request!
community_uuid
is_user_blocked?
get_group
is_blocked_from_group?

The problem here is authenticate_api_request!, community_uuid and is_user_blocked? is called after user_confirmed_email?.
Its working properly in dev and staging environment but not working same code on qa server, didn't get why this happen even replicate same code.

A: Check Filter Chain Ordering and this other answer.
You have to specify :prepend_before_filter so that your filters are executed on the beginning of the chain.
Notice that :prepend_before_action is an alias of :prepend_before_filter, prepend_before_action.
I haven't tried it myself but you might write something like:
  before_action :user_confirmed_email?, only: [:create]
  before_action :get_message, only: [:like, :dislike, :flag, :remove, :get_message_json, :reply_message, :reply_messages]
  before_action :get_reply_message, only: [:reply_message]
  before_action :get_group, only: [:create]
  before_action :is_blocked_from_group?, only: [:create, :like, :dislike, :reply_message]
  prepend_before_action :is_user_blocked?, only: [:create, :like, :dislike, :flag, :reply_message]
  prepend_before_action :community_uuid
  prepend_before_action :authenticate_api_request!, except: [:reply_messages]

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can't find IDOK (1) in the custom UI! How to add a custom OK Button in NSIS? Please Help ! In NSIS, I'm using
!define MUI_PAGE_CUSTOMFUNCTION_SHOW LicenseShow

then
Function LicenseShow

  ; New dialog for custom items
  nsDialogs::Create 1018
  Pop $0

  ; Accept button
  ${NSD_CreateButton} 373, 223, 50, 14 "Accept"  ; Can't find IDOK (1) in the custom UI!

  ; Decline button
  ${NSD_CreateButton} 21, 223, 50, 14 "Decline"

  ; Picture
  ${NSD_CreateBitmap} 5 5 100% 100 "disclosure.bmp"
  Pop $0
  ${NSD_SetImage} $0 $PLUGINSDIR\image.bmp $ImageHandle

  ; Disclaimer
  nsDialogs::CreateControl /NOUNLOAD ${__NSD_Text_CLASS} ${DEFAULT_STYLES}|${WS_TABSTOP}|${ES_WANTRETURN}|${ES_MULTILINE} ${__NSD_Text_EXSTYLE} 5 220 660 115 ''
  Pop $1
  SendMessage $1 ${EM_SETREADONLY} 1 0
  SetCtlColors $1 0x000000 0xFFFFFF
  ${NSD_SetText} $1 "The license text"

  nsDialogs::Show
  ${NSD_FreeImage} $ImageHandle

FunctionEnd

How do I tell that the Accept button has the IDOK on it ?
Please help.

A: You can set the id by calling System::Call 'user32::SetWindowLong(i $myhwnd,i -12,i $mynewid)' but what you really should be doing is setting up callback functions:
...
${NSD_CreateButton} ...
pop $0
${NSD_OnClick} $0 userclicked
...
Function userclicked
MessageBox mb_ok Hello
SendMessage $hwndparent ${WM_COMMAND} 1 0
FunctionEnd


text:
Q: Is it better to re-use view controllers or it's better to separate the logic I am using a couple of different services to display articles from feeds. They can all be displayed using one view controller, however I must make a property indicating from which service the user is coming, and to check it every time I want to do something with those articles.
I have experience in this method - and believe me there are a lot of spaghetti code, just to check out which service it is, to decide what do to for each service, it's a little messy.
So I have 2 options:
1st - re-use the ArticlesViewController for all services, but check from which one is the articles coming from, and do different things based on that when I want to edit those articles.
2nd - make FacebookArticlesViewController,TwitterArticlesViewController, SinaWeiboArticlesViewController (just examples), for each service, and separate the logic.
What do you think is the best approach?

A: Surprise third option!
Make a protocol or a base class named ArticlesViewControllerSourceDelegate.  For each place in ArticlesViewController where you'd have logic that varies based on the article source, add a selector to ArticlesViewControllerSourceDelegate.
Then make an implementation or subclass of ArticlesViewControllerSourceDelegate for each article source.

A: 1 st option is better because you do not duplicate any code. In future if you have to change the UI you'll have to change it in only one place. If you go with second approach, you'll have to change stuff in all view controllers and theres a big chance you'll miss something out.
Also, what you can do is, create a parent article view controller with all common stuff and inherit separate article view controllers only for those types of articles which need lot of customization.
And if the differences in your articles are largely related to business logic and not UI, it would be better to have separate business layer managing all this stuff. And of course, you can implement same kind of inheritance i mentioned in above paragraph for these business layers.


text:
Q: MySQL for Spyder(Python 3.5) I'm trying to find out if I can use MySQL via the Spyder IDE (Python 3.5 edition. I've had a look around and know its possible to use Python with MySQL (I've done that already a long time ago now), however, I can't seem to find any solutions to my particular question/problem. The examples I've looked at won't work for Spyder...?  Is there anyone out there who might know?
Many thanks!


text:
Q: How can I convert a Char(16) column into a Date Datatype column? I imported a CSV file (2 million records) into a derby database but always struggled to import the column with this content: "2002-09-06 00:00" as a TIMESTAMP datatype. So I changed the database column to Char(16) instead of TIMESTAMP and was able to import the file without an error.
Now I would like to convert the Char(16) column with 2 million records into a DATE datatype column or copy and convert it into a new column with DATE Datatype. Or whatever other solution you can come up with!
I was thinking of something like this
CONVERT(DATE, 101)

but I have no idea how to connect it with the already existing column.. I really suck at SQL.
Help would be appreciated!
Thank you very much!

A: SQL Server is pretty good about converting date/times.  So you can just use:
convert(datetime, '2002-09-06 00:00')

or better yet:
try_convert(datetime, col)

I recommend loading the data into a staging table.  Then transforming it in the database to the structure that you want.  That way, you can investigate any conversion issues (or other transformation issues) because you have the loaded data.


text:
Q: Why do LDMOS RF power transistors have a low real resistance? I've been looking through datasheets for RF LDMOS amplifiers for use in an RF power amplifier. They typically have an input impedance that has some small real part of the resistance (<10 Ω) with a larger reactive component.
I can understand the reactive component being large due to bond wires or capacitive effects that would dominate due to the structure of the transistor silicon itself, but I'm confused about why we have such a low real part of the resistance.
LDMOS transistors seem to have their gates completely isolated from anything that could provide a low-resistance path to ground. Where does this low-resistance part of the input impedance of the resistor come from?
I think I'm either not understanding how the input impedance is measured correctly or not understanding the structure of the LDMOS internally correctly. The other potential explanation I could come up with is that this isn't the traditional ohmic losses that you might associate with a resistor, but more along the lines of dielectric loss that occur when you get an imaginary part to the effective dielectric constant.

A:
They typically have an input impedance that has some small real part of the resistance (<10 ohms) with a larger reactive component.

An ideal capacitor/inductor has zero real resistance. So it's all as expected! The input impedance has a fairly low ESR that's related to ohmic/bulk resistances.


text:
Q: Using a variable value from one method in different one in Android Studio Firstly sorry for asking so many questions here the past couple of weeks, I'm new to android studio and finding it tough to figure out a lot of the core concepts by myself.
In regards to the question, I have a project set up so whatever you type into the "1.2, -1.2" ect parameters you will find you the distance between two places and your answer will be displayed as a toast. However, I want the latitudes and longitueds to be variables.
Button button1=(Button) findViewById(R.id.button1);
        button1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Double distance = 1.0;
                int val = 1;

                Toast.makeText(getApplicationContext(), "You are "     + String.valueOf(distance
                        (1.2, -1.2, 1.3, -2.4, "K")) + "kilometers away     from the flag", Toast.LENGTH_LONG).show(); }
        });

I have the following two methods and I want the values LatLng and currentLatitude and currentLongitude doubles for the parameters above.
    private void setUpMap() {
mMap.addMarker(new MarkerOptions().position(new LatLng(53.3835,6.5996)).title("Marker"));
}

and
private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        double currentLatitude = location.getLatitude();
        double currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude,     currentLongitude);

        //mMap.addMarker(new MarkerOptions().position(new     LatLng(currentLatitude, currentLongitude)).title("Current     Location"));
        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("I am here!");
        mMap.addMarker(options);
          mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
    }

Any insight on how to do it would be much appreciated. From what I've read I know I'll need to split the LatLng variable into strings but thats all I can think of so far

A: If those 2 methods are in the same class then just make those 2 variables attributes of that class, else you will need to pass them to the corresponding classes. I will demonstrate in a simpler example than your code :
public class MyClass(){

    private int lat;
    private int longt;

//constructors ,setters and getters

    public void method1(){

//affecting those attributes with values
        lat = 1;
        longt = 2;

    }

    public void method2(){

        //simply access the attributes
        System.out.println("lat "+lat+"  longt  "+longt);

    }

}

Reading the comments , I think I need to further explain to you that when a variable is declared inside a method, it is local to that method, and therefor it will be "destroyed" (garbage collected or w.e) when that method is done doing it's job. But when a variable is declared outside a method, like the class's attributes, you can still refer to it whenever you need to, until the instance of that class is "destroyed".


text:
Q: General exception handling without global.asax file I was wondering if there was a way to catch all unhandled exceptions in a visual studio project. My project does not have any files named global or global.asax so I was wondering if there was some other way to catch any and all unhandled exceptions? So far I've tried to put exception handling around specific blocks of code, but it doesn't have any effect.

A: You can add a global.asax file to your website and add an implementation for Application_Error and all exceptions that are thrown during processing a request will make their way there.  After handling the exception, call Server.ClearError() to prevent the default ASP.NET error page from showing up.
Another alternative is to install ELMAH in your project, which is a very nice and very customizable error handling framework.

A: simply add global.asax, add new item and choose "Global Application Class"

A: I mentioned here about both Page/Application Level handling


text:
Q: SQL Server database backup error I am trying to solve a backup problem for SQL Server 2012 for some time now.
The problem is I not able to make backup TO DISK, I think it is directory error
Query used:
BACKUP DATABASE [ProjectDatabase]
TO DISK = 'C:\Users\AizazHussain\Dropbox\TestProjectBackup.bak';

OR
BACKUP DATABASE [ProjectDatabase]
TO DISK ='C:\TestProjectBackup.bak';

Both attempts failed.
If I use the directory C:\BackupFolder\TestProjectBackup.bak, it works fine. Somewhere on Stack overflow there was a solution to create backup in a folder so I created BackupFolder in C:\ and it works fine.
Note: it worked fine for other partitions
e.g.
BACKUP DATABASE [ProjectDatabase]
TO DISK ='D:\TestProjectBackup.bak';

BACKUP DATABASE [ProjectDatabase]
TO DISK ='D:\Folder\TestProjectBackup.bak';

// It works but only for C:\

Pardon me if there are any grammatical mistake in my question

A: SQL Server executes BACKUP DATABASE command under the context of the service account. This account is usually MSSQLSERVER. This account is configured in Services:

This account must have Modify permissions to the backup target directory:

SQL Server must be able to read and write to the device; the account
  under which the SQL Server service runs must have write permissions.

(Source: BACKUP (Transact-SQL))
Check your NTFS permissions.


text:
Q: Reordenar div quando o navegador é redimensionado Como posso fazer com que a div "col-md-3" seja a primeira a ser exibida quando o navegador é redimensionado?
Repare que usei a classe "order-last" para que ela seja exibido por ultimo em resolução normal, porém, quando redimensiono o navegador, quero que essa div seja a primeira a ser exibida.
Segue codigo:

<!DOCTYPE html>

        <title>Exemplo</title>
        <meta charset="uff-8">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-iYQeCzEYFbKjA/T2uDLTpkwGzCiq6soy8tYaI1GyVh/UjpbCx/TYkiZhlZB6+fzT" crossorigin="anonymous">

                            1) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sed malesuada ex. Nam in ullamcorper tortor, ac tempor erat.

                            2) Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur sed malesuada ex. Nam in ullamcorper tortor, ac tempor erat.

Para melhor compreensão, seguem as imagens abaixo.
Até aqui esta tudo bem. Este é o comportamento que quero quando o navegador esta com a resolução "normal".

Quando o navegador é redimensionado, as divs ficam desta forma. Porem quero que a div com o paragrafo "1" seja apresentado primeiro.

A: No lugar de utilizar order-last utilize order-first order-sm-last.


text:
Q: Make qt4 designer under linux to use python3 for handling custom widgets plugins I use this script to start qt designer with my custom widgets (in Python 3) visible:
#!/usr/bin/env python3

import os, sys, subprocess

curDir = os.path.dirname(os.path.abspath(__file__))
params = list(sys.argv) # copy list
params[0] = 'designer' # "designer-qt4" on Linux

widgetsDir = os.path.join(curDir, 'wic', 'widgets')

# add search path for custom widgets and plugins for designer
os.putenv('PYQTDESIGNERPATH', widgetsDir)

subprocess.Popen(params)

But it looks like designer is using python 2.7 to use the widget plugins:
vic@ubuntu:~/wic$ python3 qt_designer.pyw
vic@ubuntu:~/wic$   File "/home/vic/wic/wic/widgets/w_date_edit_plugin.py", line 63
    app.exec()
           ^
SyntaxError: invalid syntax

How to instruct designer to use Python 3, not Python 2?
I use Kubuntu 11.10, KDE 4.7.2, python3.2 and python2.7, PyQt v4.8.5 compiled for Python 3

A: It looks like PyQt does not allow for side-by-side installation of the designer plugin that handles custom widgets (libpythonplugin.so). So there will normally be a single plugin linked against either python2, or python3, but not both.
It would appear that Kubuntu currently installs the python2 version of the plugin (on my linux system, it's the other way around). If you want a python3 version of the plugin, just compile a replacement from source.
EDIT
To compile a replacement, first ensure you have the sip packages installed. I am no expert on ubuntu, but I think you will need the python-sip-dev and python3-sip-dev packages (plus any dependencies, of course).
Next, download the PyQt4 sources that match the version installed on your system. I was able to find some ubuntu pyqt source packages here.
Now unpack the tarball, cd into the resulting source directory (looks like it should be PyQt-x11-gpl-4.8.5 for Kubuntu 11.10), and then configure the build using python3:
$ cd ~/tmp
$ tar -xf python-qt4_4.8.5.orig.tar.gz
$ cd PyQt-x11-gpl-4.8.5
$ /usr/bin/python3.2 configure.py -c -j 4

If that completes without error, build it (but do not install it):
$ make

Using the above configuration options it takes about 5 mins to compile pyqt on my old i686-AMD64-X2-6000 system. Once complete, the libpythonplugin.so plugin should be in the PyQt-x11-gpl-4.8.5/designer directory.
You can now backup and remove the existing plugin (on my system it's in the /usr/lib/qt/plugins/designer directory), and copy over your new plugin.


text:
Q: How does an error handler work internally? I know that there has to be quite a lot of documentation about this topic on the internet.
But doing research for hours without a proper answer is quite frustrating. So I assume I can't put my question in a good phrase. So here the full version:
I'm doing a presentation about try-catch, but it's rather boring to do the basic things. I know what try catch is and I know how it works.
But here comes the magic: Let's assume I use C++.
The compiler will create a read only list on the heap with structures that give information about the functions in the try-block. That includes pointers for start and end of the routine, information about about the object type of the exception and so on. (Please correct me if I'm wrong)
Okay. Now an exception occurs. The so called error handler (here we go, who is the error handler?) will look up all the data about the failing routine and get the appropriate catch routine. The correct catch is found by comparing the exception object that is generated through the error with the exception objects in the catch.
For example: InvalidCastException (or something like that) is created. There is a catch for that, the error is handled and all objects that are created in the try block are destroyed.
But: How can the program notice that there is an exception? Is this handled by the program, by the runtime or maybe even by the processor (I read something about Ring0 and Ring1, different levels in the CPU oO).

A: There are two ways of implementing exception handling in C++. First is to use Itanium ABI Zero-Cost exception handling. The second one is to use a pair of setjmp/longjmp to handle control flow for exceptions. The first is a preferred implementation for every modern compiler.
The program does not "listen" for exceptions, so it doesn't notice exceptions. Instead, it raises and processes them as part of the control flow. For example, "throw" is always raising an exception which triggers transfers the execution to exception handling code.
Even though these exceptions are heavily used in C++ which provides a nice interface to "throw" and "catch" them, they are also used in C, and even in the Linux kernel.
You can read more here:

*

*http://sourcery.mentor.com/public/cxx-abi/abi-eh.html

*http://llvm.org/docs/ExceptionHandling.html

*Zero cost exception handling vs setjmp/longjmp


text:
Q: Change Similarity per query in elasticsearch I know that we can set similarity in mapping but I need to change similarity  at query time. I need scores to be calculated in different ways by changing similarity. Is there any way to do so.

A: From Official Doc

The similarity can be set on the field level when a field is first created, as follows:

So no you cant change it at query time. Im not even sure if you can change it by updating your mapping.


text:
Q: Using Host Array in Open Cursor in Embedded SQL I have this embedded SQL code:
EXEC SQL
  OPEN MY_CURSOR USING :a1
END-EXEC

Where a1 is Array with 20 items, but I don't know in forward how many Host Variables I will need. It can be from 1 to 20. If I use it in this way, and actually I am using only 5 items from array, I got this error:

SQLCODE: -10000, SQLSTATE: 24000, SQLERRMC: Invalid Cursor State

Is there any possibility how to in OPEN CURSOR section send number of used items in array? Or I must use array with exact number of items?

A: The host variables in the "OPEN CURSOR" statement refer to parameters in the where clause.
Not data is returned on OPEN.
Instead you get each individual row by issuing a "FETCH INTO :var1, :var2 ..."
much the same a single row select.
See docs here:
https://learn.microsoft.com/en-us/sql/t-sql/language-elements/fetch-transact-sql?view=sql-server-ver15


text:
Q: Strategies for reducing data to summaries within a table over time? I have a large data set where large numbers of entries differ only by timestamp.  In the short term it's beneficial to maintain individual entries so that we can correlate by time for individual data points.  But after enough time passes, that level of granularity is unnecessary and I'm comfortable replacing those individual entries with a summarized entry by means of a count column.
So if the table has entries this when it's fresh:
+---------------------+------+-------+
| stamp               | data | count |
+---------------------+------+-------+
| 2016/01/01:12:54:00 | abcd | 1     |
| 2016/01/01:12:56:58 | abcd | 1     |
| 2016/01/01:13:02:36 | abcd | 1     |
+---------------------+------+-------+

I'm happy to combine all the entries of a given hour after, say, a week:
+---------------------+------+-------+
| stamp               | data | count |
+---------------------+------+-------+
| 2016/01/01:12:00:00 | abcd | 2     |
| 2016/01/01:13:00:00 | abcd | 1     |
+---------------------+------+-------+

And maybe after a month I only care about the granularity of a day:
+---------------------+------+-------+
| stamp               | data | count |
+---------------------+------+-------+
| 2016/01/01:00:00:00 | abcd | 3     |
+---------------------+------+-------+

This isn't hard to do in SQL (PostgreSQL shown here):
select distinct(date_trunc('hour', stamp),data,sum(count)
into table tmpdata
from data
where stamp < now() - interval '7 days'
group by date_trunc('hour', stamp),data;

...and then clear the rows I just summarized out of data and replace them with the summaries I created in tmpdata...  It seems preferable to keep the data within a single table rather than have separate tables for different granularity of data.
This all works, but it's awkward, and I'd like to learn a better way if there is one.  So I have two questions:

*

*What is the name for this sort of summary-replacement-of-data-over-time?  I would say the data is being coalesced, but COALESCE has a distinct other meaning in SQL.  It would help to know the terminology used to describe this sort of thing so I can tag it and talk about it properly.

*What strategies / algorithms / methods of achieving this goal would you recommend, with an eye towards elegance?

A: I would simply call it "aggregation".
As for elegance, you can do this with a single SQL command without another table using a data-modifying CTE:
For (only) hourly aggregation of rows that are older than a week:
WITH del AS (
   DELETE FROM data d
   WHERE  stamp < now() - interval '7 days'   -- ">" would be wrong
   AND   (date_trunc('hour', stamp) <> stamp  -- not truncated yet.
          OR EXISTS (  -- more than one in same hour
             SELECT 1
             FROM   data
             WHERE  date_trunc('hour', stamp) = date_trunc('hour', d.stamp)
             AND    ctid <> d.ctid   -- except self
             )
         )
   RETURNING *
   )
INSERT INTO data(stamp, data, count)
SELECT date_trunc('hour', stamp), data, sum(count)
FROM   del
GROUP  BY 1,2;

Only replaces rows that need replacing. Repeated calls would not repeat writes.
If you know a lower bound where all rows have been aggregated already, add another WHERE condition to make it faster:
AND stamp > $lower_bound

Obviously, you need an index on stamp or, ideally, a partial index only including rows younger than $lower_bound that would need to be recreated from time to time. Related:

*

*PostgreSQL partial index unused when created on a table with existing data

*Add datetime constraint to a PostgreSQL multi-column partial index
Using ctid since no PK is defined.

*

*In-order sequence generation

*How do I decompose ctid into page and row numbers?
You may want to VACUUM FULL data; to reclaim table bloat after that. But be aware of implications. Maybe pg_repack is for you:

*

*VACUUM returning disk space to operating system
Aside: DISTINCT and GROUP BY was redundant in your original query. And you were aggregating rows younger than a week instead of older.


text:
Q: How to display text in center if use verticalText? My code
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.setVerticalLayout(marginLeft + squareHeight, 1191.0f - marginTop, squareHeight, 3, 20);
vt.setAlignment(Element.ALIGN_CENTER);
Paragraph p = new Paragraph(imgr.getText(), fontV);
p.setLeading(10);
vt.addText(p);
vt.go();

The result : Text is middle in vertical mode.
I want to display text is center in horizontal mode as below link:

How to solve this problem ?

A: As documented, left, center and right align has a different meaning in the context of VerticalText. Left is top, center is middle and right is bottom.
With class VerticalText, you always write from right to left. There is currently no way to align the text as shown in the screen shot to the right.
However, you could work around this problem by adding the vertical text in simulation mode first and then calculate the number of lines that have been written.
See for instance the VerticalText1 example from my book. I have adapted the code of that example like this:
BaseFont bf = BaseFont.createFont(
    "KozMinPro-Regular", "UniJIS-UCS2-V", BaseFont.NOT_EMBEDDED);
Font font = new Font(bf, 20);
VerticalText vt = new VerticalText(writer.getDirectContent());
vt.setVerticalLayout(390, 570, 540, 12, 30);
vt.addText(new Chunk(MOVIE, font));
vt.go();
System.out.println(vt.getMaxLines());
vt.addText(new Phrase(TEXT1, font));
vt.go();
System.out.println(vt.getMaxLines());
vt.setAlignment(Element.ALIGN_RIGHT);
vt.addText(new Phrase(TEXT2, font));
vt.go();
System.out.println(vt.getMaxLines());

The output of the System.out calls is:
11
4
1

These numbers are the number of lines that are available after each go().
We start with 12 lines as defined in the setVerticalLayout() method.
We add MOVIE and there are 11 lines left. We've defined a leading of 30, which means we've already consumed (12 - 11) x 30pt = 30pt.
Then we add TEXT1 which is distributed over 7 lines, which take 7 * 30pt in width. In total we now have consumed (12 - 4) x 30pt = 240pt.
Finally we add TEXT2 which is distributed over 3 lines. Only 1 line is left. The total horizontal width of all the text is 330pt (we had only 30pt left).
Now that you know this math, you can execute the go() method in simulation mode, calculate the width that was consumed and use that info to add your text for real at the desired position.


text:
Q: Does disabling "restart and shut down" under the remote management options do nothing? I've got a Mac running Mojave and under the System Preferences > Sharing > Remote Management I've checked "Allow access for: only these users". I've added the account name of my remote user and under "options" set the following settings:

It seems logical that disabling "restart and shut down" would prevent the remote user from restarting or shutting down the machine, however in practice they can freely restart and shutdown the Mac once they've connected to the screen share.
Is this expected behaviour? Is there any way to completely prevent the screen sharing user from shutting down the machine, in case I'm logged in at the same time?


text:
Q: java : accessing static variables inside static block Analyzing some weird scenarios in following static block :
static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(i); // Compilation error "Cannot reference a field before it is defined"
}

private static int i=100;

While same code is working fine while using :
static {
  System.out.println("Inside Static Block");
  i=100; // Compilation Successful , why ?
  System.out.println(MyClass.i); // Compiles OK
}

private static int i=100;

Not sure why variable initialization do not need variable access using class name while SOP requires ?

A: This is because of the restrictions on the use of Fields during Initialization. In particular, the use of static fields inside a static initialization block before the line on which they are declared can only be on the left hand side of an expression (i.e. an assignment), unless they are fully qualified (in your case MyClass.i).
So for example: if you insert int j = i; right after i = 100; you would get the same error.
The obvious way to solve the issue is to declare static int i; before the static initialization block.

A: this is because compilers doing static code analysis, for example the live variable analysis (backward analyze). It calculates for each program point whether the variable will be read before the next write.


text:
Q: Processing intent with camera image between two Activities and passing it to marker on Google Maps API does not work I am new to Android and working on an Android app. The app has two activities: An Edit Activity and a Maps Activity.
In the Edit activity, the user can input data and take a picture from the Android phone, which works fine. The other Activity is a Maps Activity, where Markers on a map are displayed.
The markers on the map contain a bitmap, which also works fine. The part that isn´t working, is the part that the camera picture is placed on the marker instead of the bitmap graphic.
The image from the camera is displayed in an image view for the Edit Activity, which works fine.
The part that is not working is passing the camera intent to the other activity and placing the content of the intent on the marker.
Here´s the Edit Activity (a lot of code is commented out):
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.R.attr.data;
import static android.R.attr.id;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.ACTION_IMAGE_CAPTURE;

public class EditActivity extends Activity {

    public static int count = 0;
    static final int REQUEST_TAKE_PHOTO = 1;
    private static final String KEY_MARKER_ID = "id";
    private static final String KEY_MARKER_TITLE = "title";
    private static final String KEY_MARKER_DATE = "date";
    private static final String KEY_MARKER_LOC = "location";
    private static final String KEY_MARKER_LAT = "latlng";
    private static final String KEY_MARKER_NAME = "name";
    private static final String KEY_MARKER_PIC = "picture";
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editactivity);
        PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
        helper.getReadableDatabase();
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.btnCapture);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });

        final LatLng latlng = getIntent().getParcelableExtra("location");
        //final MarkerImage markerImage = getIntent().getParcelableExtra("data");
        final EditText title = (EditText) findViewById(R.id.title);
        final EditText date = (EditText) findViewById(R.id.date);
        final EditText location = (EditText) findViewById(R.id.location);
        final ImageView image = (ImageView) findViewById(R.id.imageView1);
        final EditText name = (EditText) findViewById(R.id.name);
        Button button = (Button) findViewById(R.id.save);
        final Button camerabutton = (Button) findViewById(R.id.btnCapture);
        final Intent getCameraImage = new Intent(ACTION_IMAGE_CAPTURE);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
                MarkerOptions marker = new MarkerOptions().position(latlng)
                        .icon(BitmapDescriptorFactory.fromBitmap(bmp)
                        );
                if (title.getText() != null) {
                    marker.title(title.getText().toString());
                }
                if (date.getText() != null) {
                    marker.getPosition();
                    Log.d("String Value of Marker:", String.valueOf(marker));
                }

                Intent resultIntent = new Intent();
                resultIntent.putExtra("marker", marker);
                resultIntent.putExtra("picture", getCameraImage);
                Log.d("Längen-und Breitengrad:", String.valueOf(marker));
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }

        });

        // Here, we are making a folder named picFolder to store
        // pics taken by the camera using this application.
        //final String dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/picFolder/";
        //File newdir = new File(dir);
        //newdir.mkdirs();

        //final Intent cameraIntent = new Intent(ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        /*if (getCameraImage.resolveActivity(getPackageManager()) != null) {
            // Create the File where the photo should go
            SQLiteDatabase db = helper.getWritableDatabase();

            db.beginTransaction();
            try {
                // The user might already exist in the database (i.e. the same user created multiple posts).
                //long markerId = addOrUpdateMarker(marker.user);

                ContentValues values = new ContentValues();

                values.put(KEY_MARKER_ID, id);
                values.put(KEY_MARKER_TITLE, String.valueOf(title));
                values.put(KEY_MARKER_NAME, String.valueOf(name));
                values.put(KEY_MARKER_LOC, String.valueOf(location));
                values.put(KEY_MARKER_DATE, String.valueOf(date));
                // Notice how we haven't specified the primary key. SQLite auto increments the primary key column.
                db.insertOrThrow(TABLE_MARKERS, null, values);
                db.setTransactionSuccessful();
            } catch (Exception e) {
                Log.d(TAG, "Error while trying to add post to database");
            } finally {
                db.endTransaction();
            }

            /*File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                // Error occurred while creating the File
            }
            // Continue only if the File was successfully created
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        "com.example.android.fileprovider",
                        photoFile);
                cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO);
            }
        }
        /*capture.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

                // Here, the counter will be incremented each time, and the
                // picture taken by camera will be stored as 1.jpg,2.jpg
                // and likewise.

                //count++;
                //String file = dir+count+".jpg";
                //File newfile = new File(file);
                //try {
                //    newfile.createNewFile();
               //}
               // catch (IOException e)
               // {
               // }

                //Uri outputFileUri = Uri.fromFile(newfile);

                //cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);
                startActivityForResult(cameraIntent, REQUEST_TAKE_PHOTO);
            }
        });
    }

    String mCurrentPhotoPath;

    private File createImageFile() throws IOException {
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* prefix */
              //  ".jpg",         /* suffix */
              //  storageDir      /* directory */
        //);

        // Save a file: path for use with ACTION_VIEW intents
        //mCurrentPhotoPath = image.getAbsolutePath();
        //return image;
    }

        /*@Override
        protected void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
           if (requestCode == REQUEST_TAKE_PHOTO && resultCode == RESULT_OK) {
                    Bundle extras = data.getExtras();
                    Bitmap imageBitmap = (Bitmap) extras.get("data");
                    Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);

                }
            }

        /*if (requestCode == TAKE_PHOTO_CODE && resultCode == RESULT_OK) {
            Log.d("CameraDemo", "Pic saved");

        }*/

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
            Bitmap photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);
        }
    }

}

Here´s the Maps Activity:
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;

import gmbh.webagenten.recycling.PostsDatabaseHelper;
import gmbh.webagenten.recycling.SQLiteSampleActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import static android.content.ContentValues.TAG;
import static gmbh.webagenten.recycling.R.attr.title;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private static final int EDIT_REQUEST = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        // Get singleton instance of database

        //PostsDatabaseHelper databaseHelper = PostsDatabaseHelper.getInstance((Context) this);

        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {

        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.id.imageView1);
        this.mMap = map;
        try {
            mMap.setMyLocationEnabled(true);
        } catch (SecurityException e) {
            LatLng hamburg = new LatLng(53.551085, 9.993682);
            mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg")
                .icon(BitmapDescriptorFactory.fromBitmap(bmp)));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
            //PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
            //helper.getReadableDatabase();
            //Log.d(TAG, "Database in use");
         }

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {

                Intent edit = new Intent(MapsActivity.this, EditActivity.class);
                edit.putExtra("location", latLng);
                Log.d("Längen-und Breitengrad:", String.valueOf(latLng));

                MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
            case (EDIT_REQUEST) : {
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    MarkerOptions markerOptions = data.getParcelableExtra("marker");
                    MarkerOptions markerImage = data.getParcelableExtra("data");
                    mMap.addMarker(markerOptions);
                    //mMap.addMarker(markerImage);
                }
                break;
            }
        }
    }
}

    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */

/*

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        try {
            mMap.setMyLocationEnabled(true);
        } catch (SecurityException e) {
            LatLng hamburg = new LatLng(53.551085, 9.993682);
            mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg"));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
            mMap.setOnMapClickListener(this);
        }
        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {
                Intent edit = new Intent(MapsActivity.this, EditActivity.class);
                edit.putExtra("location", latLng);
                MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
            }
        });

    }

*/

The XML files:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:background="#222"
        android:id="@+id/llMarker">

        <ImageView
            android:id="@+id/ivMarker"
            android:layout_marginTop="5dp"
            android:layout_width="40dp"
            android:layout_height="40dp" />
        <item>
            <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_width="wrap_content"></ImageView>
        </item>

    </LinearLayout>
</selector>

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Title"
        android:inputType="text" />

    <EditText
        android:id="@+id/date"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Date"
        android:inputType="date" />

    <EditText
        android:id="@+id/location"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Location"
        android:inputType="text" />

    <EditText
        android:id="@+id/name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Name"
        android:inputType="text" />

    <Button
        android:id="@+id/btnCapture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Camera" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Save"/>

    <ImageView android:id="@+id/imageView1" android:layout_height="wrap_content" android:layout_width="wrap_content"></ImageView>

As I am new to Android, I am stuck with this problem for a longer time now. Any help or hints would be appreciated, thanks!

A: I understand your problem . What I got the mistake is , you are not able to get the bitmap to the next activity , you have set the data to the imageview in edit activity and when you are opening the map activity, that data is lost ,
what you have to do is:
1. pass the bitmap to the map activity from edit activity
2. get the bitmap to the map activity and then show the bitmap to the map.
import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import static android.R.attr.data;
import static android.R.attr.id;
import static android.content.ContentValues.TAG;
import static android.provider.MediaStore.ACTION_IMAGE_CAPTURE;

public class EditActivity extends Activity {

    public static int count = 0;
    static final int REQUEST_TAKE_PHOTO = 1;
    private static final String KEY_MARKER_ID = "id";
    private static final String KEY_MARKER_TITLE = "title";
    private static final String KEY_MARKER_DATE = "date";
    private static final String KEY_MARKER_LOC = "location";
    private static final String KEY_MARKER_LAT = "latlng";
    private static final String KEY_MARKER_NAME = "name";
    private static final String KEY_MARKER_PIC = "picture";
    private static final int CAMERA_REQUEST = 1888;
    private ImageView imageView;
    Bitmap photo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.editactivity);
        PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
        helper.getReadableDatabase();
        this.imageView = (ImageView)this.findViewById(R.id.imageView1);
        Button photoButton = (Button) this.findViewById(R.id.btnCapture);
        photoButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(cameraIntent, CAMERA_REQUEST);
            }
        });

        final LatLng latlng = getIntent().getParcelableExtra("location");
        //final MarkerImage markerImage = getIntent().getParcelableExtra("data");
        final EditText title = (EditText) findViewById(R.id.title);
        final EditText date = (EditText) findViewById(R.id.date);
        final EditText location = (EditText) findViewById(R.id.location);
        final ImageView image = (ImageView) findViewById(R.id.imageView1);
        final EditText name = (EditText) findViewById(R.id.name);
        Button button = (Button) findViewById(R.id.save);
        final Button camerabutton = (Button) findViewById(R.id.btnCapture);
        final Intent getCameraImage = new Intent(ACTION_IMAGE_CAPTURE);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View view) {
                Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
                MarkerOptions marker = new MarkerOptions().position(latlng)
                        .icon(BitmapDescriptorFactory.fromBitmap(bmp)
                        );
                if (title.getText() != null) {
                    marker.title(title.getText().toString());
                }
                if (date.getText() != null) {
                    marker.getPosition();
                    Log.d("String Value of Marker:", String.valueOf(marker));
                }

                Intent resultIntent = new Intent();
                resultIntent.putExtra("marker", marker);
                resultIntent.putExtra("picture", getCameraImage);
                intent.putExtra("BitmapImage", photo);          // passing the bitmap to the next activity . and retrieve it to the next activity
                Log.d("Längen-und Breitengrad:", String.valueOf(marker));
                setResult(Activity.RESULT_OK, resultIntent);
                finish();
            }

        });

  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK) {
           `photo = (Bitmap) data.getExtras().get("data");
            imageView.setImageBitmap(photo);
        }
    }

}

Here is the map activity
import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.View;

import gmbh.webagenten.recycling.PostsDatabaseHelper;
import gmbh.webagenten.recycling.SQLiteSampleActivity;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import static android.content.ContentValues.TAG;
import static gmbh.webagenten.recycling.R.attr.title;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private GoogleMap mMap;
    private static final int EDIT_REQUEST = 1;
    Bitmap bmp;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setTheme(R.style.AppTheme);
        super.onCreate(savedInstanceState);
        // Get singleton instance of database

        Intent intent = getIntent();
        bmp = (Bitmap) intent.getParcelableExtra("BitmapImage");      // getting the bitmap data from the edit activity.

        //PostsDatabaseHelper databaseHelper = PostsDatabaseHelper.getInstance((Context) this);

        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {

        //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.id.imageView1);
        this.mMap = map;
        try {
            mMap.setMyLocationEnabled(true);
        } catch (SecurityException e) {
            LatLng hamburg = new LatLng(53.551085, 9.993682);
            mMap.addMarker(new MarkerOptions().position(hamburg).title("Marker in Hamburg")
                .icon(BitmapDescriptorFactory.fromBitmap(bmp)));
            mMap.moveCamera(CameraUpdateFactory.newLatLng(hamburg));
            //PostsDatabaseHelper helper = PostsDatabaseHelper.getInstance(this);
            //helper.getReadableDatabase();
            //Log.d(TAG, "Database in use");
         }

        mMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick(final LatLng latLng) {

                Intent edit = new Intent(MapsActivity.this, EditActivity.class);
                edit.putExtra("location", latLng);
                Log.d("Längen-und Breitengrad:", String.valueOf(latLng));

                MapsActivity.this.startActivityForResult(edit, EDIT_REQUEST);
            }
        });
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch(requestCode) {
            case (EDIT_REQUEST) : {
                if (resultCode == Activity.RESULT_OK) {
                    Bundle bundle = data.getExtras();
                    MarkerOptions markerOptions = data.getParcelableExtra("marker");
                    MarkerOptions markerImage = data.getParcelableExtra("data");
                    mMap.addMarker(markerOptions);
                    //mMap.addMarker(markerImage);
                }
                break;
            }
        }
    }
}

Here is the updated code, Hope it help .Kindly check it and let me know.


text:
Q: Creating a settings text file for python tkinter form widgets I am creating a form for session variables in python and (currently) store the inputs in separate text files.  How could I use a single file to hold all session variables in lists (there will be more than 2 in the final form)?  What would I need to change in my code to make this more efficient?  Any help is greatly appreciated.
import tkinter
from tkinter import *
from tkinter import ttk

regionList = open('regions.txt','r')
optionList = open('options.txt','r')
class MainWindow(Frame):
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master = master
        self.init_window()
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create Window Layout"""
        Boxfont = ('Lucida Grande', 12)

        self.label1 = Label(self, font=Boxfont,
text="Regions").grid(row=2,column=0)
        self.regcombo = ttk.Combobox(self, font = Boxfont, width = 20, textvariable = varRegions)
        self.regcombo.bind("<Return>", self.regcombo_onEnter)
        self.regcombo.bind('<<ComboboxSelected>>',self.regcombo_onEnter)
        self.regcombo['values'] = regionList.readlines()
        self.regcombo.grid(row=2, column=1,sticky = W)

        self.label2 = Label(self, font=Boxfont, text="Options").grid(row=4,column=0)
        self.optcombo = ttk.Combobox(self, font = Boxfont, width = 20, textvariable = varOptions)
        self.optcombo.bind("<Return>", self.optcombo_onEnter)
        self.optcombo.bind('<<ComboboxSelected>>',self.optcombo_onEnter)
        self.optcombo['values'] = optionList.readlines()
        self.optcombo.grid(row=4, column=1,sticky = W)

    def init_window(self):
        self.master.title("User Settings")
        self.pack(fill=BOTH, expand=1)

    def regcombo_onEnter(self,event):
        varRegions.set(varRegions.get().lower())
        mytext = varRegions.get()
        vals = self.regcombo.cget('values')
        self.regcombo.select_range(0,END)
        print(mytext)
        if not vals:
            self.regcombo.configure(values = (mytext.strip,))
        elif mytext not in vals:
            with open('regions.txt','a') as f:
                f.write('\n'+ mytext)
                self.regcombo.configure(values = vals + (mytext,))
                f.close
        return 'break'

    def optcombo_onEnter(self,event):
        varOptions.set(varOptions.get().lower())
        mytext = varOptions.get()
        vals = self.optcombo.cget('values')
        self.optcombo.select_range(0,END)
        print(mytext)
        if not vals:
            self.optcombo.configure(values = (mytext.strip,))
        elif mytext not in vals:
            with open('options.txt','a') as f:
                f.write('\n'+ mytext)
                self.optcombo.configure(values = vals + (mytext,))
                f.close
        return 'break'

root = tkinter.Tk()
root.geometry("600x600")
varRegions = tkinter.StringVar(root, value='')
varOptions = tkinter.StringVar(root, value='')
app = MainWindow(root)
root.mainloop()


text:
Q: Getting pid trying to stop a program with C Probably the core of this question has been asked a lot on this site.
I'mm working with pocketsphinx and I'm trying to play music each time I request it.
When I say "MUSIC" the program executes the music, my idea is that when I say "STOP" music should stop. I'm trying to get the PID the following way. I got this idea from this question
I though using popen I will get the PID, but isn't that way when it get to  pid_t pid = strtoul(line, NULL, 10); it's returning me 0.
How I can get this PID and continue with the program running at the same time?
I'm using the same template that you will find on the pocketsphinx want to see it with modifications here: http://pastebin.com/Duu2nbCA
if(strcmp(word, "MUSIC") == 0)
{
    FILE *fpipe;
  char *command = (char *)"aplay BobMarley.wav";
  char line[256];

  if ( !(fpipe = (FILE*)popen(command,"r")) )
  {  // If fpipe is NULL
    perror("Problems with pipe");
    exit(1);
  }
  fgets( line, sizeof line, fpipe);
  pid_t pid = strtoul(line, NULL, 10);
  printf("The id is %d\n", pid);

}

A: You can refer the below code to find the PID of a process. Execute with "root" permission

The argument to the executable will the name of the process for which the PID has to obtained

#define TMP_FILE  "/tmp/pid"

int main(int argc, char** argv)
{
    FILE *fpipe;
    int pid = 0;
    char command[50] = "pidof -s ";

    if (argc != 2) {
        printf("Invalid input\n");
        return -1;
    }

    strcat(command, argv[1]);
    strcat(command, " > "TMP_FILE);
    system(command);

    fpipe = fopen(TMP_FILE, "r");
    fscanf(fpipe, "%d", &pid);
    printf("The pid is %d\n", pid);
    fclose(fpipe);

    return 0;
}

Based on the sizeof the process name vary the length of the command.

Implementation 2

int main( int argc, char *argv[] )
{

    FILE *fp;
    char path[10];

    fp = popen("/sbin/pidof -s YOUR_APP", "r");
    if (fp == NULL) {
        printf("Failed to run command\n" );
        exit(1);
    }

    /* Read the output a line at a time - output it. */
    while (fgets(path, sizeof(path), fp) != NULL) {
        printf("%s", path);
    }

    pclose(fp);

    return 0;
}

Change YOUR_APP with your application name.
Tested with other commands.


text:
Q: Replace NA in one data by the value of another data in R? I have two data set, data1 has no NA but data2 has NA. I would like to replace the NA in data2 by the corresponding value in data1.
dput(data1)
structure(list(X1 = c(4, 7, 8, 4, 5), X2 = c(2, 1, 1, 2, 1),
    X3 = c(1, 2, 2, 1, 2)), class = "data.frame", row.names = c(NA,
-5L))
> data1
  X1 X2 X3
1  4  2  1
2  7  1  2
3  8  1  2
4  4  2  1
5  5  1  2

> dput(data2)
structure(list(X1 = c(10, NA, 9, 8, NA), X2 = c(3, 2, 2, NA,
1), X3 = c(4, 3, NA, 5, 4)), class = "data.frame", row.names = c(NA,
-5L))

> data2
  X1 X2 X3
1 10  3  4
2 NA  2  3
3  9  2 NA
4  8 NA  5
5 NA  1  4

Expected outcome is
> data2
  X1 X2 X3
1 10  3  4
2  7  2  3
3  9  2  2
4  8  2  5
5  5  1  4

Any help is appreciated.

A: We can use coalesce
library(dplyr)
data2 %>%
    mutate(across(everything(), ~ coalesce(., data1[[cur_column()]])))

-output
#  X1 X2 X3
#1 10  3  4
#2  7  2  3
#3  9  2  2
#4  8  2  5
#5  5  1  4

Or in base R
i1 <- is.na(data2)
data2[i1] <- data1[i1]

A: Does this work:
library(dplyr)
coalesce(data2, data1)
  X1 X2 X3
1 10  3  4
2  7  2  3
3  9  2  2
4  8  2  5
5  5  1  4

A: You could also use
library(tidyverse)
map2_dfc(data2, data1, coalesce)

# A tibble: 5 x 3
     X1    X2    X3
  <dbl> <dbl> <dbl>
1    10     3     4
2     7     2     3
3     9     2     2
4     8     2     5
5     5     1     4


text:
Q: Truncating integer using string manipulation? I have a class with a data member that needs to be rounded up to a 2 digit integer, irrespective of the number of the input digits.
For example:
roundUpto2digit(12356463) == 12
roundUpto2digit(12547984) == 13 // The 5 rounds the 12 up to 13.

Currently my code looks like:
int roundUpto2digit(int cents){
    // convert cents to string
    string truncatedValue = to_string(cents);
    // take first two elements corresponding to the Most Sign. Bits
    // convert char to int, by -'0', multiply the first by 10 and sum the second
    int totalsum =  int(truncatedValue[0]-'0')*10 + int(truncatedValue[1]-'0');
    // if the third element greater the five, increment the sum by one
    if (truncatedValue[2]>=5) totalsum++;
    return totalsum;
}

Any advice to make it less ugly will be deeply appreciated.

A: You can use fixed point integer arithmetics which are probably faster and look better. You want the number in a scale of 10^2 and you have it in an arbitrary scale power of 10 as well, so to round you just need to apply the formula:
ROUNDED_VAL = (INITIAL_VAL + (10^(ORIG_SCALE - 2) / 2)) / 10^(ORIG_SCALE - 2)

So your code could look something like this:
int roundUpto2digit(int cents){
    int scale = 10;
    while(cents / scale > 0) {
        // Find out original scale. This can be done maybe faster with a divide and conquer algorithm
        scale *= 10;
    }
    int applied_scale = scale / 100;
    if (applied_scale == 0) {
        // In case there is only one digit, scale it up to two
        return 10 * cents;
    }
    return ((cents + (applied_scale / 2)) / applied_scale);
}

EDIT: The 10 * cents line I wrote was an arbitrary extrapolation of the problem I made based on my interpretation. If that is not the desired behavior, it can be of course changed.

A: #include <math.h>

int roundUpto2digit(int value)
{
    value /= pow(10,(int)log10(value)-2);
    /*
    (int)log10(value) returns base ten logarithm (number of digits of your number)
    pow(10, N) returns number 1 followed by N zeros
    example:
    pow(10,(int)log10(123)-2) returns 1
    pow(10,(int)log10(1234)-2) returns 10
    pow(10,(int)log10(1234567)-2) returns 10000
    thus
    value / pow(10,(int)log10(value)-2) returns first 3 digits
    */
    return value%10>=5? (value+10)/10 : value/10;
    /*
    if(value%10>=5)// the last digit is >= 5
    {
    // increase previous number
    value = value + 10;
    }
    // return number without the last digit
    return value/10;
    */
}


text:
Q: Web service concurrent calls processing I've faced with the next issue related to web service request processing:
Preamble
I have

*

*Web api service hosted on IIS 7.0 on local machine

*Test harness console application on the same machine

and i'm trying to simulate web service load by hitting one with requests generated via test harness app.
Test harness core code:
    static int HitsCount = 40;

    static async void PerformHitting()
    {
        {
            await Task.WhenAll(ParallelEnumerable.Range(0, HitsCount)
                                                 .Select(_ => HitAsync())
                                                 .WithDegreeOfParallelism(HitsCount));
        }
    }

    static async Task HitAsync()
    {
        // some logging skipped here
        ...
        await new HttpClient().GetAsync(TargetUrl, HttpCompletionOption.ResponseHeadersRead);
    }

Expectation
Logging shows that all HitAsync() calls are made simultaneously: each hit via HttpClients had started in
[0s; 0.1s] time frame (timings are roughly rounded here and below). Hence, I'm expecting to catch all these requests in approximately the same time frame on web service side.
Reality
But logging on the service side shows that requests grouped in bunches 8-12 request each and service catches these bunches with ~1 second interval. I mean:
[0s, 0.3s] <- requests #0-#10
[1.2s, 1.6s] <- requests #10-#20
...
[4.1s, 4.5s] <- request #30-#40

And i'm getting really long execution time for any significant HitCount values.
Question
I suspect some kind of built-in service throttling mechanism or framework built-in concurrent connections limitation. Only I found related to such guesstimate is that, but i didn't get any success trying soulutions from there.
Any ideas what is the issue?
Thanks.

A: By default, HTTP requests on ASP.NET are limited to 12 times the number of cores. I recommend setting ServicePointManager.DefaultConnectionLimit to int.MaxValue.

A: Well, the root of the problems lies in the IIS + Windows 7 concurrent requests handling limit (some info about such limits here. Moving service out to the machine with Windows Server kicked out the problem.


text:
Q: Passing object parameters to functions c++ I am creating a program that simulates phone calls and text messages. I am trying to pass the info from the class object 'phone' to my dialNum and txtNum functions to cout when the user assigns the two phone numbers as originating and receiving phones but I'm having trouble figuring out what to do.
This is my code so far:
#ifndef PHONENUMBER_H
#define PHONENUMBER_H

#include <iostream>
#include <iomanip>

using namespace std;

class PhoneNumber {
public:

   PhoneNumber(const PhoneNumber &);
   friend ostream &operator<<( ostream&, const PhoneNumber & );
   friend istream &operator>>( istream&, PhoneNumber & );
   void dialNum();
   void txtNum();
   void displaySummary ();
   operator int() const {return phonenumberval;}
 //  Constructor(int, int);

private:
   char areaCode[ 5 ]; // 3-digit area code and null
   char exchange[ 5 ]; // 3-digit exchange and null
   char line[ 5 ];  // 4-digit line and null
   int phonenumberval;
   static int ntext;
   static int nlive;

}; // end class PhoneNumber

#endif

PhoneNumber::PhoneNumber (const PhoneNumber &phone1){

    phonenumberval = phone1. PhoneNumber;
}

ostream &operator<<( ostream &output, const PhoneNumber &num )
{
   output << "(" << num.areaCode << ")" << num. exchange << "-" << num.line;

   return output; // enables cout << a << b << c;
} // end function operator<<

istream &operator>>( istream &input, PhoneNumber &num )
{
   input.ignore(0);
   input >> setw( 4 ) >> num.areaCode;
   input.ignore( 1 ); // skip ( and space
   input >> setw( 4 ) >> num.exchange;
   input.ignore();
   input >> setw( 5 ) >> num.line;  // input line

   return input;
}

void PhoneNumber::dialNum(){
    int num1;
    int num2;
    cout << "Enter originating phone: " << endl;
    cin >> num1;
    cout << "Enter recieving phone: " << endl;
    cin >> num2;
    cout << " Calling number " << num2 <<"...call made."<< endl;
    cout << "The const int phonenumberval = " << phonenumberval;
}

void PhoneNumber::txtNum(){
    string txt;
    int textphone1;
    int textphone2;

    cout << "Enter orginating phone: " << endl;
    cin >> textphone1;
    cout << "Enter receiving phone: " << endl;
    cin >> textphone2;
    cout << "Enter text message to send." << endl;
    cin >> string txt;
    cout << "Sending message to " << textphone2 << " .....message sent." <<     endl;
}

void PhoneNumber::displaySummary(int a, int b){
    nlive = int b;
    ntext = int a;

    cout << "You made " << nlive << " calls and " << ntext << " texts." << endl;
}

}
int main()
{
   PhoneNumber phone, phone2; // create object phone
   char answer;
   int callCounter = 0;
   int textCounter = 0;

   cout << "Enter phone number in the form (NNN) NNN-NNNN:\n";

   cin >> phone;

   cout << "Enter phone number in the form (NNN) NNN-NNNN:\n";

   cin >> phone2;

   cout << "The phone number entered was: ";

   cout << phone << endl;
   cout << phone2 << endl;

 do {
 cout << "Enter c to make a a call, t to text, s for summary information, or x to exit. " << endl;
    cin >> answer;

        if (answer == 'c'){
            phone.dialNum();
            ++callCounter;

        }

        else if (answer == 't'){

            cout << "who cares" << endl;
            ++textCounter;
        }

        else if (answer == 's'){
            phone.displaySummary(callCounter, textCounter);
        }

 } while (answer != 'x');

    cout << "You made " << callCounter << " calls and " << textCounter << " texts." << endl;

    return 0;
 } // end main

When I tried to pass the object these are the errors I got:
In copy constructor 'PhoneNumber::PhoneNumber(const PhoneNumber&)':
32:30: error: invalid use of 'PhoneNumber::PhoneNumber'
 In function 'int main()':
67:16: error: no matching function for call to 'PhoneNumber::PhoneNumber()'
67:16: note: candidate is:
30:1: note: PhoneNumber::PhoneNumber(const PhoneNumber&)
30:1: note:   candidate expects 1 argument, 0 provided
67:23: error: no matching function for call to 'PhoneNumber::PhoneNumber()'
67:23: note: candidate is:
30:1: note: PhoneNumber::PhoneNumber(const PhoneNumber&)
30:1: note:   candidate expects 1 argument, 0 provided

A: Issue 1: user defined cast operator
You define a cast operator with this code:
operator int() const {return phonenumberval;}

… which I guess you try to call with this code:
phonenumberval = phone1. PhoneNumber;

… but this is not the way it works. To call the cast operator, you have to do the following:
phonenumberval = (int)phone1;

Issue 2: user defined constructor
In C++, as soon as you provide a user-defined constructor (which you do there by declaring the copy constructor PhoneNumber(const PhoneNumber &);), you lose the default constructors provided by the language. In your case, you lose the default constructor PhoneNumber();, which means you can't create a new PhoneNumber without giving a parameter to the constructor.
Just add a new constructor the PhoneNumber class, and it should be ok.
class PhoneNumber {
public:
    PhoneNumber(); // This is the default constructor
    PhoneNumber(const PhoneNumber &); // This is your copy constructor

// ...
};

// ...

int main()
{
    PhoneNumber phone, phone2; // This will call the default constructor, which has to be declared first
    // ...
}


text:
Q: What statistical test would be the most useful for a 3 x 2 table when more than 20% of cells are less than 5? What statistical test would be the most useful for a 3 x 2 table when more than 20% of cells are less than 5?
Chi square testing requires a min of 80% of cell counts to be over 5.
For example, if I was wanting to see if room colour effected mood and these were my results.
.............Happy........Sad.........Hopeful
Black............2.............4..................25
Blue..............16...........2..................3

A: I assume you want to test the null hypothesis that the row value is statistically independent of the column value.  This can be done using Fisher's exact test, which conditions on the marginal totals of the categories.  (Hat-tip to Glen_b for pointing this out.)  This can be implemented in R as follows:
#Set up the contingency table for the data
DATA <- matrix(c(2, 4, 25, 16, 2, 3), nrow = 2, ncol = 3, byrow = TRUE);
rownames(DATA) <- c('Black', 'Blue');
colnames(DATA) <- c('Happy', 'Sad', 'Hopeful');

#Perform Fisher's exact test
TEST <- fisher.test(x = DATA);

#See the results of the test
TEST;

        Fisher's Exact Test for Count Data

data:  DATA
p-value = 1.344e-07
alternative hypothesis: two.sided

Unsurprisingly, there is extremely strong evidence to reject the null hypothesis of independence (which was already pretty obvious from looking at the numbers in the table).


text:
Q: What does the parenthesis mean in a command description like "mklost+found(8)" When googling for linux commands, I often see a number in parenthesis like this:

mklost+found(8)

What does it mean?
Is it a version number of the program, reference to some standard, or what?

A: The number refers the section in the system's reference manual in which the corresponding page resides, e.g. for command date, (date(1), in your case), 1 refers to the "user commands" section, which can be accessed by executing the command man 1 date.
See also man man. It lists all the standard sections:

The standard sections of the manual include:
  1      User Commands

  2      System Calls

  3      C Library Functions

  4      Devices and Special Files

  5      File Formats and Conventions

  6      Games et. Al.

  7      Miscellanea

  8      System Administration tools and Deamons

Distributions customize the manual section to their specifics, which often include additional sections.


text:
Q: How to drag and drop edit text, radio buttons, view groups(along with child) and layouts in android programmatically? I have implemented drag and drop on Imageviews, Buttons and Textviews by OnLongClicklistener() and Ondraglistener() but the problem is I am unable to drag and drop edit text, radio buttons, linear/relative layouts and view groups(along with child).
Any method to drag these views in the same way?


text:
Q: Let $\mathbb{Z} \subset \mathbb{R}$ with the discrete topology prove that $X$ is connected if and only if $f: X \rightarrow \mathbb{Z}$ is constant
Let $\mathbb{Z} \subset \mathbb{R}$ with the discrete  topology prove that $X$ is connected if and only if for every continuous function  $f: X \rightarrow \mathbb{Z}$ is constant function.

Attempt
Suppose that $X$ is connected and consider an arbitrary continuous function $f: X \rightarrow \mathbb{Z}$
since $X$ is connected  then $f(X)\subset \mathbb{Z}$ is connected, and $f(X)$ is an open set since we be considering the discrete topology, that is $f(X) \subset \mathbb{Z}$ is open in the subespace topology
if for any $x\in X$ $f(x)=\mathbb{Z} \cap \mathbb{R}$for all $x\in X$.This is $f$ is a constant function.
Conversely assume that for every continuous function $f:X \rightarrow \mathbb{Z}$ is constant we should prove that $X$ is connected.
Assume that $X$ is not conected, then Exists $U,V\subset X$ such that $U,V \neq \emptyset$ and $U \cup V=X$,but $U \cap V = \emptyset$ then consider the function
$h_1:U \rightarrow \mathbb{Z}$ given by $h_1(x)=1$ which is continuous function.
And consider $h_2:V \rightarrow \mathbb{Z}$ given by $h_2(x)=0$ which is continuous function.
Notice that $U\cap V= \emptyset$ implies that $h_1$ and $h_2$ are equal in their points of intersections.
Consider $h:U \cup V=X \rightarrow \mathbb{Z}$ given by
$$h(x)=\begin{cases}
h_1(x) if\, x\in U&\\
h_2(x)if\, x\in V
\end{cases}$$
Which is non constant continuous function then not every continuous function $f:X \rightarrow \mathbb{Z}$ is constant which is a contradiction, then $X$ is connected.
Is my proof right?

A: For the first part of the proof the fact that $f[X]$ is open in $\Bbb Z$ is irrelevant: all that matters is that the only non-empty, connected subsets of $\Bbb Z$ are the singletons.
The other direction is fine, though it can be done more simply without the pasting lemma. Just prove the contrapositive. If $X$ is not connected, there is a continuous function $f$ mapping $X$ onto the discrete two-point space $\{0,1\}$. Clearly this $f$ can be viewed as a continuous function from $X$ to $\Bbb Z$, and it is not constant.


text:
Q: how do i fix "cannot read property match of undefned" in this code i'm trying to integrate nativescript-imagepicker plugin with my Nativescript App, but i get error **cannot read **property match of undefined****
below is what i have already tried, thanks.
function onSelectSingleTap(args) {
    var context = imagepickerModule.create({
        mode: "single"
    });
    if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
        permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
        .then(function() {
            console.log("Permissions granted!");
            startSelection(context);
        })
        .catch(function() {
            console.log("Uh oh, no permissions - plan B time!");
        });
    } else {
        startSelection(context);
    }
}

function sendImages(selected) {
    let fileUri = selected.fileUri;
    imageName = extractImageName(fileUri);

    var request = {
        url: "http://vvvvvv.com/skog/upload.php",
        method: "POST",
        headers: {
            "Content-Type": "application/octet-stream",
            "File-Name": imageName
        },
        description: "{ 'uploading': " + imageName + " }"
    };
    //get the image source and upload from there
    selected.getImage().then(imageSource => {
        let temp = fs.knownFolders.temp();
        let uniqueName = '_' + Math.random().toString(36).substr(2, 9);
        let filePath = fs.path.join(temp.path, uniqueName + ".jpg");
        let saved = imageSource.saveToFile(filePath, enums.ImageFormat.jpeg);
        console.log(`item saved:${saved}`);
        var task = session.uploadFile(filePath, request);

        task.on("progress", logEvent);
        task.on("error", logEvent);
        task.on("complete", x => cleanFile(filePath));
    });
    //return task;
}
function logEvent(e) {
        console.log("----------------");
        console.log('Status: ' + e.eventName);
        console.log('Error: ' + e.error);
        // console.log(e.object);
        if (e.totalBytes !== undefined) {
            console.log('current bytes transfered: ' + e.currentBytes);
            console.log('Total bytes to transfer: ' + e.totalBytes);
        }
    }
function cleanFile(file){
    fs.remove(file);
}
function startSelection(context) {
    context
        .authorize()
        .then(function() {
            imageItems.length = 0;
            return context.present();
        })
        .then(function(selection) {
            selection.forEach(function(selected) {
                sendImages(selected);
                //selected.uploadTask = sendImages(selected);
                selected.imageName = imageName;

                console.log("----------------");
                console.log("uri: " + selected.uri);
                console.log("fileUri: " + selected.fileUri);
                console.log('Image name:' + imageName);

                imageItems.push(selected);
            });
            //list.items = selection;
        }).catch(function (e) {
      console.log(e);
      alert(e.message);
        });
}
function extractImageName(fileUri) {
  var pattern = /[^/]*$/;
  var imageName = fileUri.match(pattern);

  return imageName[0];
}

I don't think the fault is from the php which is why i'm not adding the code to the question, but if you think otherwise, please let me know
please help

A: selection is an array of ImageAsset, so selected.getImage() is obviously undefined. It has only getImageAsync(...) but that returns native image data.
To create ImageSource from asset, you should use fromAsset method.
fileUri is also undefined, there is no property as such. I'm not sure where you are picking all these from. I suggest you to refer the documentation for all valid properties and methods.

A: this will do it
function onSelectSingleTap(args) {
      var context = imagepickerModule.create({
          mode: "single"
      });

      if (platformModule.device.os === "Android" && platformModule.device.sdkVersion >= 23) {
          permissions.requestPermission(android.Manifest.permission.READ_EXTERNAL_STORAGE, "I need these permissions to read from storage")
              .then(function () {
                  console.log("Permissions granted!");
                  startSelection(context);
              })
              .catch(function () {
                  console.log("Uh oh, no permissions - plan B time!");
              });
      } else {
          startSelection(context);
      }
    }

    function startSelection(context) {

      context
          .authorize()
          .then(function () {

              return context.present();
          })
          .then(function (selection) {
            selection.forEach(function(selected) {
              //alert(selected.android.toString());
              var file =  selected.android.toString();
              var url = "https://adekunletestprojects.000webhostapp.com/skog/upload.php";
              var name = file.substr(file.lastIndexOf("/") + 1);
              //alert(name);
              var bghttp = require("nativescript-background-http");
              var session = bghttp.session("image-upload");
              var request = {
              url: url,
              method: "POST",
              headers: {
                  "Content-Type": "application/octet-stream",
                  "File-Name": name
              },
            description: "Uploading " + name
        };

            var task = session.uploadFile(file, request);
            task.on("progress", progressHandler);
            return task;
            function progressHandler(e) {
              var toast = Toast.makeText("uploaded " + e.currentBytes + " / " + e.totalBytes);
              toast.show();
          }
            });
          }).catch(function (e) {
              console.log(e.eventName);
              alert(e.message);
          });
    }


text:
Q: pythagorean triplet prints all numbers I don't understand why but pythagorean_triplet code print all numbers, not just the 3 of it
import math

def pythagorean_triplet(n):
    if 1 <= n <= 90000:
        for b in range(n):
            for a in range(1, b):
                c = math.sqrt(a * a + b * b)
                if c % 1 == 0:
                    print(a, b, int(c))

x = int(input())

pythagorean_triplet(x)

A: I'm not sure of your question, but if the output should only be the last triplet, why not start backwards and end the loop you're in whenever you've found the number? The following code gave me: 12 16 20
import math

def pythagorean_triplet(n):
    if 1 <= n <= 90000:
        for b in range(n - 1, 0, -1):
            for a in range(b - 1, 0, -1):
                c = math.sqrt(a * a + b * b)
                if c % 1 == 0:
                    print(a, b, int(c))
                    return

x = int(input())

pythagorean_triplet(x)

Since you didn't return or break the loops, it will keep on iterating over the numbers.
EDIT 1:
If you only want the first triple, there is no point of using a for-loop. I suggest you test with an if-statement, whether the number is greater then a certain minimum. To be honest, I haven't really researched pythogerean triplets, but it's apparently - according to the code - 5. So the best way to solve this is:
def pythagorean_triplet(n):
    if n >= 5:
        print(3, 4, 5)

x = int(input())

pythagorean_triplet(x)

And here is what you requested, but I should NOT do it this way, because it's unnecessary complicated.
import math

def pythagorean_triplet(n):
    if 1 <= n <= 90000:
        for b in range(n):
            for a in range(1, b):
                c = math.sqrt(a * a + b * b)
                if c % 1 == 0:
                    print(a, b, int(c))
                    return

x = int(input())

pythagorean_triplet(x)

A: so, I think I didn't understand the question that was given to me. the result was only 3 numbers. so I was confused!  and after I asked about it I found out that the Sum of 3 numbers should be equal to the input :
    import math

y = []
x = int(input())
if 1 <= x <= 90000:
    for b in range(x):
        for a in range(1, b):
            c = math.sqrt(a * a + b * b)
            u = a + b + c
            if c > x:
                break
            elif c % 1 == 0:
                if u == x:
                    k = (a, b, int(c))
                    y.append(k)

if len(y) != 0:
    for a_tuple in y:  # iterates through each tuple
        for item in a_tuple:  # iterates through each tuple items
            print(item, end=" ")
else:
    print("Impossible")


text: Q: Do virtual particles have a density? I am currently working with some theory that predicts that virtual particles would have a higher density (higher chance of appearing) in strong gravity field and would move towards gravity force. I cannot find any info about it. Is this even possible? Do virtual particles appearing chance depends on something or its more like some constant per space cube meter?


text:
Q: insert value from specific position in .dat file into mysql I have a .dat file that contains a bunch of text information. What I need to do via php is be able to upload the .dat file to the server which I know how to do already. However once it is uploaded to the server I am not sure how in PHP to open the file and get what ever value is at the 180th position in the file.
The files should all be one row although even if its not I still just need the value from the first row 180th position and take that value and insert it into a mysql database table.
I am looking for any tutorial or documentation on how to do this
Thanks all


text:
Q: What does it basically mean with scope annotations in two components (one depends on the other) In my Android project, I have two project modules, an main module and a core module.
In main module, I have a dagger component, MainComponent:
 // it has dependency on CoreComponent
@Component(modules = [MyModule::class], dependencies = [CoreComponent::class])
@FeatureScope
interface MainComponent {
    fun inject(mainActivity: MainActivity)
}

As you can see above, MainComponent has a dependency on CoreComponent. It also has a custom scope annotation @FeatureScope.
In core module I have another dagger component called CoreComponent:
@Component(modules = [CoreModule::class])
@Singleton
interface CoreComponent {
    fun getExpensiveObject(): ExpensiveObject
}

@Module
class CoreModule {
    @Provides
    @Singleton
    fun provideExpObj(): ExpensiveObject = ExpensiveObject()
}

The CoreComponent is annotated by Dagger defined @Singleton scope.
I build the Main component in onCreate() of Application class:
class MyApplication : Application() {
    override fun onCreate() {
        super.onCreate()
          //build main component along with core component
         mainComponent = DaggerMainComponent
                .builder()
                .myModule(MyModule())
                .coreComponent(DaggerCoreComponent.builder().build())
                .build()
     }
}

CoreComponent & its providers are annotated by @Singleton, while MainComponent & its providers are annotated by custom annotation @FeatureScope.
Question one: From lifetime perspective, does the code mean the lifetime of objects in MainComponent is shorter than that in CoreComponent due to the scope annotations (@Singleton in CoreComponent and @FeatureScope in MainComponent)?
Question two: Since the components are built in Application class onCreate() which is the entry point of app at runtime, am I right that even though components in two project modules are annotated by different scope annotation, their objects basically have the same lifetime as the whole app's  at runtime?
(I ask those questions because my understanding is that the Dagger defined @Singleton scope has the longest lifetime, but I get confused by that with my project)

A: Yes, the fact that CoreComponent is annotated with @Singleton and the component instance is created in the Application means that there will be a single ExpensiveObject created in the lifetime of the application.
Concerning the custom annotation (@FeatureScope)

The component implementation ensures that there is only one provision of each scoped binding per instance of the component.
  ref

But since, the MainComponent is created only once per application, this custom annotation is effectively the same as the Singleton annotation.
If you want a feature-scoped object then you should remove it from the MainComponent and have this annotation only on a sub-component. Read the dagger tutorial, and in particular the step 13.

Annotating both WithdrawalLimiter and UserCommandsRouter with
  @PerSession indicates to Dagger that a single WithdrawalLimiter should
  be created for every instance of UserCommandsRouter.
@PerSession
final class WithdrawalLimiter { ... }

@PerSession
@Subcomponent(...)
interface UserCommandsRouter { ... }


text:
Q: Azure Stack and Ansible There is no azure stack ansible modules in the latest ansible 2.7.
There are two things i want to know.
1. Is it feasible to customize azure ansible modules to work for azure stack?
2. If yes for the first question,what are the features which are only available in azure stack which cannot be invoked using azure modules?

A: You can use old azure ansible module with Azure Stack because Azure Stack doesn't support a new API version. The latest ansible uses a new API version. So you must use old ansible to use the old API version. I confirmed that ansible 2.4 work with ASDK 1901.

A: The Ansible playbooks simply call Azure Resource Manager API, so in most cases they will work the same as in public Azure. With that said, Azure Stack does not support all of the same APIs and versions that public Azure does so you will have to match your version.
https://learn.microsoft.com/en-us/azure/ansible/ansible-matrix
https://learn.microsoft.com/en-us/azure-stack/user/azure-stack-considerations?view


text:
Q: fastapi post method call with and without trailing slashes I was trying to write a fastapi post method as:
@app.post('/method/final_path/', tags=['method/final_path'])

When i do a postman call as
https://......./method/final_path/
I get the expected result, but if the call is changed to  https://......./method/final_path
I get 405-method not allowed.
According to FastAPI docs, the trailing slashes shouldn't matter, so ideally
@app.post('/method/final_path/', tags=['method/final_path'])
@app.post('/method/final_path', tags=['method/final_path'])

with postman calls:

*

*https://......./method/final_path/

*https://......./method/final_path
all the above 4 combinations should give the same result. Then what am I doing wrong?
Versions:
fastapi-0.63
starlette-0.13.6
Thanks in advance.

A: Try using APIRouter to define the route instead of directly using the app. The APIRouter has redirect_slashes set to True by default.


text:
Q: Use Stored Procedure OUT Parameter in Unix Script I have a ksh script that is directly Selecting a count from the database.  I am replacing this with a call with a stored procedure. My Stored Procedure selects into an OUT variable.
How do I capture the OUT value into my data file as declared in my script?
    bteq <<EOF
.RUN FILE $DBENV/1logon.txt
.export data file=$PMRootDir/$FOLDER_NME/SessLogs/pdbasis_count.txt
.set recordmode OFF;
.set sidetitles OFF;
.set titledashes off;

#This Select Statement is being replaced by the Stored Procedure Call
SELECT trim(COUNT(*))
FROM [Removed]
WHERE [Removed]

.IF ERRORCODE <> 0 THEN .QUIT 11;

.export reset;
.logoff;
.quit

EOF

A: You can try this one. The lv_status should give you the out parameter.
            ##Procedure Execution starts

         procname=$your_user_name."your_proc_name"
        echo $procname
        echo $procname |grep "("
        if [ $? -eq 0 ]
        then
            procname=`echo $procname|cut -f1 -d")"`",lv_status)";
        else
            procname=`echo $procname`"(lv_status)";
        fi
        echo "Executing $procname"

        bteq <<EOF
        .logon $tdpid/db_user_name,db_password
        .EXPORT FILE=$tempfile
        .SET WIDTH 3000
        .SET TITLEDASHES OFF;
        CALL $procname;
        .EXPORT RESET;
        .LOGOFF
        .EXIT
        EOF

        exit_status=$?
        lv_status=`tail +2 $tempfile`

        rm -f $tempfile

        if [ $lv_status ]
        then
            if [ $lv_status = "FAILED" -o $exit_status -ne 0 ]
            then
                echo "Error in executing procedure $procname";
                exit 1;
            fi
        else
            echo "The procedure does not have the mandatory OUT status parameter. Consider remodeling the code for full error trapping"
            exit 1
        fi

        echo "Procedure $procname completed successfully"


text:
Q: Python tkinter loading in progress I would like to know how to display the text "loading in progress" while the final text is loading after pressing the execute button?
import time
import random
import tkinter as tk

def load():
    my_label.config(text="Loading in progress...")  #how to display it?
    my_time = random.randint(1,10)
    time.sleep(my_time)
    my_label.config(text="Loaded!!!")

root = tk.Tk()
root.geometry('300x300')

my_button = tk.Button(root, text='Load', width=20, command=load)
my_button.pack(pady=20)

my_label = tk.Label(root, text='')
my_label.pack(pady=20)

root.mainloop()

Thank you for your answers

A: Use .after instead of sleep in tkinter to avoid blocking the main loop.
import time
import random
import tkinter as tk
from functools import partial

my_time = None

def load(my_time):
    if my_time is None:
        my_time = random.randint(2, 10)
    my_label.config(text=f"Loading in progress...{my_time}")
    my_time -=1
    timer = root.after(1000, load, my_time)
    if not my_time:
        root.after_cancel(timer)
        my_label.config(text="Loaded!!!")

root = tk.Tk()
root.geometry('300x300')

my_button = tk.Button(root, text='Load', width=20, command=partial(load, my_time))
my_button.pack(pady=20)

my_label = tk.Label(root, text='')
my_label.pack(pady=20)

root.mainloop()