Q: php maverick htaccess not parsed on port :8888 I've install a dev environment on my mac running os x maverick and everything works fine excepted url rewriting.
To be exact, when I go to localhost on the default port, it works.
but when I go to the website folder in terminal and I start apache on the port :8888 using this command:
php -S localhost:8888
then the .htaccess is not read.
I want to work this way in order to have my server logs in the terminal.
What is the problem?
This is my httpd.conf file:
ServerRoot "/usr"

    Listen 80

    LoadModule authn_file_module libexec/apache2/mod_authn_file.so
    LoadModule authn_dbm_module libexec/apache2/mod_authn_dbm.so
    LoadModule authn_anon_module libexec/apache2/mod_authn_anon.so
    LoadModule authn_dbd_module libexec/apache2/mod_authn_dbd.so
    LoadModule authn_default_module libexec/apache2/mod_authn_default.so
    LoadModule authz_host_module libexec/apache2/mod_authz_host.so
    LoadModule authz_groupfile_module libexec/apache2/mod_authz_groupfile.so
    LoadModule authz_user_module libexec/apache2/mod_authz_user.so
    LoadModule authz_dbm_module libexec/apache2/mod_authz_dbm.so
    LoadModule authz_owner_module libexec/apache2/mod_authz_owner.so
    LoadModule authz_default_module libexec/apache2/mod_authz_default.so
    LoadModule auth_basic_module libexec/apache2/mod_auth_basic.so
    LoadModule auth_digest_module libexec/apache2/mod_auth_digest.so
    LoadModule cache_module libexec/apache2/mod_cache.so
    LoadModule disk_cache_module libexec/apache2/mod_disk_cache.so
    LoadModule mem_cache_module libexec/apache2/mod_mem_cache.so
    LoadModule dbd_module libexec/apache2/mod_dbd.so
    LoadModule dumpio_module libexec/apache2/mod_dumpio.so
    LoadModule reqtimeout_module libexec/apache2/mod_reqtimeout.so
    LoadModule ext_filter_module libexec/apache2/mod_ext_filter.so
    LoadModule include_module libexec/apache2/mod_include.so
    LoadModule filter_module libexec/apache2/mod_filter.so
    LoadModule substitute_module libexec/apache2/mod_substitute.so
    LoadModule deflate_module libexec/apache2/mod_deflate.so
    LoadModule log_config_module libexec/apache2/mod_log_config.so
    LoadModule log_forensic_module libexec/apache2/mod_log_forensic.so
    LoadModule logio_module libexec/apache2/mod_logio.so
    LoadModule env_module libexec/apache2/mod_env.so
    LoadModule mime_magic_module libexec/apache2/mod_mime_magic.so
    LoadModule cern_meta_module libexec/apache2/mod_cern_meta.so
    LoadModule expires_module libexec/apache2/mod_expires.so
    LoadModule headers_module libexec/apache2/mod_headers.so
    LoadModule ident_module libexec/apache2/mod_ident.so
    LoadModule usertrack_module libexec/apache2/mod_usertrack.so
    #LoadModule unique_id_module libexec/apache2/mod_unique_id.so
    LoadModule setenvif_module libexec/apache2/mod_setenvif.so
    LoadModule version_module libexec/apache2/mod_version.so
    LoadModule proxy_module libexec/apache2/mod_proxy.so
    LoadModule proxy_connect_module libexec/apache2/mod_proxy_connect.so
    LoadModule proxy_ftp_module libexec/apache2/mod_proxy_ftp.so
    LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so
    LoadModule proxy_scgi_module libexec/apache2/mod_proxy_scgi.so
    LoadModule proxy_ajp_module libexec/apache2/mod_proxy_ajp.so
    LoadModule proxy_balancer_module libexec/apache2/mod_proxy_balancer.so
    LoadModule ssl_module libexec/apache2/mod_ssl.so
    LoadModule mime_module libexec/apache2/mod_mime.so
    LoadModule dav_module libexec/apache2/mod_dav.so
    LoadModule status_module libexec/apache2/mod_status.so
    LoadModule autoindex_module libexec/apache2/mod_autoindex.so
    LoadModule asis_module libexec/apache2/mod_asis.so
    LoadModule info_module libexec/apache2/mod_info.so
    LoadModule cgi_module libexec/apache2/mod_cgi.so
    LoadModule dav_fs_module libexec/apache2/mod_dav_fs.so
    LoadModule vhost_alias_module libexec/apache2/mod_vhost_alias.so
    LoadModule negotiation_module libexec/apache2/mod_negotiation.so
    LoadModule dir_module libexec/apache2/mod_dir.so
    LoadModule imagemap_module libexec/apache2/mod_imagemap.so
    LoadModule actions_module libexec/apache2/mod_actions.so
    LoadModule speling_module libexec/apache2/mod_speling.so
    LoadModule userdir_module libexec/apache2/mod_userdir.so
    LoadModule alias_module libexec/apache2/mod_alias.so
    LoadModule rewrite_module libexec/apache2/mod_rewrite.so
    #LoadModule perl_module libexec/apache2/mod_perl.so
    LoadModule php5_module libexec/apache2/libphp5.so
    LoadModule hfs_apple_module libexec/apache2/mod_hfs_apple.so

    <IfModule !mpm_netware_module>
    <IfModule !mpm_winnt_module>

    User _www
    Group _www

    </IfModule>
    </IfModule>

    ServerAdmin you@example.com

    DocumentRoot "/Library/WebServer/apachesites"

    <Directory />
        Options FollowSymLinks
        AllowOverride all
        Order deny,allow
        Deny from all
    </Directory>
    <Directory "/Library/WebServer/apachesites">
        Options Indexes FollowSymLinks MultiViews
        AllowOverride All
        Order allow,deny
        Allow from all

    </Directory>

    <IfModule dir_module>
        DirectoryIndex index.html
    </IfModule>

    <FilesMatch "^\.([Hh][Tt]|[Dd][Ss]_[Ss])">
        Order allow,deny
        Deny from all
        Satisfy All
    </FilesMatch>

    <Files "rsrc">
        Order allow,deny
        Deny from all
        Satisfy All
    </Files>
    <DirectoryMatch ".*\.\.namedfork">
        Order allow,deny
        Deny from all
        Satisfy All
    </DirectoryMatch>

    ErrorLog "/private/var/log/apache2/error_log"

    LogLevel warn

    <IfModule log_config_module>
        LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined
        LogFormat "%h %l %u %t \"%r\" %>s %b" common

        <IfModule logio_module>
          # You need to enable mod_logio.c to use %I and %O
          LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio
        </IfModule>

        CustomLog "/private/var/log/apache2/access_log" common

    </IfModule>

    <IfModule alias_module>

        ScriptAliasMatch ^/cgi-bin/((?!(?i:webobjects)).*$) "/Library/WebServer/CGI-Executables/$1"

    </IfModule>

    <IfModule cgid_module>

    </IfModule>

    <Directory "/Library/WebServer/CGI-Executables">
        AllowOverride None
        Options None
        Order allow,deny
        Allow from all
    </Directory>

    DefaultType text/plain

    <IfModule mime_module>
        TypesConfig /private/etc/apache2/mime.types

        AddType application/x-compress .Z
        AddType application/x-gzip .gz .tgz

    </IfModule>

    TraceEnable off

    Include /private/etc/apache2/extra/httpd-mpm.conf

    Include /private/etc/apache2/extra/httpd-autoindex.conf

    Include /private/etc/apache2/extra/httpd-languages.conf

    Include /private/etc/apache2/extra/httpd-userdir.conf

    Include /private/etc/apache2/extra/httpd-vhosts.conf

    Include /private/etc/apache2/extra/httpd-manual.conf

    <IfModule ssl_module>
    SSLRandomSeed startup builtin
    SSLRandomSeed connect builtin
    </IfModule>

    Include /private/etc/apache2/other/*.conf

And this is httpd-vhosts.conf
NameVirtualHost *:80

<VirtualHost *:80>
    DocumentRoot "/Library/WebServer/apachesites"
    ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log"
    CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common
</VirtualHost>
<VirtualHost *:8888>
    DocumentRoot "/Library/WebServer/apachesites"
    ErrorLog "/private/var/log/apache2/dummy-host.example.com-error_log"
    CustomLog "/private/var/log/apache2/dummy-host.example.com-access_log" common
</VirtualHost>

A: The built-in HTTP server ran by php -S is not Apache, thus there's no .htaccess nor mod_rewrite or any fancy stuff


Q: Setting ActionBarSherlock Theme for Android app READ UPDATE 2 BELOW FOR THE ANSWER
I'm trying to use ActionBarSherlock in my app. I checked out the 4.0.0 release from the project github repo, built it in Netbeans, then copied the library-4.0.0.jar file into my project's lib directory (I'm not using Eclipse).
It's just a skeleton activity right now, and it launches just fine in ICS, but when I run it on Gingerbread I get the following exception complaining that I haven't the app theme to Theme.Sherlock (or similar):
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.arashpayan.prayerbook/com.arashpayan.prayerbook.PrayerBook}: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
    at android.app.ActivityThread.access$1500(ActivityThread.java:117)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:130)
    at android.app.ActivityThread.main(ActivityThread.java:3683)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:507)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
    at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.generateLayout(ActionBarSherlockCompat.java:987)
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.installDecor(ActionBarSherlockCompat.java:899)
    at com.actionbarsherlock.internal.ActionBarSherlockCompat.setContentView(ActionBarSherlockCompat.java:852)
    at com.actionbarsherlock.ActionBarSherlock.setContentView(ActionBarSherlock.java:655)
    at com.actionbarsherlock.app.SherlockFragmentActivity.setContentView(SherlockFragmentActivity.java:316)
    at com.arashpayan.prayerbook.PrayerBook.onCreate(PrayerBook.java:44)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
    ... 11 more

The line it complains about (PrayerBook:44) is the call to setContentView. The app just consists of a single activity with an onCreate() method that I call setTheme() from at the top:
public void onCreate(Bundle savedInstanceState)
{
        setTheme(com.actionbarsherlock.R.style.Theme_Sherlock);
        super.onCreate(savedInstanceState);

        TextView rootTextView = new TextView(this);
        rootTextView.setText("Hello, world!");
        setContentView(rootTextView);

        getSupportActionBar().setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        ActionBar.Tab tab = getSupportActionBar().newTab();
        tab.setText("Prayers");
        getSupportActionBar().addTab(tab);

        tab = getSupportActionBar().newTab();
        tab.setText("Recents");
        getSupportActionBar().addTab(tab);

        tab = getSupportActionBar().newTab();
        tab.setText("Bookmarks");
        getSupportActionBar().addTab(tab);
}

I must be setting the theme incorrectly, but I just don't see how. Can anyone help?
UPDATE
Below, CommonsWare noted that the theme can be set in the AndroidManifest.xml. I've tried that like so:
<application android:label="@string/app_name" android:icon="@drawable/icon" android:theme="@style/Theme.Sherlock">
        <activity android:name="PrayerBook"
                  android:label="@string/app_name"
                  android:configChanges="orientation|keyboardHidden|screenLayout|uiMode|mcc|mnc|locale|navigation|fontScale|screenSize">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="LanguagesActivity" />
</application>

but Ant gives me an error when it tries to build the app:
/Users/arash/coding/prayerbook/AndroidManifest.xml:7: error: Error: No resource found that matches the given name (at 'theme' with value '@style/Theme.Sherlock').

UPDATE 2
With CommonsWare's help in his follow up comments, I was able to get it working. I needed to add ActionBarSherlock as a project dependency. To do so,
1) I removed library-4.0.0.jar and android-support-4.0.jar from my project's lib directory.
2) Next, navigate into the library folder inside the root of the ActionBarSherlock directory checked out from github. Type android update project so a build.xml and proguard.cfg file will be created for the library.
3) Finally, cd back into the main project directory and add ABS as a library dependency with android update project --path . --library ../ActionBarSherlock/library
The path to the --library in the command will vary according to where you checked out the repo. ActionBarSherlock and my app's project directory were sibling directories.

A: Usually, you set your theme in the manifest, as shown in the Android developer documentation (and linked to from the ActionBarSherlock theming page).
If you want to use ActionBarSherlock everywhere within your app, this works:
<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.Sherlock">

A: <!--Provides resources-->
<dependency>
   <groupId>com.actionbarsherlock</groupId>
   <artifactId>library</artifactId>
   <version>4.1.0</version>
   <type>apklib</type>
</dependency>
<!-Provides import links-->
<dependency>
   <groupId>com.actionbarsherlock</groupId>
   <artifactId>library</artifactId>
   <version>4.1.0</version>
   <type>jar</type>
   <scope>provided</scope>
 </dependency>

The hint is to use type "apklib", that's mean that maven will be using all sources (resources too). Other dependecy to jar file (scope "provided") is used to achieve link to sherlock classes during coding.

A: For me this was caused by not using the @style/ prefix. I.e. I had
<style name="AppTheme" parent="Theme.Sherlock.Light" />

instead of
<style name="AppTheme" parent="@style/Theme.Sherlock.Light" />

Which is kind of weird because I swear the default template value is something like:
<style name="AppTheme" parent="android:Theme.Holo.Light" />

A: If you wanna use custom style, I made a template for custom ActionBarSherlock style. Theme is defined in /values/styles.xml file. It is extended from Theme.Sherlock.Light theme. There are many parameters, you can set: icon, logo, divider, title, shadow overlay, action menu buttons, popup menu, action mode background, dropdown list navigation, tab style, display options etc. Almost everything, what you need, to create your custom action bar theme. I use this template in my apps, because it helps me to style action bar very quickly.
You can find this template on my GitHub. It is very easy to use. Just copy values and drawable directiories into your project and set android:theme parameter in application element in AndroidManifest.xml:
<application
    ...
    android:theme="@style/Theme.Example">

Drawables in my template were generated via Android Action Bar Style Generator. I use different naming convention for resources. This simple script renames all resources generated with Android Action Bar Style Generator to my own convention, used in the template.

A: Had the same problem. The app crashed altough the theme was set in the manifest. Setting the theme programmatically solved the problem:
@Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(R.style.AppTheme);
    super.onCreate(savedInstanceState);

A: This was happening to me in IntelliJ IDEA. I solved this issue by going to File > Project Structure > Project Settings > Facets > Select actionbarsherlock module in 2nd column > Check the "Library module" checkbox > Apply and OK > Save and Rebuild.
UPDATE After further review, my original response may be too specific, and will probably only work in certain cases. This error means that the dependencies have not been properly setup. In IntelliJ IDEA, follow these steps to properly setup actionbarsherlock as a module dependency:

*

*Download and extract the actionbarsherlock library from the zip (Note: You only need the “actionbarsherlock” folder)

*Copy and paste it alongside your Android project

*Open your project in IntelliJ

*File > Project Structure > Project Settings > Modules > Add (green ‘+’ above second column) > Import Module > Select actionbarsherlock directory in file browser dialog > OK > Create module from existing sources > Next

*Uncheck the “test” folder so it is not added to the project and click “Next”

*Under the Libraries tab, android-support-v4 should be checked, click “Next”

*Under the Modules tab, actionbarsherlock should be checked, click “Next”

*If it asks you to Overwrite actionbarsherlock.iml, choose “Overwrite” and then "Finish" (You should be returned to the Modules section of the Project Structure dialog)

*Select the actionbarsherlock module from the second colum and under the Dependencies tab in the third column, check “Export” next to the android-support-v4 library

*Almost there!

*Now select your project module from the second column, and under the Dependencies tab, click the Add button (green ‘+’ on the far right side of the dialog)

*Select Module Dependency and choose actionbarsherlock from the dialog that pops up and press “OK”

*Now click “Apply” or “OK” to accept the changes

That should do the trick.

A: This is not an answer for the OP's question, but I'll just describe how I managed to get the same exception as he mentions, in the hopes it may help someone else:
    java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.Merlinia.MMessaging_Test/com.Merlinia.MMessaging_Test.TestObjectsActivity}:
    java.lang.IllegalStateException: You must use Theme.Sherlock, Theme.Sherlock.Light, Theme.Sherlock.Light.DarkActionBar, or a derivative.

In my case the solution was very simple, although it took me way too long to find it. Everything you read about this exception says "check that you've specified the theme in the manifest.xml file", so I took a quick look at my manifest.xml file, and there it was. So then I tried various other things.
Finally, I took a closer look at my manifest.xml file. I'd made the mistake of specifying the theme for the main activity, not for the whole application!


Q: On the meaning of formal sums of $k$-cubes, i.e. $k$-chains (in integration on manifolds) A singular $k$-cube in $A \subseteq \mathbb R^n$ is a continuous function $c : [0,1]^k \to A$. A singular $0$-cube in $A$ is then a function $f : \{0\}\to A$, what amounts to the same thing, a point in $A$. A formal sum of singular $k$-cubes in $A$ multiplied by integers is an $k$-chain, i.e. sums like
$$
 3c_1 + 2c_2 - 4c_3
$$
for singular $k$-cubes $c_1, c_2, c_3$. These could be defined more formally as "polynomials" in the $k$-cubes on $A$, i.e. functions from the $k$-cubes to $\mathbb Z$ for which only finitely many function values are non-zero.
By the way these definitions are taken from Spivak, Calculus on Manifolds, page 97 (the more formal one is from an exercise therein).
So now my question. As formal sums they do not admit any interpretation behind being merely formal objects with prescribed rules to manipulate them. Now for an $n$-cube (and also an $n$-chain by linear extension) its boundary is defined as such a formal sum of $n-1$-cubes got from this cube by fixing one variable.
Then relations like $\partial^2 = 0$, or extending the integral over $n$-chains lineary from $n$-cubes, all work out fine, and ultimately lead to Stokes theorem. But when I look at the definition, and try to give it some meaning, or picture to have, such a formal sum seems to correspond to an union of sets (i.e. the parts of the boundary) enriched by some notion of orientation (by the sign in the sum) and "speed of transversal" (by its magnitude) (Remark: Actually this seems more of a multiset, as different $n$-cubes could share parts as sets).
So, it might be possible to interpret these sums pointwise, i.e. for example $2c_1 - c_2$ not as a formal sum, but as the pointwise addition of functions, i.e. $2\cdot c_1(x) - c_2(x)$ for all $x \in [0,1]^k$ if $c_1, c_2$ are singular $k$-cubes. Of course, I mean this addition if we interpret every element of $\mathbb R^n$ as a vector (i.e. a position vector w.r.t. the origin), as a priori points could not be added.
Comparing with the picture (I appended one from the above mentioned book) this seems to work fine. So why not use this more concrete definition, but use abstract formal sums? (or is my interpretation to naive, and fails somewhere?)

A: Let's see what happens when we interpret these sums pointwise. For example, $\partial I^2$ is an 1-chain given by
$$\partial I^2 = -I^2_{(1,0)} + I^2_{(1,1)} + I^2_{(2,0)} - I^2_{2,1}$$
Now evaluating this "sum" at a point $x \in [0,1]$ gives
$$\partial I^2 = -(0,x) + (1, x) + (x, 0) - (x, 1) = (1, -1) $$
Try the same calculation for $\partial I^3$ and you'll get $(1,-1,1)$. Clearly this doesn't make sense.
To see how Spivak "summed" the $(n-2)$-chain in his proof of $\partial^2=0$, let's take $\partial^2I^2$ as an example. Now we must sum the boundaries of each $I^2_{(i, \alpha)}$ with the correct orientation.
So, for instance,
\begin{align}
\partial (-I^2_{(1,0)})(0)
&= -[-(I^2_{(1,0)})_{(1,0)}(0) + (I^2_{(1,0)})_{(1,1)}(0)] \\
&= -[-I^2_{(1,0)}(I^1_{(1,0)}(0)) + I^2_{(1,0)}(I^1_{(1,1)}(0))] \\
&= -[-I^2_{(1,0)}(0) + I^2_{(1,0)}(1)] \\
&= -[-(0,0) + (0,1)]\\
&= (0,0) + - (0,1)
\end{align}
We don't add these: they are just "oriented" points in $\mathbb{R}^2$.
Similarly, we get
\begin{align}
\partial(I^2_{(1,1)})(0) &= -(1,0) + (1,1)\\
\partial(I^2_{(2,0)})(0) &= -(0,0) + (1,0)\\
\partial(-I^2_{(2,1)})(0) &= (0,1) + -(1,1)
\end{align}
Each of the four corners of the square are appear twice with opposite signs.
For instance,
$(0,1) = (I^2_{(1,0)})_{(1,1)} = (I^2_{(2,1)})_{(1,0)}$ (this is the statement $(I^n_{(i,\alpha)})_{(j,\beta)} = (I^n_{(j+1,\beta)})_{(i,\alpha)}$ in Spivak's proof). But it's orientation is negative in the former and positive in the latter. So they cancel each other out - they are not "added".
To summarize, we don't add two different n-cubes in an n-chain. We add the coefficients of the same n-cube if it appears more than once.


Q: I have a data structure defined as QMap, how may I sort this by value? I have a randomly generated a list of integers and populated a QMap with these values but i would like to get the QMap sorted by value

A: This is a demonstration of how to sort a QMap <int, int> by value and not by key in qt C++.
The values of the QMap were extracted and stored in a QList container object, then sorted through the qSort method. The keys were also stored in a QList for themselves. After sorting is complete, the QMap object is then cleared and the Keys and values are then inserted back in the QMap container in ascending order by value. See solution below:
#include <QCoreApplication>
#include <qalgorithms.h>
#include <QMap>
#include <QDebug>
#include <QList>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    QMap <int, int> dataMapList;
    //QMap <int, int> sorted = new QMap<int, int>();
    QList <int> keys; // container to store all keys from QMap container
    QList<int> values; // container to store all values from QMap container
    QMap<int, int>::Iterator h; // used to loop/ iterate through QMap

    // used to iterate through QLists
    QList<int>::Iterator i; //
     QList<int>::Iterator j;

     //inserts to QMap Container
    dataMapList.insert(1,34);
    dataMapList.insert(3,2);
    dataMapList.insert(2,32);
    dataMapList.insert(14,89);
    dataMapList.insert(7,23);

    h=dataMapList.begin();

     qDebug()<< "unsorted";
    //list out the unsorted values along with their respective keys
    while(h!=dataMapList.end()){
        qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
        h++;
    }

    values = dataMapList.values(); // pass all values in the QMap to a QList container to store values only
    keys= dataMapList.keys(); // pass all keys in the QMap to a QList container to store already sorted by default keys

    qSort(values); // sorts the values in ascending order
    dataMapList.clear(); // empties the QMap

    i=values.begin();
    j=keys.begin();

    // insert back the sorted values and map them to keys in QMap container
    while(i!=values.end() && j!=keys.end()){

        dataMapList.insert(*j, *i);
        i++;
        j++;
    }

    qDebug() << "sorted" << endl;
    h=dataMapList.begin();
    //the display of the sorted QMap
    while(h!=dataMapList.end()){
        qDebug() << "[" << h.key()<<"], " <<"[" <<h.value()<<"]" << endl;
        h++;
    }

    return a.exec();
}

Note: The iterators for the QMap and QList were used to traverse through the containers to access the value and/or keys stored. These also helped with displaying the items in the list (unsorted and sorted). This solution was done in a Qt console application.

A: In QMap by default the items are always sorted by key. So, if you iterate over QMap like:
 QMap<int, int>::const_iterator i = yourQMap.constBegin();
 while (i != yourQMap.constEnd()) {
     cout << i.key() << ": " << i.value() << endl;
     ++i;
 }

You'll get result sorted by keys.
Try to think about transforming your task to fit standard algorithms.
Otherwise, you can use this approach to get sorted your titles:
QList<int> list = yourQMap.values();
qSort(list.begin(), list.end());

And then, if you need -- get associated keys by calling method QMap::key(const T &value);.

A: Another alternative, depending on the exact case, is simply to swap the keys and values around since the keys will be automatically sorted by the QMap. In most cases, the values will not be unique, so just use a QMultiMap instead.
For example, let's say we have the following data in a QMap:
Key       Value
---       -----
1         100
2         87
3         430
4         87

The following piece of code will sort the data by value.
QMap<int, int> oldMap;
QMultiMap<int, int> newMap;
QMapIterator<int, int> it(oldMap);

while (it.hasNext())
{
    it.next();
    newMap.insertMulti(it.value(), it.key()); //swap value and key
}

Our new map now looks like this:
Key       Value
---       -----
87        4
87        2
100       1
430       3


Q: Python как округлить число без округления последней цифры x = 10.19
print(round(x, 1))

Ответ будет 10.2.
Как сделать так, чтобы ответ был 10.1?
То есть не округлить, а обрезать.

A: Самый простой вариант:
x = float(input())   # Запрос ввода числа
res = x * 100 // 10  # Умножаем на 100 и делим на 10 чтобы откинуть остаток
res = res / 10       # Делим на 10 чтобы получилось нужно число
print(res)

A: float("{0:.1f}".format(10.19))

10.1

A: У функции round() есть ещё один аргумент. Он показывает до какого количества знаков после запятой следует округлять:
round(10.19, 1)


Q: Converting webpage into HTML I want to convert a webpage into an HTML  page programatically.I searched many sites but only providing details like converting into pdf format etc.For my program now I'm saving a page as .html and then extracting the necessary data.Is there any way to convert the webpage to an html page? Can anyone help me?Any help would be appreciated.
Well I can explain in detail
I am extracting the names of users who like a page which i'm admin of . So I found a link https://www.facebook.com/browse/?type=page_fans&page_id=pageid where i can find the list of users. So for getting it first of all i have to save it as a .html page and then extract necessary data. So here I'm converting it into .html and then extract the data. But what I need is that convert that page into an HTML page using my program. I hope my question is clear now

A: Oracle provides the following code snippet for programmatically retrieving an html page here.
import java.net.*;
import java.io.*;

public class URLReader {
    public static void main(String[] args) throws Exception {

        URL oracle = new URL("http://www.oracle.com/");
        BufferedReader in = new BufferedReader(
        new InputStreamReader(oracle.openStream()));

        String inputLine;
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
    }
}

Instead of printing to console, you can save the contents to a file by using a FileWriter and BufferedWriter (example from this question):
    FileWriter fstream = new FileWriter("fileName");
    BufferedWriter fbw = new BufferedWriter(fstream);

    while ((line = in.readLine()) != null) {

        fbw.write(line + "\n");

    }

A: Webpages are already HTML, if you want to save a webpage as HTML you can do this via the Firefox > Save Page As menu on Firefox. Or through File menu on other browsers.
If you need to download multiple pages in HTML from the same website or from a list of URLs there is a software that will make it easier for you: http://www.httrack.com/


Q: User Pool allows two users with same email despite configuration Background
I'm using aws-amplify to interact with Cognito.  So when a user registers with my app, I call Auth.signUp().  I'm passing only username (email) and password to this function.
My user pool is configured to allow sign in by email only:

The Bug?
In my front end code, I accidentally registered an event listener twice, so Auth.signUp() was being called twice (concurrently, or at least in rapid succession) with the same parameters.
This resulted in two users being created in my User Pool, with the same email.  My understanding of my user pool configuration suggests that this shouldn't be possible.

Race Condition?
My first thought was that since I'm sending two requests so close together, this may be some sort of unavoidable race condition.  If I introduce an artificial pause between the calls (a breakpoint, or a setTimeout, say), everything works as expected.
However, even with the requests very tightly spaced, the second request does return the error response I'd expect:
{ code: 'InvalidParameterException',
  name: 'InvalidParameterException',
  message: 'Alias entry already exists for a different username'
}

Sadly, this response is misleading, because I do get a second (duplicate) user created in my pool with this request.

MCVE
This is easy to reproduce by exercising Auth.signUp twice concurrently, either in a node script or a browser.  This repository contains examples of both.

The Question(s)

*

*Is this a legitimate bug with Cognito?

*Is a preSignUp Lambda trigger my only way to defend against this?  If so, what would the broad strokes of that implementation look like?

A: I talked to AWS, still no fix and no time estimation.

A: I sent this to AWS support. They're aware of the issue but have no ETA.

Thanks for contacting AWS Premium Support.  I understand that you
  would like to know whether Cognito team is aware of the issue posted
  here[1].
I checked with Cognito team on our end and YES, they are aware of this
  issue/bug. Good news is, we already have trouble ticket open with
  Cognito Team to fix the issue.  However, I won't be able to provide an
  ETA on when this fix will go live as I don't have any visibility into
  their development/release plans. But, I would like to thank you for
  your valued contribution in bringing this issue to our attention, I do
  appreciate it.

A: Cognito limits usernames to one user only. However, yes multiple user can share an email.


Q: Programmatic import in Python 3? Say I have a directory foo that contains some .py files.
Each of these python files has a class Bar defined.
Say there were three .py files called  baz.py, qux.py and quux.py - then to get the bar classes I could write:
import foo.baz
import foo.qux
import foo.quux

bars = [
    foo.baz.Bar,
    foo.qux.Bar,
    foo.quux.Bar,
]

However, rather than list out all the imports like this and all the Bar names, I want to populate bars programmatically.
That is, I want to write some code to populate bars that doesn't change as .py files are added or removed from the foo directory.
One way to do this might be to use Path('foo').iterdir() to list the .py files, but then how do I do a programmatic import of a string and name its Bar class?
Or is there some totally different approach to achieve this?
bars = []
for py_file in the directory foo:
   import foo.py_file  ???
   bars.append(foo.py_file.Bar)  ???

A: Here is one approach using glob module to match the pathnames of the modules we would like to import and importlib's SourceFileLoader to import.
from glob import glob
from importlib.machinery import SourceFileLoader

modules = glob('foo/*.py')

bars = list(map(lambda pathname: SourceFileLoader(".", pathname).load_module().Bar, modules))

A: You can use importlib to import the modules dynamically. But you need to find them first. If you include foo.__init__.py in the source, then then foo.__file__ will be that name. You can use that as the base of your glob, but you need to make sure you don't try to import __init__.py itself. This technique is nice because you don't have to worry about another bit of source importing the same module name but getting a different module in memory.
from pathlib import Path
import importlib
import foo

def no_magic(paths):
    for path in paths:
        if not path.name.startswith("_"):
            yield path

bars = []
for py in no_magic(Path(foo.__file__).resolve().parent.glob("*.py")):
    mod = importlib.import_module(f"foo.{py.stem}", foo)
    bars.append(mod.Bar)

print(bars)


Q: How to install Kafka inside a docker image? I am working on docker for the first time where I am trying to run my pyspark code on a docker container.
This my project structure.

My Dockerfile content:
from gcr.io/datamechanics/spark:platform-3.1-dm14

ENV PYSPARK_MAJOR_PYTHON_VERSION=3
WORKDIR /opt/application/

RUN wget  https://jdbc.postgresql.org/download/postgresql-42.2.5.jar
RUN mv postgresql-42.2.5.jar /opt/spark/jars

COPY requirements.txt .
RUN pip3 install -r requirements.txt

COPY main.py .
COPY tweepy_kafka_producer.py .
COPY kafka_spark.py .

docker-compose.yml file content:
version: '2'

services:
  spark:
    image: docker.io/bitnami/spark:3
    environment:
      - SPARK_MODE=master
      - SPARK_RPC_AUTHENTICATION_ENABLED=no
      - SPARK_RPC_ENCRYPTION_ENABLED=no
      - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
      - SPARK_SSL_ENABLED=no
    ports:
      - '8080:8080'
  spark-worker:
    image: docker.io/bitnami/spark:3
    environment:
      - SPARK_MODE=worker
      - SPARK_MASTER_URL=spark://spark:7077
      - SPARK_WORKER_MEMORY=1G
      - SPARK_WORKER_CORES=1
      - SPARK_RPC_AUTHENTICATION_ENABLED=no
      - SPARK_RPC_ENCRYPTION_ENABLED=no
      - SPARK_LOCAL_STORAGE_ENCRYPTION_ENABLED=no
      - SPARK_SSL_ENABLED=no

I am trying to read tweets using tweepy library, send them to Kafka & read data from Kafka using Spark streaming. All this is running fine on my local and I trying to learn how can I run the same on a docker container. To do that, I have created a docker container and installed libraries from my requriements.txt file using below commands:
curl -LO https://raw.githubusercontent.com/bitnami/bitnami-docker-spark/master/docker-compose.yml
docker build -f Dockerfile -t sparkcontainer .

My requirements.txt file contains only four packages: pyspark, kafka, python-kafka & tweepy
I started the docker image using the steps below (8558b79243f8 is my docker image name):
docker run -i -t 8558b79243f8 /bin/bash

I do ls and these are the files I see:
185@f4a100a4ad06:/opt/application$ ls
kafka_spark.py  main.py  requirements.txt  tweepy_kafka_producer.py

When I try to run the python file that pushes data into a kafka topic:
185@f4a100a4ad06:/opt/application$ python tweepy_kafka_producer.py

I see the below error message:
    Traceback (most recent call last):
  File "tweepy_kafka_producer.py", line 40, in <module>
    producer = KafkaProducer(bootstrap_servers='localhost:9092')
  File "/opt/conda/lib/python3.8/site-packages/kafka/producer/kafka.py", line 381, in __init__
    client = KafkaClient(metrics=self._metrics, metric_group_prefix='producer',
  File "/opt/conda/lib/python3.8/site-packages/kafka/client_async.py", line 244, in __init__
    self.config['api_version'] = self.check_version(timeout=check_timeout)
  File "/opt/conda/lib/python3.8/site-packages/kafka/client_async.py", line 900, in check_version
    raise Errors.NoBrokersAvailable()
kafka.errors.NoBrokersAvailable: NoBrokersAvailable

I understand that I have to install Kafka in the docker image.
Could anyone let me know how can I configure Kafka inside my docker image ?

A: Kafka and Spark are distributed processes; and its a bad practice to use more than one process inside a Docker container.
Instead, add more services to your existing Docker Compose file, copied from existing Docker Compose setups from Kafka.

My requirements.txt file contains only four packages: pyspark, kafka, python-kafka & tweepy

You don't need two Kafka dependencies ; you only need pyspark and tweepy since Spark can write to Kafka on its own.
Or you could create a 5th (if counting Zookeeper), for a plain Python container with your producer application that has no Spark dependencies


Q: Negative scaling mirror alternative Unity I am trying to set up an airplane model downloaded from the sketchup warehouse, and in order to mirror the wings (the imported mirror setup had lighting and texture bugs) I have to scale the wings by -1. I want to attach parts of the plane via fixed joints to the fuselage, but when I scale the rigidbody/joint by -1 it freaks out on load. Is there an alternative mirror method or something that needs to be changed on the joints.
If this belongs on another forum (other than unity answers) tell me and I will repost there.
Thanks.

A: I found a solution, in which I put the rigidbody in a gameobject that parented the negatively scaled mesh.


Q: Login Example with nodejs and jsonwebtoken: can't read the token verification result My MIDDLEWARE checks if the tokens provided by users are correct.
The secuirity control, implemented by using jsonwebtoken, was inside the middleware and it was working fine.
After I decided to move all this security checks in another file: TokenManger.js
But I don't know how to set the code between the two files.
I tried many ways but no one is working.
So just for a better understanding I paste in the following an example code, which is not working. This is about the middleware:
...
router.use(function(req,res,next){
        var token = req.body.token || req.query.token || req.headers['x-access-token'];
        //decode token
        if(token){
            TokenManager.verifyToken(token,true,function(err,key){
                if(err) return res.json({ success : false, message : "Failed to authenticate token"});
                else next();
            });
        }else{
            // no token, return error
            return res.status(403).send({
                success : false,
                message: 'No token provided!'
            });
        }
});
...

In the other hand this is an example (and not working) implementation of the TokenManager.js:
var _ = require('lodash');
var jwt = require('jsonwebtoken');
var config = require('../../config.js');

var TokenManager = {
    createToken: function(user) {
        if(user.admin){
            var token = jwt.sign(user, config.SECRET_WORD.ADMIN,{expiresIn:config.EXPIRE_TIME.ADMIN_TOKEN});
        }else{
            var token = jwt.sign(user, config.SECRET_WORD.USER,{expiresIn:config.EXPIRE_TIME.USER_TOKEN});
        }
        return token;
    },
    verifyToken: function(token, admin, decode){
        if(admin){
            //admin authentication
            jwt.verify(token, config.SECRET_WORD.ADMIN, function(err,key){
                if(err){
                    return false;
                }else{
                    return true;
                }
            });
        }else{
            //user authentication
            jwt.verify(token, config.SECRET_WORD.USER, function(err,key){
                if(err){
                    return false;
                }else{
                    return true;
                }
            });
        }
    }
}

module["exports"] = TokenManager;

Actually the createToken(user) function is working fine with the previous code, there is a problems only with the verifyToken(token, admin, decode) function. But I care about the design so if you have suggestions about the creation too, they are more than welcome.
Just to complete the picture, this is how I call the createToken(user) function:
...
.post(function(req,res){
        User.findOne({ username: req.body.username }, function(err,user){
            if(err) throw err;
            if(!user){
                res.json({ success: false, message: 'Authentication failed. User not found!' });
            }else{
                if(user.password != req.body.password){
                    res.json({ success: false, message: 'Authentication failed. Wrong password!' });
                }else{
                    //token creation
                    var token = TokenManager.createToken(user);
                    res.json({
                        success: true,
                        token: token
                    });
                }
            }
        });
    });
...

A: You are passing function(err, key) to verifyToken, but there is not callback in the signature of verifyToken.
Try changing the verifyToken function to
verifyToken: function(token, admin, callback){
    if(admin){
        //admin authentication
        jwt.verify(token, config.SECRET_WORD.ADMIN, callback);
    }else{
        //user authentication
        jwt.verify(token, config.SECRET_WORD.USER, callback);
    }
}

Update : Without callback
verifyToken: function(token, admin){
    try {
       if(admin){
          //admin authentication
          jwt.verify(token, config.SECRET_WORD.ADMIN, callback);
       }else{
          //user authentication
          jwt.verify(token, config.SECRET_WORD.USER, callback);
       }
       return true;
    } catch(err)
       return false;
    }
}

And use like this in your middleware:
if (TokenManager.verifyToken(token,true)){
    return next();
} else {
    return res.json({ success : false, message : "Failed to authenticate token"});
}


Q: Jquery Daily Timer Failing I am using this jQuery code to display the left left until 10am locally.
Between 10am and 14:00pm it removes some images.
Then after 14:00 it should display time left until 10am. It also adds an offset to account for weekends.
It works brilliantly most of the time, however it seems after 14:00 it goes way over the time...
Can anyone see why this is failing, I've been looking at it for to long... now I'm just confussed! Please help!
$(document).ready(function() {
// 24 hour based
var targetTime = 1000;
var targetHour = 10;
var openingTime = 1400;
var openingHour = 14;

var currentTime = new Date();

// sun 0 mon 1 ... fri 5 sat 6
var currentDay = currentTime.getDay();

var offset = 24;
// friday
if (currentDay === 5) {
    offset = 60;
} // saturday
else if (currentDay === 6) {
    offset = 48;
}

var the_current_time = ''+ currentTime.getHours() + '' + currentTime.getMinutes() + '';

if( the_current_time > targetTime && the_current_time < openingTime ) {

    var time_hours = (openingHour + offset) - currentTime.getHours() - 1;
    var time_min = 60 - currentTime.getMinutes();
    var time_seconds = 60 - currentTime.getSeconds();

    $('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
    $('#watch_image').attr('src','http://cdn.shopify.com/s/files/1/0085/1702/t/1/assets/closed-until-icon.png');
    $('#time-left-banner').css('width','275px');
    $('.add-to-button').css('display','none');
    $('#purchase').css('display','none');

}
else if( the_current_time > targetTime && the_current_time > openingTime ) {

     var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
     var time_min = 60 - currentTime.getMinutes();
     var time_seconds = 60 - currentTime.getSeconds();

    $('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);

}

else {
 var time_hours = (targetHour + offset) - currentTime.getHours() - 1;
 var time_min = 60 - currentTime.getMinutes();
 var time_seconds = 60 - currentTime.getSeconds();

 $('#hours_left').append(time_hours, ':',time_min < 10 ? "0" : "" , time_min , ':' , time_seconds < 10 ? "0" : "" , time_seconds);
}

});

A: First, I would simplify the code a bit. The three var calculation in all three branches seem to be the same. So is the updating of #hours_left. You should be able to factor them out of the if. This will also reduce the number of if branches from 3 to 1 - if I am not missing something.
As for the problem, I would look at the_current_time. You are not zero padding the minutes, so 10:05 will become 105, or 1:05. I can't see how this would cause any dramas, as the calculations do not depend on this value, but it will change the if branch you will take.

Ah, I missed the time_hours calculation difference in the first branch of if. It uses opening_hours instead of target_hours. This explains why a bad the_current_time will make a difference on the reported value.


Q: SessionNotCreatedException in Eclipse "Appium" code My Code to execute a simple click button automation is given below , I am very new to appium so I am just trying to get my app and click one button , as i have given my exception down it is stopping me to proceed
public class IOSTester {
    public static void main(String[] args) throws Exception {
    WebDriver driver;
     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
     capabilities.setCapability(CapabilityType.VERSION, "8.1");
     capabilities.setCapability("deviceName","iPadAir Simulator");
     capabilities.setCapability("app", "/Users/AZ-Admin/Documents/test.app");
     driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);

     if(driver!=null)
     {
         driver.quit();
 }

     driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIAButton[1]")).click();
 }
 }

I Got the below exception when the compiler reached "driver = new RemoteWebDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);" , can anyone help me
Exception in thread "main" org.openqa.selenium.SessionNotCreatedException: A new session could not be created. (Original error: Requested a new session but one was in progress) (WARNING: The server did not provide any stacktrace information)
Command duration or timeout: 1.19 seconds
Build info: version: '2.44.0', revision: '76d78cf', time: '2014-10-23 20:02:37'
System info: host: 'CodeWarrior.local', ip: '192.168.0.114', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.10.1', java.version: '1.7.0_71'
Driver info: org.openqa.selenium.remote.RemoteWebDriver
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:526)
    at org.openqa.selenium.remote.ErrorHandler.createThrowable(ErrorHandler.java:204)
    at org.openqa.selenium.remote.ErrorHandler.throwIfResponseFailed(ErrorHandler.java:156)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:599)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:240)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:126)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:153)
    at CalculatorTest.IOSTester.main(IOSTester.java:28)

Thank you

A: Change the code to
public class IOSTester {
    public static void main(String[] args) throws Exception {
    AppiumDriver driver;
     DesiredCapabilities capabilities = new DesiredCapabilities();
     capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
     capabilities.setCapability(CapabilityType.VERSION, "8.1");
     capabilities.setCapability("platformName", "iOS");
     capabilities.setCapability("deviceName","iPad Air");
     capabilities.setCapability("app", "/Users/AZ-Admin/Documents/test.app");
     driver = new AppiumDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
     driver.findElement(By.xpath("//UIAApplication[1]/UIAWindow[1]/UIAButton[1]")).click();
 }
 }

Download Appium Driver.jar and attach it to your code file and Import AppiumDriver


Q: Updating caller's argument array from within a function In Bash I can set $@ this way:
set -- a b c

Then, I can inspect the content of $@:
printf '%s\n' "$@"

which would show:
a
b
c

However, if I do this in a function:
f() {
    set d e f
}

set a b c
f
printf '%s\n' "$@"

I still get
a
b
c

and not
d
e
f

How can I make my function update caller's $@?  I tried with BASH_ARGV, but it didn't work.
I am trying to write a function that processes the command line arguments and removes certain items from there (while setting a variable) so that the caller doesn't need to bother about them.  For example, I want all my scripts to turn on their debug logging if I invoke them with --debug without having to write the code to process that in each script and placing that logic in a common "sourced" function instead.
Note: I don't want to fork a subshell.

A: You cannot change the values of arguments, as they are passed by reference
in bash functions.
The best you can do is to pass the arguments you want to process, and return
the ones not processed yet.
Something in the lines of:
process_arguments() {
    # process the arguments
    echo "original arguments : $@"
    local new_arguments=(a c)

    echo ${new_arguments[@])
}

new_arguments=$(process_arguments a b c)
set -- $new_arguments

If you don't want the trouble of a "subshell", you can use a global var:
arguments=""

process_arguments() {
    # process the arguments
    echo "original arguments : $@"
    local new_arguments=(a c)
    arguments="${new_arguments[@]}"
}

process_arguments a b c # no subshell
set -- $arguments

As suggested by @ruakh, you can also use arguments as an array, like this:
arguments=()

process_arguments() {
    # process the arguments
    echo "original arguments : $@"
    local new_arguments=(a c)
    arguments=( "${new_arguments[@]}" )
}

process_arguments a b c # no subshell
set -- "${arguments[@]}"

A: This is a matter of scope: Functions each have their own parameter array, independently of the script:
$ cat test.bash
#!/usr/bin/env bash
f() {
    printf '%s\n' "Function arguments:" "$@"
}
printf '%s\n' "Script arguments:" "$@"
f 'a b' 'c d'
$ chmod u+x test.bash
$ ./test.bash 'foo bar' baz
Script arguments:
foo bar
baz
Function arguments:
a b
c d

So when you set the parameter array, that only applies within the current scope. If you want to change the script parameter array, you need to set it outside of any function. Hacks like set -- $(f) are not going to work in general, because it can't handle whitespace in arguments.
A general solution gets much uglier: you'd need to printf '%s\0' "$parameter" in the function and while IFS= read -r -d'' -u9 in the script to put the returned values into an array, and then set -- "${arguments[@]}".
I hope this is possible to do reliably some other way, but that's all I got.

A: vfalcao's approach is good, though the code in that answer wouldn't handle whitespaces accurately.
Here is the code based on the same idea that does handle whitespaces well:
wrapper() {
  # filter args
  args=()
  for arg; do
    if [[ $arg = arg1 ]]; then
      # process arg1
    elif [[ $arg = arg2 ]]; then
      # process arg2
    elif ...
      # process other args
    else
      args+=("$arg")
    fi

    # call function with filtered args
    wrapped_function "$args[@]"
  done
}

wrapper "$@"

An example implementation here: base-wrapper


Q: Retrieving command invocation in AWS SSM I am trying to send command to a running ubuntu ec2 instance. I have configured the appropriate role and I have an ssm agent running on the ec2 instance. Using the boto3 SDK I am able to use the client.send_command() function to successfully send a shell command and was subsequently able to get the command Id. Now the challenge is polling for the result. I am trying to use the  client.get_command_invocation() function but keep getting a InvocationDoesNotExist error. I am confident that I am using the correct command ID and instance ID because I have tested these using the AWS CLI as in  aws ssm list-command-invocations --command-id #### --instance-id i-##### and this worked. Here is a snippet of my code:
`ssm_client = boto3.client('ssm')
target_id = "i-####"
response = ssm_client.send_command(
            InstanceIds=[
                target_id
                    ],
            DocumentName="AWS-RunShellScript",
            Comment="Code to run" ,
            Parameters={
                    "commands": ["ls -l"]
                        }
            )
cmd_id= response['Command']['CommandId']
response = ssm_client.get_command_invocation(CommandId=cmd_id,
InstanceId=target_id)
print(response)`

Here is the returned error:
botocore.errorfactory.InvocationDoesNotExist: An error occurred (InvocationDoesNotExist) when calling the GetCommandInvocation operation
Thanks in advance.

A: Just add these 2 line.
import time
time.sleep(2)

Then It'll work properly generally it take only 0.65sec but it's better to give 2 sec. To make it better you can add some cool stuffs like some print statement in for loop and sleep inside it something like that.

A: The following worked for me. Check out the API documentation for how to update the default delays and max attempts at https://boto3.amazonaws.com.
from botocore.exceptions import WaiterError
ssm_client = boto3.client(
    "ssm",
    region_name=REGION,
    aws_access_key_id=KEY,
    aws_secret_access_key=SECRET,
)

waiter = ssm_client.get_waiter("command_executed")
try:
    waiter.wait(
        CommandId=commands_id,
        InstanceId=instance_id,
    )
except WaiterError as ex:
    logging.error(ex)
    return

A: I had the same issue, I fixed it by adding a time.sleep() call before calling get_command_invocation(). A short delay should be enough.

A: time.sleep does the job 99% of the time. Here is a better way to do this:
MAX_RETRY = 10

get_command_invocation_params = {
    'CommandId': 'xxx',
    'InstanceId': 'i-xxx'
}

for i in range(MAX_RETRY):
    try:
       command_executed_waiter.wait(**get_command_invocation_params)
       break
    except WaiterError as err:
        last_resp = err.last_response
        if 'Error' in last_resp:
            if last_resp['Error']['Code'] != 'InvocationDoesNotExist' or i + 1 == MAX_RETRY:
                raise err
        else:
            if last_resp['Status'] == 'Failed':
                print(last_resp['StandardErrorContent'], file=sys.stderr)
                exit(last_resp['ResponseCode'])
        continue


Q: Can't Access CSS Selector's Properties from Javascript Here's a very basic question: why is the finishLoading() function in the code below not able to access the 'opacity' property for the #myStyle CSS selector? The alert doesn't display anything, and I've verified that the 'opacity' property is 'false'.
Thanks very much!
<html>
<head>
<style type="text/css">
<!--
#myStyle
{
    opacity: 0.50;
}
-->
</style>

<script type="text/javascript">
<!--
function finishedLoading()
{
    alert(document.getElementById('myStyle').style.opacity);
}
-->
</script>
</head>
<body onload="finishedLoading();">

    <div id="myStyle">
        hello
    </div>

</body>
</html>

A: You can get the values set through class only after their computation.
var oElm = document.getElementById ( "myStyle" );
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle)
{
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue("-moz-opacity");
}
else if(oElm.currentStyle)    // For IE
{
strValue = oElm.currentStyle["opacity"];
}

alert ( strValue );

A: The problem is, that element.style.opacity only stores values, that are set inside the element's style attribute. If you want to access style values, that come from other stylesheets, take a look at quirksmode.
Cheers,

A: I suggest you take a look at jQuery and some of the posts at Learning jQuery, it will make doing things like this very easy.

A: Opacity should be a number rather than a boolean. Is it working in any other browseR?

A: this link help
http://www.quirksmode.org/js/opacity.html
function setOpacity(value) {
    testObj.style.opacity = value/10;
    testObj.style.filter = 'alpha(opacity=' + value*10 + ')';
}

opacity is for Mozilla and Safari, filter for Explorer. value ranges from 0 to 10.


Q: Keep AVAudioPlayer sound in the memory I use AVAudioPlayer to play a click sound if the user taps on a button.
Because there is a delay between the tap and the sound, I play the sound once in viewDidAppear with volume = 0
I found that if the user taps on the button within a time period the sound plays immediately, but after a certain time there is a delay between the tap and the sound in this case also.
It seems like in the first case the sound comes from cache of the initial play, and in the second case the app has to load the sound again.
Therefore now I play the sound every 2 seconds with volume = 0 and when the user actually taps on the button the sound comes right away.
My question is there a better approach for this?
My goal would be to keep the sound in cache within the whole lifetime of the app.
Thank you,

A: If you save the pointer to AVAudioPlayer then your sound remains in memory and no other lag will occur.
First delay is caused by sound loading, so your 1st playback in viewDidAppear is right.

A: To avoid audio lag, use the .prepareToPlay() method of AVAudioPlayer.
Apple's Documentation on Prepare To Play

Calling this method preloads buffers and acquires the audio hardware
  needed for playback, which minimizes the lag between calling the
  play() method and the start of sound output.

If player is declared as an AVAudioPlayer then player.prepareToPlay() can be called to avoid the audio lag. Example code:
struct AudioPlayerManager {

    var player: AVAudioPlayer? = AVAudioPlayer()

    mutating func setupPlayer(soundName: String, soundType: SoundType) {

    if let soundURL = Bundle.main.url(forResource: soundName, withExtension: soundType.rawValue) {
        do {
            player = try AVAudioPlayer(contentsOf: soundURL)
            player?.prepareToPlay()
        }
        catch  {
            print(error.localizedDescription)
        }
    } else {
        print("Sound file was missing, name is misspelled or wrong case.")
    }
}

Then play() can be called with minimal lag:
player?.play()


Q: Changing the first row of a matrix; subsequent rows depend on the first row I have generated a matrix of zeros.
tab=Table[0,{i,10},{j,10}]

tab is defined such that given tab[[1]] (the first row of tab), I am doing For[i=2,i<=10,i++,tab=ReplacePart[tab,i->2*tab[[i-1]]]] so that given the first row, all the other rows follow.
Now I have generated another table, tab1 which is a 3x10 matrix of
{{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
 {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}}

The problem is to replace the first row of tab with the first row of tab1 {1,....,1} and to calculate tab. Then doing the same with replacing the first row of tab with the second row of tab1 and then the third row of tab1. In each realization of the matrix of tab, I want to calculate the sum of each column and store the result. So in the end, I will have a 3x10 matrix of the sums of columns from each realization. [I am presenting this as a relatively simple problem as in the real problem I am trying to solve, there are about 50000 realizations of the first row of the matrix of dimensions 50x100].
I have tried
For[j = 1, j <= 3, j++, ps[j] = tab1[[j]]];
For[tab[[1]] = ps[j]; i = 2, i <= 10, i++,
 tab = ReplacePart[tab, i -> 2*tab[[i - 1]]]];

but its not working. I would appreciate any help.
Thank you.

A: The final result can be obtained with
Total /@ (NestList[2 # &, #, 9] & /@ tab1)

or
Plus @@@ (NestList[2 # &, #, 9] & /@ tab1)

or
Plus @@ NestList[2 # &, tab1, 9]

where 9 is the number of rows of tab minus 1. With the given value for tab1, one gets
(* {{1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023},
    {2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046},
    {3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069}} *)

Update
Per OP's comment

the real problem that I am trying to solve [...] is (tab, i -> 2*tab[[i - 1]]] + 4 * rnorm[[i]]) where rnorm is a matrix of random normal variables

This can be achieved for instance with
First@*Total /@ (NestList[{2 #[[1]] + 4 rnorm[[#[[2]]]], #[[2]] + 1} &,
          {#, 2}, 9] & /@ tab1)

or
First@*Plus @@@ (NestList[{2 #[[1]] + 4 rnorm[[#[[2]]]], #[[2]] + 1} &,
          {#, 2}, 9] & /@ tab1)

or
rnorm2 = ConstantArray[#, 3] & /@ rnorm;
First@*Plus @@ NestList[{2 #[[1]] + 4 rnorm2[[#[[2]]]], #[[2]] + 1} &,
          {tab1, 2}, 9]

where the parameter 3 used for rnorm2 is the number of rows of tab1.

A: As I understand your question, the computation can be done for one column and then rows of length 10 can be generated from that column. If that is correct, then this may be what you looking for.
Module[{t = {1, 2, 3}, sums},
  sums = Table[Total @ Thread[Times[t[[i]], {1, 2, 4}]], {i, Length @ t}];
  ConstantArray[#, 10]& /@ sums]

{{7, 7, 7, 7, 7, 7, 7, 7, 7, 7},
 {14, 14, 14, 14, 14, 14, 14, 14, 14, 14},
 {21, 21, 21, 21, 21, 21, 21, 21, 21, 21}}

A: Whenever a computation depends upon a previous computation it is a good idea to think Fold or FoldList.
For the simple case of multiplying the previous row by two NestList works fine (and Goldberg's approach is even better) but for more complicated functions I think there is a benefit to considering FoldList.
tab1 = {{1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
        {2, 2, 2, 2, 2, 2, 2, 2, 2, 2},
        {3, 3, 3, 3, 3, 3, 3, 3, 3, 3}};

The matrix generated by using tab1[[1]] as the input is
FoldList[2*#1 &, tab1[[1]], Range[9]]

which produces

and then one computes the total
Total@FoldList[2*#1 &, tab1[[1]], Range[9]]
(* {1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023} *)

To apply this to all of the rows in tab1 wrap the above step in Map using a Function to define the index into tab1.
Map[
 Function[tab1Index,
  Total@FoldList[2*#1 &, tab1[[tab1Index]],
    Range[Length[tab1[[1]]] - 1]]
  ], Range[Length[tab1]]
 ]

resulting in
{{1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023, 1023},
 {2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046, 2046},
 {3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069, 3069}}

This should be fast for 50000 realizations on a 50x100 matrix.


Q: Automatic Link conversion with preg_replace - but without last bracket, period and comma The php q2a software www.question2answer.org parses links in text with the following preg_replace:
function qa_html_convert_urls($html, $newwindow=false) {
    return substr(preg_replace('/([^A-Za-z0-9])((http|https|ftp):\/\/([^\s&<>"\'\.])+\.([^\s&<>"\']|&)+)/i', '\1\2', ' '.$html.' '), 1, -1);
}

The only problem is that text such as "look here http://www.mydomain.com/." will link like https://www.mydomain.com/. or "look here (http://www.mydomain.com/)" will link http://www.mydomain.com/) the last char (period, comma or bracket) gets part of the link. And breaks the correct link.
Could you provide a solution for this issue?
Thanks a lot :)

A: The working solution is:
function qa_html_convert_urls($html, $newwindow=false) {
    return substr(preg_replace('/([^A-Za-z0-9])((http|https|ftp):\/\/([^\s&<>\(\)\[\]"\'\.])+\.([^\s&<>\(\)\[\]"\']|&)+)/i', '\1\2', ' '.$html.' '), 1, -1);`
}

Thanks and credits to gidgreen.


Q: apply a jQuery function on a CkEditor I have a textarea in my html file, and I need to send the data in the textarea to the database. However, the textarea send the data without the enter spaces. so a data like this:
Shortly after reading a few books on web design, I was hooked. I wanted to know everything and anything about it. I was designing websites any chance I could.

I spent almost all of my savings buying more books on different programming languages and other nerdy computer gear.

would be like this in the database.
Shortly after reading a few books on web design, I was hooked. I wanted to know everything and anything about it. I was designing websites any chance I could. I spent almost all of my savings buying more books on different programming languages and other nerdy computer gear.

So I decided to change the textarea to a ckeditor to send the data as html. But the problem now that I have a jQuery method on the textarea, and now it won't work.
HTML :

<textarea maxlength="5000" id="blah" cols="100" rows="20" name="essay_content" class="ckeditor" onkeyup="words();">
</textarea>

jQuery:
function words(content)
{
    var f = $("#blah").val()
    $('#othman').load('wordcount.php?content='+ encodeURIComponent(f));

}

now it won't work with me because the text area is a CkEditor ... any suggestions ?

A: This should get you the contents of the CkEditor textarea:
function words(content)
{
    var f = CKEDITOR.instances.blah.getData();
    $('#othman').load('wordcount.php?content='+ encodeURIComponent(f));
}

But,I don't think the onkeyup will work, because CkEditor replaces the textarea. You would need to create a plugin for CkEditor to catch the key up trigger within the editor instance.

A: I have used nlbr and everything works.


Q: getting response from Facebook is getting timed out Hi I am using a facebook posts feeding application which will read all the new posts from my facebook page and will save to my sharepoint list. Earlier, i.e, before June it has worked properly it feeds all the posts from fabebook to my Share point list. But nowadays its throws an error while getting response from the Facebook authorize url. I don't know what went wrong. Please help me if you guys have any suggestion to resolve this issue. I am appending my code part below.
private void btnSendToList_Click(object sender, EventArgs e)
    {
        try
        {
            if (ConfigurationSettings.AppSettings["fbClientID"] != null)
                strClientID = ConfigurationSettings.AppSettings["fbClientID"];

            if (ConfigurationSettings.AppSettings["fbRedirectURL"] != null)
                strURL = ConfigurationSettings.AppSettings["fbRedirectURL"];

            if (ConfigurationSettings.AppSettings["fbCltSecret"] != null)
                strCltSecret = ConfigurationSettings.AppSettings["fbCltSecret"];

            if (ConfigurationSettings.AppSettings["fbUserId"] != null)
                strUserId = ConfigurationSettings.AppSettings["fbUserId"];

            if (ConfigurationSettings.AppSettings["SPSiteURL"] != null)
                strSiteURL = ConfigurationSettings.AppSettings["SPSiteURL"];

            CookieCollection cookies = new CookieCollection();
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.facebook.com");
            request.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
            request.CookieContainer = new CookieContainer();
            request.CookieContainer.Add(cookies);
            //Get the response from the server and save the cookies from the first request..
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            cookies = response.Cookies;

            string getUrl = "https://www.facebook.com/login.php?login_attempt=1";
            string postData = String.Format("email={0}&pass={1}", "testuser@gmail.com", "test123$"); // Masking credentials.
            getRequest = (HttpWebRequest)WebRequest.Create(getUrl);
            getRequest.CookieContainer = request.CookieContainer;
            getRequest.CookieContainer.Add(cookies);
            getRequest.Method = WebRequestMethods.Http.Post;
            getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
            getRequest.AllowWriteStreamBuffering = true;
            getRequest.ProtocolVersion = HttpVersion.Version11;
            getRequest.AllowAutoRedirect = true;
            getRequest.ContentType = "application/x-www-form-urlencoded";

            byteArray = Encoding.ASCII.GetBytes(postData);
            getRequest.ContentLength = byteArray.Length;
            newStream = getRequest.GetRequestStream(); //open connection
            newStream.Write(byteArray, 0, byteArray.Length); // Send the data.

            getResponse = (HttpWebResponse)getRequest.GetResponse();

            getRequest = (HttpWebRequest)WebRequest.Create(string.Format("https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}", strClientID, "http://www.facebook.com/connect/login_success.html"));
            getRequest.Method = WebRequestMethods.Http.Get;
            getRequest.CookieContainer = request.CookieContainer;
            getRequest.CookieContainer.Add(cookies);
            getRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.121 Safari/535.2";
            getRequest.AllowWriteStreamBuffering = true;
            //getRequest.ProtocolVersion = HttpVersion.Version11;
            getRequest.AllowAutoRedirect = true;
            getRequest.ContentType = "application/x-www-form-urlencoded";

            getResponse = (HttpWebResponse)getRequest.GetResponse();

The above line throws WebExceptopn which is teeling like Process has timed out.

            strAccessToken = getResponse.ResponseUri.Query;
            strAccessToken = strAccessToken.Replace("#_=_", "");
            strAccessToken = strAccessToken.Replace("?code=", "");

            newStream.Close();

            if (!string.IsNullOrEmpty(strAccessToken))
                strCode = strAccessToken;

            if (!string.IsNullOrEmpty(strCode) && !string.IsNullOrEmpty(strClientID) &&
                    !string.IsNullOrEmpty(strURL) && !string.IsNullOrEmpty(strCltSecret) &&
                            !string.IsNullOrEmpty(strUserId))
            {
                SaveToList();
            }
        }
        catch (Exception ex)
        {
            LogError(ex);
        }
    }

A: Hi Finally i got the solution.
Here i am using getResponse = (HttpWebResponse)getRequest.GetResponse();
The problem is we can use only one HttpWebResponse at a time. In my case i am using the same object in two times without any disposing and closing. That's make me the error.
So I updated my code like this.
 byteArray = Encoding.ASCII.GetBytes(postData);
        getRequest.ContentLength = byteArray.Length;
        newStream = getRequest.GetRequestStream(); //open connection
        newStream.Write(byteArray, 0, byteArray.Length); // Send the data.

        getResponse = (HttpWebResponse)getRequest.GetResponse();
        getresponse.Close();

This solved my error. Thanks


Q: Can I create a mutable slice &mut [u8] from a single byte (u8)? Sometimes I want to read a single byte from a std::io::Reader. If I try to do this:
use std::io::{self, Read};

fn main() {
    let mut byte: u8 = 0;
    io::stdin().read(&mut byte).unwrap();
    println!("byte: {}", byte);
}

I get the following error (which is clear, as byte is not a slice):
error[E0308]: mismatched types
 --> src/main.rs:6:22
  |
6 |     io::stdin().read(&mut byte).unwrap();
  |                      ^^^^^^^^^ expected slice, found u8
  |
  = note: expected type `&mut [u8]`
             found type `&mut u8`

Is there a way I can keep byte as a simple u8 and just take a slice of it, which I can then pass to read()? The obvious way to make this code work is to use an array of length 1:
use std::io::{self, Read};

fn main() {
    let mut byte: [u8; 1] = [0];
    io::stdin().read(&mut byte).unwrap();
    println!("byte: {}", byte[0]);
}

But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8 rather than a [u8; 1] that I have to index into.
If it's not possible to create a slice from the simple u8 that's okay, but I don't know if it's possible or not and would like to know.

A: To answer your actual question: no, you can’t do that, and there’s almost never any need to. Even if you couldn’t get an iterable out of a readable, you could just put byte[0] into another variable and use that.
Instead, you can use the Bytes iterator:
let byte: u8 = io::stdin().bytes().next().unwrap();

A: Rust 1.28+
slice::from_mut is back and it's stable!
use std::{
    io::{self, Read},
    slice,
};

fn main() {
    let mut byte = 0;
    let bytes_read = io::stdin().read(slice::from_mut(&mut byte)).unwrap();
    if bytes_read == 1 {
        println!("read byte: {:?}", byte);
    }
}

Rust 1.0+

But that's kinda weird feeling throughout the rest of the code, and it would be more natural to use a single u8 rather than a [u8; 1] that I have to index into.

Creating an array of length 1 would be the most natural way of doing it:
use std::io::{self, Read};

fn main() {
    let mut bytes = [0];
    let bytes_read = io::stdin().read(&mut bytes).unwrap();
    let valid_bytes = &bytes[..bytes_read];
    println!("read bytes: {:?}", valid_bytes);
}

However, it is possible to unsafely create a slice from a reference to a single value:
use std::io::{self, Read};
use std::slice;

fn mut_ref_slice<T>(x: &mut T) -> &mut [T] {
    // It's important to wrap this in its own function because this is
    // the only way to tell the borrow checker what the resulting slice
    // will refer to. Otherwise you might get mutable aliasing or a
    // dangling pointer which is what Rust is trying to avoid.
    unsafe { slice::from_raw_parts_mut(x, 1) }
}

fn main() {
    let mut byte = 0u8;
    let bytes_read = io::stdin().read(mut_ref_slice(&mut byte)).unwrap();
    if bytes_read != 0 {
        println!("byte: {}", byte);
    }
}

Remember that a slice is basically two things: a pointer to an area of memory and a length. With a slice of length one, you simply need to add a length to a mutable reference and bam! you got yourself a slice.
Earlier versions of Rust had the ref_slice and mut_ref_slice functions. They were removed because their utility was not yet proven (this isn't a common problem), but they were safe to call. The functions were moved to the ref_slice crate, so if you'd like to continue using them, that's one possibility.


Q: Recording from tv tuner/webcam with gstreamer and audio/video going out of sync I have a TV tuner card that shows up as /dev/video1. I am trying to digitize some old VHS tapes. The TV tuner doesn't do audio, I have a wire connected to my microphone in.
This is the gstreamer pipeline I'm using to capture video & audio and save it to a file. I'm using motion jpeg because I don't want it to drop frames and lose content. I'll re-encode it better later.
gst-launch-0.10 v4l2src device=/dev/video1 ! \
    queue ! \
    video/x-raw-yuv,width=640,height=480 ! \
    ffmpegcolorspace ! \
    jpegenc ! \
    avimux name=mux ! \
    filesink location=output.avi \
   pulsesrc ! \
    queue ! \
    audioconvert ! \
    audio/x-raw-int,rate=44100,channels=2 ! \
    mux.

This all works well and good. I have files that play that have video and audio. However sometimes when playing the output files, the audio & video goes out of sync. It happens at the same place in the video, on numerous different media players (totem, mplayer). So I think this is a problem in how I'm saving and recording the file.
Is there anything I can do to the pipeline to make it less likely to suffer from audio/video sync problems? I'm a bit of a newbie to gstreamer and video/audio codecs, so I might be doing something stupid here (please point out!). Is there any video/audio/muxer codec that would be better?

A: Try adding an audiorate element in the audio branch, and a videorate element in the video branch, to see if that makes a difference, or try a different muxer, like qtmux or matroskamux.


Q: cordova-plugin-file on IONIC2 with externalDataDirectory the file is not visible with a file manager I try to write a log file using IONIC2, all seems to work, not error, with IONIC2 the file exist the directory is created, but I can not see the file with a file explorer. See my source there :
            File.checkDir(cordova.file.externalDataDirectory, 'mydir')
                .then(_ => {
                    trace.info('yay')
                })
                .catch(err => {
                    trace.error('BackgroundGeolocationService','constructor',`boooh`);
                    File.createDir(cordova.file.externalDataDirectory, "mydir", false)
                        .then(function (success) {
                            // success
                            trace.info('create mydir success');
                        }, function (error) {
                            // error
                            trace.error('BackgroundGeolocationService','constructor',`unable to create mydir`);
                        }.bind(this));
                });

            File.createFile(cordova.file.externalDataDirectory, "new_file.txt", true)
                .then(function (success) {
                    // success
                    trace.info('write file success');
                }, function (error) {
                    // error
                    trace.error('BackgroundGeolocationService','constructor',`error:${error}`)
                });

A: Your source checks for a folder called myDir being created, but when you create new_file.txt, it isn't creating it in the myDir folder, it looks to be creating it in the externalDataDirectory folder.
So check the externalDataDirectory folder rather than your myDir folder, and you'll probably see your file there.


Q: docker images are stored in root user thus consuming my disk space Hi my server is configured such that the free space for root user in it is very less. However the user created(suppose user1) has lot of space.
The docker images which are getting created by docker are saved in the root user thus consuming space and making my jobs to fail.How can i make docker images use user1?
Do i need to restart the registry in anyway?
I am unable to understand how to use docker groups and -G tag for this purpose.
Can i mention something in dockerfile and make images up using user1 ?

A: Checkout the -g option on the daemon process. Can be used to locate the docker home on an alternative disk volume.
Explained in the following documentation links:

*

*http://docs.docker.com/reference/commandline/cli/#daemon

*http://docs.docker.com/articles/systemd/#custom-docker-daemon-options

A: Linked /var to /user1/var.
The mounts and the volumes stay the same.
I did this:
`telinit 1
cp -pR /var /user1/var
mv /var /var.old
ln -s /user1/var /var
telinit 2`


Q: Facebook Graph API - IG Media Getting Metadata Issue I have some issues about IGMedia getting metadatas. I followed the instructions in documentations. But I am getting an error like "400" "Bad Request". Before try to getting IGMedia metadatas , I took the recent media datas. But ı dont get an error. Its worked perfectly. So ı need to help about why ı am getting that error? Because of permissions or another things? Please help me. Here is the code. And ı get the error, line of // Get IGMedia Metadata
        string access_token = "ACCESS_TOKEN";
        var values = new Dictionary<string, string>
      {
         { "access_token", access_token},
         { "scope","instagram_basic,manage_pages"},
         { "redirect_uri","" },
      };

        var content = new FormUrlEncodedContent(values);
        var response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login", content);
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Auth failed");
        var responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        dynamic data = Json.Decode(responseString.Result);

        Console.WriteLine("Code : " + data.code);
        Console.WriteLine("User Code : " + data.user_code);
        Console.WriteLine("Verification Uri : " + data.verification_uri);
        Console.WriteLine("Expires in : " + data.expires_in + " seconds");
        Console.WriteLine("Interval : " + data.interval);

        int interval = Convert.ToInt32(data.interval) * 1000;
        int expires_in = Convert.ToInt32(data.expires_in);
        string longCode = data.code;

        bool loggedIn = false;
        DateTime dtCodeGenerated = DateTime.Now;

        string TokenCall = "";
        int TokenExpireTime;

        while (!loggedIn)
        {
            Thread.Sleep(interval);

            // Poll Login Status
            values = new Dictionary<string, string>
      {
         { "access_token", access_token },
         { "code",longCode}
      };

            content = new FormUrlEncodedContent(values);
            response = new HttpClient().PostAsync("https://graph.facebook.com/v2.6/device/login_status", content);
            response.Wait();
            if (!response.Result.IsSuccessStatusCode)
                throw new Exception("Login Status failed");
            responseString = response.Result.Content.ReadAsStringAsync();
            responseString.Wait();

            data = Json.Decode(responseString.Result);

            if (data.access_token != null)
            {
                loggedIn = true;

                TokenCall = data.access_token;
                TokenExpireTime = Convert.ToInt32(data.expires_in);
                break;
            }
            else
            {
                if (data.error != null)
                {
                    Console.WriteLine(data.error.error_user_title);
                }

            }

            Console.WriteLine(String.Format("Expires in : {0:000} seconds", (expires_in - (DateTime.Now - dtCodeGenerated).TotalSeconds)));

        }
        // Get Profile
        response = new HttpClient().GetAsync("https://graph.facebook.com/v2.3/me?fields=name,picture&access_token=" + TokenCall);
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Profile Get failed");
        responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        data = Json.Decode(responseString.Result);

        Console.WriteLine("Name : " + data.name);
        Console.WriteLine("User picture : " + data.picture.data.url);
        Console.WriteLine("Id : " + data.id);

        string userID = data.id;

        // Get User's Pages

        response = new HttpClient().GetAsync("https://graph.facebook.com/v5.0/me/accounts?access_token=" + TokenCall);
        response.Wait();
        if (!response.Result.IsSuccessStatusCode)
            throw new Exception("Profile Get failed");
        responseString = response.Result.Content.ReadAsStringAsync();
        responseString.Wait();

        data = Json.Decode(responseString.Result);

        string selectedBusinessAccountID = "";
        if (data.data.Length > 0)
        {
            for (int i = 0; i < data.data.Length; i++)
            {
                Console.WriteLine("PAGE " + i.ToString());

                Console.WriteLine("Name : " + data.data[i].name);
                Console.WriteLine("Category : " + data.data[i].category);
                Console.WriteLine("Id : " + data.data[i].id);

                Console.WriteLine();
                Console.WriteLine();

                string pageID = data.data[i].id;

                // get Instagram Business Account
                response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/v5.0/{0}?fields=instagram_business_account&access_token={1}", pageID, TokenCall));
                response.Wait();
                if (!response.Result.IsSuccessStatusCode)
                    throw new Exception("Profile Get failed");
                responseString = response.Result.Content.ReadAsStringAsync();
                responseString.Wait();

                dynamic data_instagram_business = Json.Decode(responseString.Result);

                if (data_instagram_business.instagram_business_account != null)
                {
                    selectedBusinessAccountID = data_instagram_business.instagram_business_account.id;
                    Console.WriteLine("selectedBusinessAccountID : " + selectedBusinessAccountID);

                    break;
                }
            }

            // Get Hashtag id
            response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/ig_hashtag_search?user_id={0}&q={2}&access_token={1}", selectedBusinessAccountID, TokenCall, "hisseliharikalar"));
            response.Wait();
            if (!response.Result.IsSuccessStatusCode)
                throw new Exception("Hashtag ID Failed");
            responseString = response.Result.Content.ReadAsStringAsync();
            responseString.Wait();

            data = Json.Decode(responseString.Result);
            string hashtagID = "";
            if (data.data.Length > 0)
            {
                for (int i = 0; i < data.data.Length; i++)
                {

                    Console.WriteLine("Id : " + data.data[i].id);
                    hashtagID = data.data[i].id;
                    Console.WriteLine();
                    Console.WriteLine();

                    break;
                }

            }

            // Get Medias of hashtag

            response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}/recent_media?user_id={1}&fields={3}&access_token={2}", hashtagID, selectedBusinessAccountID, TokenCall, "id,media_type,comments_count,like_count,media_url,caption,children"));
            response.Wait();
            if (!response.Result.IsSuccessStatusCode)
                throw new Exception("Hashtag Medias Failed");
            responseString = response.Result.Content.ReadAsStringAsync();
            responseString.Wait();

            data = Json.Decode(responseString.Result);

            if (data.data.Length > 0)
            {
                for (int i = 0; i < data.data.Length; i++)
                {

                    Console.WriteLine("Id : " + data.data[i].id);
                    Console.WriteLine("like_count : " + data.data[i].like_count);
                    Console.WriteLine("caption : " + data.data[i].caption);
                    Console.WriteLine("media_type : " + data.data[i].media_type);
                    Console.WriteLine("media_url : " + data.data[i].media_url);
                    if (data.data[i].media_url == null)
                    {
                        Console.WriteLine("children  : " + data.data[i].children);

                    }

                    Console.WriteLine();
                    Console.WriteLine();

                    **// Get IGMedia Metadata**

                    response = new HttpClient().GetAsync(String.Format("https://graph.facebook.com/{0}?fields={3}&access_token={2}", data.data[i].id, selectedBusinessAccountID, TokenCall, "id,like_count,caption,media_type,media_url,comments_count"));
                    response.Wait();
                    if (!response.Result.IsSuccessStatusCode)
                        throw new Exception("IGMedia metadata Failed");
                    responseString = response.Result.Content.ReadAsStringAsync();
                    responseString.Wait();

                    data = Json.Decode(responseString.Result);

                        Console.WriteLine("Id : " + data.data[i].id);
                        Console.WriteLine("like_count : " + data.data[i].like_count);
                        Console.WriteLine("caption : " + data.data[i].caption);
                        Console.WriteLine("media_type : " + data.data[i].media_type);
                        Console.WriteLine("media_url : " + data.data[i].media_url);
                        Console.WriteLine("comment_count : " + data.data[i].comments_count);

                        Console.WriteLine();
                        Console.WriteLine();

                }

            }

            //
        }

        //End
        Console.ReadKey();

    }

}

}


Q: How to install Oracle's exp / imp binaries I was browsing the net to find a solution, but I had no luck. :(
How can I install Oracle's imp / exp binaries to my CentOS box without installing an Oracle Server? I'm accessing an existing Oracle database on another machine, so I only need a client here.
I already installed sqlplus and its dependencies (oracle-instantclient11.2-basic-11.2.0.3.0-1.x86_64.rpm, and oracle-instantclient11.2-odbc-11.2.0.3.0-1.x86_64.rpm), but that didn't provide those tools.
Do I really need to fully install Oracle?
My aim is to suck a database dump from the Oracle to my CentOS box. If there is another way to do this without using exp I wouldn't feel bad about NOT using it, but it seems to me there is no alternative.

A: To get the export (exp) and import (imp) binaries, install the full Oracle Client, instead of the Instant Client or the full RDBMS.  The 11gR2 Client is actually the 4th file of a 7 file set for the full RDBMS.  The latest version is 11.2.0.3.0 (659,229,728 bytes, released in Q4 2011 - technically called a "patch set" but it is a complete install).  It is not available for public download. (Only the obsolete 11.2.0.1.0 for Linux x86-64 is available publicly).
To download the full Oracle Client, follow these steps:

*

*Log in to My Oracle Support (MOS), formerly known as metalink.

*Click the "Patches & Updates" menu at the top.

*In the Patch Search section, click the Search tab.

*Enter 13390677 in the "Patch Name or Number" field. (13390677 is version 11.2.0.4.0)

*Also select a "Platform".  (e.g., "Linux x86-64")

*Click Search.

*In the search results, click on the patch number to display the details or click Download - assuming your MOS account has been given download privileges.
The file name for the client-only download is "p13390677_112040_platform_4of7.zip" (where platform is "Linux-x86-64" for example).
NOTE: exports/dumps are not true backups.  They are only logical copies of the database.  The meta-data and indexes get re-created during import and so won't be byte-for-byte identical to the source database.

A: You do NOT need to fully install an Oracle instance.

*

*Download the Oracle Client as mentioned in George3's answer

*Install - when it asks you to select either Instant Client, Runtime, Administrator, or Custom <-- pick Custom.

*Select Database Utilities. This contains the exp/imp files

A: Instant client tools provides exp / imp utilities since v12.2.0.1.0. Unrestricted download is available:
https://www.oracle.com/technetwork/database/database-technologies/instant-client/downloads/index.html

A: Here is how I did it. Had to hack it.
a) Download Oracle 11.2 XE for Linux 64 in your $HOME
b) Unzip the zip file you get
c) Unpack the content of the rpm file without installing it (we don't need the Oracle RDBMS to be running on the server)
    mkdir ~/Oracle11XE-binaries
    cd ~/Oracle11XE-binaries

    # extract all the binaries from the RPM (rather than installing the RPM)
    rpm2cpio ../Disk1/oracle-xe-11.2.0-1.0.x86_64.rpm  | cpio -idmv

    sudo mkdir /opt/oracle
    sudo mv u01/app/oracle/product /opt/oracle

    # clean up downloaded and extracted files (they are BIG)
    cd
    rm -rf Disk1 oracle-xe-11.2.0-1.0.x86_64.rpm.zip

    echo 'export ORACLE_HOME=/opt/oracle/product/11.2.0/xe
    export PATH=$PATH:$ORACLE_HOME/bin
    export LD_LIBRARY_PATH=$ORACLE_HOME/lib
    export TNS_ADMIN=$ORACLE_HOME/network/admin' | sudo tee /etc/profile.d/oracle.sh

    # source it so it takes effect in the current session
    . /etc/profile.d/oracle.sh

    # now you can run imp and exp
    $ imp

    Import: Release 11.2.0.2.0 - Production on Mon Aug 4 14:39:39 2014

    Copyright (c) 1982, 2009, Oracle and/or its affiliates.  All rights reserved.

Username:

A: You want to import a database without DBMS system in place, sorry, but this is impossible in every definition of the word...
So, yes, you have to do full Oracle install before imp and exp will work.
Also, in the future I'd suggest using expdp and impdp instead.


Q: Android bitmap - out of memory I have a problem with a function that I implemented. On some phones I get a out of memory error.
private Bitmap getIconMarkerOfPlayer(Player p) {
    Drawable drawable = getIconOfPlayer(p);
    Bitmap img = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_4444);
    Canvas canvas = new Canvas(img);
    drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
    drawable.draw(canvas);

    final float scale = this.getResources().getDisplayMetrics().density;
    int heigthPixels = (int) (24 * scale + 0.5f);
    int widthPixels = (int) (24 * scale + 0.5f);
    return Bitmap.createScaledBitmap(img, widthPixels, heigthPixels, false);
}

The getIconMarkerOfPlayer(Player p) function gives a "programmed" drawable depending on the player's status (dead, alive, offline, ...) and its color. Each player has a unique color assigned to it in the early games.
How can I resize my bitmap from a Drawable object without having a out of memory error?

A: I suggest you to use some ImageLibraries to load Bitmaps efficiently.
Some of them are Fresco, Glide, Piccasio.
I suggest you to go with Glide. Have a look at it here


Q: Should I use Boost.GIL or is it dead? I actually like the clean approach of Boost.GIL, standardized libraries are cool and Adobe certainly put some thought in it but when comparing to libs such as OpenCV its feature set is marginal. Do you use GIL and for what purposes?

A: Boost.GIL is not dead. There is a few maintainers interested in keeping the project up to date, fixing bugs, helping contributors to bring new features, etc.
Boost.GIL is preparing for refreshing release as part of the upcoming Boost 1.68, including new I/O implementation accepted to Boost.GIL during the official Boost review a longer while ago.
Stay tuned and if you have any specific questions, feel free to post to the official boost-gil mailing list

A: Boost is a widely accepted set of libraries, but it's not in the C++ standard. So don't feel that you've violated the ANSI/ISO code of conduct by using something that better suits your needs.

A: Do not use boost gil, recently I tried to use it to do a "complex" task of reading a png file, but for that it requires installing a bunch of libraries that have no install documentation for Windows, and to make matters worse gil documentation suggest the following regarding libpng and libjpeg(in year 2020):

The user has to make sure this library is properly installed. I
  strongly recommend the user to build the library yourself. It could
  potentially save you a lot of trouble.


Q: What's the difference between a certstore and a keystore? I'm specifically using openssl in RHEL.
What's the difference between a certstore and a keystore?

A: These are exactly the same thing.  However, it is keytool terminology, not openssl terminology.  Either way, it stores certificates (such as a list of trusted CA certificates, or your certificates), and private keys as applicable.

A: A key store stores keys which are used for signing and a cert store stores signed certs?


Q: derivative of a diagonal matrix
Given the weight graph $G(V,E,w)$ where $w_{}$ is a function which assigns a weight to an edge in graph G, we define the adjacency matrix $A$ by
  $$A_{ij}=\begin{cases} w_{ij},&\text{if }(i,j) \in E, \\ 0 & \text{otherwise}.\end{cases}$$
  The degree matrix of a weighted graph is a diagonal matrix $D$ such that
  $$D_{ii}=\sum_j A_{ij}.$$
  Which is the derivative of $P=D^{-1}$ with respect to $A$?
  $$\frac{\partial P}{{\partial\ A}}=\frac{\partial(D^{-1})}{\partial\ A}$$

I was wondering if any one could help me to find out the answer.

A: Let $e$ be the vector whose components are all ones.
Then
$$\eqalign{
 b &= Ae \cr
 D &= \operatorname{Diag}(b) \cr
 P &= D^{-1} \cr
dP &= -P\,dD\,P \cr
}$$
Those matrices are all diagonal, so apply the diag() operator (which is the reverse of the Diag() operator) to obtain
$$\eqalign{
dp &= -P^2\,db \cr
   &= -P^2\,dA\,e \cr
}$$
Now vectorize both sides
$$\eqalign{
dp &= -\operatorname{vec}(P^2\,dA\,e) \cr
   &= -(e^T\otimes P^2)\,\operatorname{vec}(dA) \cr
   &= -(e^T\otimes P^2)\,da \cr\cr
\frac{\partial p}{\partial a} &= -\,e^T\otimes P^2 \cr\cr
}$$
If you don't wish to vectorize, then you must use higher-order tensors to express the result.
Let $T$ be a 3rd-order tensor, and $F$ a 4th-order tensor, with components given by
$$\eqalign{T_{ijk} &= \begin{cases} 1 &\text{if }(i=j=k) \\ 0 & \text{otherwise}\end{cases}\cr
F_{ijkm} &= \delta_{ik}\,\delta_{jm} \cr
}$$
Then picking up the previous thread just before vectorization
$$\eqalign{
 dp &= -P^2\,dA\,e \cr
\cr
 dP &= T\,dp \cr &= -T\,P^2\,dA\,e \cr
    &= -T\,P^2\,F\,e^T:dA \cr
\cr
\frac{\partial P}{\partial A} &= -T\,P^2\,F\,e^T \cr
}$$