text:
Q: php-fpm for Windows? The PHP-FPM's homepage http://php-fpm.org/ states that it is part of PHP since PHP 5.3.3. Now, I was wondering, when I download the newest PHP binaries from php.net, there is no php-fpm in it. How do I get it? Is it even available for Windows?

A: Starting PHP v5.3.3, FPM Server-API [SAPI] support has been integrated into core PHP. This means, you can take PHP's source codes and compile and build them with FPM-SAPI [using --enable-fpm configuration parameter] support, instead of let's say Apache SAPI [--enable-apx2]. As shown in PHP-Wiki you can build PHP almost the same way you do in *nix systems - that is, configuration-wise. I would suggest you learn the ins and outs of building PHP in *nix systems first, and even try to do it yourself [usual configure, make and make install pattern], and then try to utilize the experience gained from it to build on Windows environment.
In addition to --enable-fpm configuration parameter, there are two additional parameters as well: --with-fpm-user=USERNAME_HERE and --with-fpm-group=USERGROUPNAME_HERE. These two work in *nix environment, but may not be available in Windows.
Overall, I am pretty sure you can build your own PHP-FPM server app on Windows using Visual Studio IDE. There are no official PHP-FPM builds as of the date of this writing.
EDIT 1: Ok, guess I might be wrong re the possibility of building PHP-FPM on Windows, since this SAPI uses libevent component from *nix environment. Guess you will have to stick with Cygwin-bundled installation after all.

A: Here how to setup php-fpm on Windows:

*

*Download the .zip file from http://windows.php.net/download/.  The .zip file should be VC9 which has the FastCGI file (php-cgi.exe).  Don't download VC6, and don't download the .msi file because it requires that you have IIS setup already in order to install php-fpm.  The zip file contains the php-cgi.exe which is what you need for php-fpm.  I downloaded a slightly older version, php-5.3.10-Win32-VC9-x86.zip, from here http://windows.php.net/downloads/releases/archives/ because I wanted to match the version running on my production server.

*Unzip the file, e.g. unzip into C:\php-5.3.10-Win32-VC9-x86

*Edit the php.ini file as needed.  What I did:
# nginx security setting
cgi.fix_pathinfo=0

extension_dir = "C:\php-5.3.10-Win32-VC9-x86\ext"

enable the following modules by uncommenting them:
extension=php_curl.dll
extension=php_mbstring.dll
extension=php_mysqli.dll

*Create a .bat file somewhere, e.g. start-php-fcgi.bat in webserver directory or in the PHP directory:
@ECHO OFF
ECHO Starting PHP FastCGI...
set PATH=C:\php-5.3.10-Win32-VC9-x86;%PATH%
C:\php-5.3.10-Win32-VC9-x86\php-cgi.exe -b 127.0.0.1:9123 -c C:\php-5.3.10-Win32-VC9-x86\php.ini

*Double click the .bat file to start php-fpm.  A window will popup and stay open while its running.  Its kind of annoying, but just haven't looked into setting it up as service yet.

*Configure your webserver. If you wish to use it with nginx, here a config sample for 127.0.0.1:9123:
location ~ \.php$ {
    fastcgi_pass    127.0.0.1:9123;
    fastcgi_index   index.php;
    fastcgi_param   SCRIPT_FILENAME  $document_root$fastcgi_script_name;
    include         fastcgi_params;
}

A: PHP-FPM is only available to linux as of now. There are some sites that provides a tutorial on how to get php-fpm to run on windows, under cygwin. You can try those guides.

A: On Windows, when you run PHP with IIS and install the "PHP FastCGI" module, you get similar functionality to what is explained about PHP-FPM. In other words, this is not the official PHP-FPM code base, but just similar functionality.
For one, IIS would spawn multiple php-cgi.exe processes (worker processes). And any PHP requests that come in will be handed down to a worker, IIS will dynamically spawn more workers depending on the server resources. These settings are configurable under the "Fast CGI" options for the server tree node on IIS.
That said, I believe performance-wise the php-cgi.exe is not on par with Apache servers.
You can view the installation procedure for IIS 7 here: https://learn.microsoft.com/en-us/iis/application-frameworks/install-and-configure-php-applications-on-iis/using-fastcgi-to-host-php-applications-on-iis

FastCGI addresses the performance issues that are inherent in CGI by providing a mechanism to reuse a single process over and over again for many requests. Additionally, FastCGI maintains compatibility with non-thread-safe libraries by providing a pool of reusable processes and ensuring that each process handles only one request at a time.

A: Old as this post is I have to weigh in here because what has been posted here is not PHP-FPM, it's running PHP using Fast-CGI.
Yes PHP-FPM stands for PHP-FastCGI Process Manager and so implements FastCGI but you are forgetting that FPM is much more than that as it contains process management features that are not managed by the webserver.
On *nix systems PHP-FPM has a separate process that manages the PHP child processes and has a detailed configuration to specify how these processes are managed. For details on these features read here
Launching a CGI process on windows is not the same thing. It does not spaw worker processes or dynamically scale them or allow multi-threading.
There is no PHP-FPM for windows yet.
http://php.net/manual/en/install.fpm.php#121725
However as suggested, you may launch a CGI process if you wish.

A: Alan's answer is a great start. However, for Apache 2.4 and later you do not need to run PHP-FPM as a separate service, you can use mod_fcgid to handle everything within Apache.
Here is an example configuration:
LoadModule fcgid_module modules/mod_fcgid.so

FcgidInitialEnv PHPRC "c:/php"
FcgidInitialEnv PATH "c:/php;C:/WINDOWS/system32;C:/WINDOWS;C:/WINDOWS/System32/Wbem;"
FcgidInitialEnv SystemRoot "C:/Windows"
FcgidInitialEnv SystemDrive "C:"
FcgidInitialEnv TEMP "C:/WINDOWS/Temp"
FcgidInitialEnv TMP "C:/WINDOWS/Temp"
FcgidInitialEnv windir "C:/WINDOWS"
FcgidIOTimeout 64
FcgidConnectTimeout 16
FcgidMaxRequestsPerProcess 500

<Files ~ "\.php$">
  AddHandler fcgid-script .php
  FcgidWrapper c:/php/php-cgi.exe .php
</Files>

Note, this is based on a post in Apache Lounge. As helpful as it was, their version had quotes around c:/php/php-cgi.exe and if you do that it WILL NOT START php-cgi.exe, at least on Windows Server 2012, and you get HTTP 500. Took me a painful few days to figure that out.

A: PHP-FPM uses mainly *NIX specific features and is not likely to ever be ported to Windows. In the end there really isn't the motivation, especially when considering php-cgi was developed to allow Windows specific services to configure it as a fork pool. Yes, they have their differences, but not enough so to push the community into a complete rewrite of PHP-FPM.
Keep in mind that php-cgi on Windows is not just multiple instances of a CGI, but uses a Windows managed pool of forked FastCGI processors which use the same architecture of PHP-FPM. Multiple processes complete the module initialization of PHP, and from these multiple forks are maintained (and restarted when needed) to handle requests. php-cgi hasn't been a CGI since at least as early as PHP3.


text:
Q: newbie team city questions I am working with team city for CI and very happy with it. I use it to build from Tfs and build my code. As a newbie, I have some questions.

*

*I have a version info that my app uses for version number. How can I increment this on each build?

*I run code analysis and style cop analysis against my code. The settings file for these are located outside of the solution as they are shared across multiple solutions. How best can these be referenced for the builds? Can a directory where they reside be pulled with the source code to build?

*is there any way to generate a release notes document after each build pulled from tfs checkins?

A: *

*You can do this using TeamCity, here is the relevant question: Assembly Versioning with TeamCity

*Having not used TFS I can't say for sure how to do this, however from the look of things this guide's section(s) on "Workplace Mapping" seem to match up to how we pull files like this into our projects for TeamCity builds:
http://tfsguide.codeplex.com/wikipage?title=Chapter%206%20-%20Managing%20Source%20Control%20Dependencies%20in%20Visual%20Studio%20Team%20System&ProjectName=tfsguide

*Not out of the box, you will have to build this yourself using whatever script you prefer (MSBuild, Command line etc) and calling the relevant commands on TFS:
http://msdn.microsoft.com/en-us/library/z51z7zy0(v=vs.80).aspx

A: To answer question 2.
You could create a build configuration which publishes the settings files as artefacts. Each configuration which needs these settings files could then have both a snapshot dependency and an artefact dependency on this project. When setting the artefact dependency you want to select 'from the same build chain'.
For more information on dependencies, please see section 'Using Artifact and Snapshot Dependencies Together' in
http://blogs.jetbrains.com/teamcity/2012/04/24/teamcity-build-dependencies-2/

A: *

*You could use "Defining and Using Build Parameters in Build Configuration" to define environment variable current build id. Check available values in Predefined Build Parameters.

*You can use more than one VCS Roots, and checkout configs form shared root.

*Only using your script.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to extract video data liike images, duration and short preview from Uint8Array
*

*i'm still new in working with buffer array but i don't know why i'm thinking that i can get everything i need of that buffer array i'm using drag and drop to drag media from my pc to my custom media player after dropping it i got the video array buffer from ev.dataTransfer.files[0].arrayBuffer().then(buffer => console.log(buffer) then i get the Uint8Array of this buffer to be able to create Blob, object url for running this media file but my question is

*

*can i capture (image|frame) from this buffer array to use it as poster for this media

*can i use this buffer to create a quick video preview by drawing frames from this buffer to canvas element

*can i get something like video durtion from this array buffer to fix something like the duration errors when start playing a webm file i wanna know if there's a relation between the byteLength and the duration and also how can i draw the whole frames of the video from this buffer into canvas

*why when i'm trying to drawing image from this media by ctx.drawImage it's require user interaction and not drawing anything even when i change the video currentTime

*i know that i'm talking too much about how can i use this buffer but i haven't experience in working with buffering and the usage and how to manipulate it to the correct media type and display the buffer data so can anyone help me to answer this questions and guide me to how it's parsed and not working in any other thing except it's media type and how to parse and working with it and how browsers compiling it in a media that we can see and listen to it

*i searched a lot but i can't really understand it correctly and not found a lot of questions like what i'm asking about so there's no any useful answer i got so i hope someoone help me to understand better and go near to answer for those questions


text:
Q: Ical sync dynamically with google calender I have created iCal event by using iCalcreator. I want to make the google calendar so that it syncs automatically. I can create the .ical file that I will be importing or adding by URL. After I login into Gmail it is working. How can I make my events to automatically add to calendar by using the URL dynamically?

A: would the feature under

other calendars

    >import by URL

be what you are looking for?
provided your URL always points to the up to date calendar your google calendar will always be up to date (down to the synch frequency of google calendar) and you or anyone who you shared you google calendar url with will have access to it


text:
Q: I can't change Alpha property of a HUD in AndEngine. Is it possible? I'm trying to change alpha value of a HUD, but it is not changing. I've tried with AlphaModifier and changing with method .setAlpha(), but with no result. As i can see, a HUD entity does not have setBlendingFunction() method.
This is what i am now trying to do:
this.mHud = new HUD() {
        @Override
        protected void onManagedUpdate(float pSecondsElapsed) {
            super.onManagedUpdate(pSecondsElapsed);
            if(flag) {
                while (this.getAlpha() > 0) {
                    this.set(this.getAlpha() - (pSecondsElapsed / 1.5f));
                }
            } else {
                while (this.getAlpha() < 1) {
                    this.setAlpha(this.getAlpha() + (pSecondsElapsed / 1.5f));
                }
            }
        }
    };

The "flag" variable is initialized to false, and it is changed when a button is pressed.
I have tried this too:
 private static final IEntitiyModifier mToTransparentModifier = new AlphaModifier(1, 1, 0);
private static final IEntitiyModifier mToOpaqueModifier = new AlphaModifier(1, 0, 1);
this.mToTransparentModifier.setAutoUnregisterWhenFinished(true);
this.mToOpaqueModifier.setAutoUnregisterWhenFinished(true);

if(flag) {
    this.mHud.registerEntityModifier(this.mToTransparentModifier);
}else {
    this.mHud.registerEntityModifier(this.mToOpaqueModifier);
}

Any help would be appreciated. Thanks


text:
Q: Nessus Vulnerability 35291 Weak Hashing Algorithm :383 HP OpenView I got the Nessus Vulnerability 35291 Weak Hashing Algorithm on Port 383 - It's HP OpenView Agent - and I don't get any idea to close this.
I already updated the Agent to the newest version, which closed some vulnerabilities, but this is still open.
The Agent is Using SHA-1 and must be using at least SHA-2.
Has anyone solved this problem in past?
Thanks.


text:
Q: How do I access List items in order to change their values I want to dynamically fill a drop down list with text and values using a different table from my database.  I am using this code:
    protected void MachineGrid_RowEditing(object sender, GridViewEditEventArgs e)
    {
        int index = e.NewEditIndex;
        var ddl = MachineGrid.Rows[index].FindControl("OSDropDownList") as DropDownList;
    }

To access the drop down list.  I then have tried using both of the following code snippets to modify one of the List items, but both have given me the following error
"System.NullReferenceException: 'Object reference not set to an instance of an object."
Code 1:
        var li = ddl.SelectedItem;
        li.Text = "test";

Code 2:
        var li = ddl.Items[0];
        li.Text = "test";

Thanks!

A: Use something that will
fill your datatable via a query and provide a datasource to the dropdownlist.
yourDropDownList.DataSource= dt;
yourDropDownList.DataTextField="StringColumnName";
yourDropDownList.DataValueField="integerColumnName";
yourDropDownList.DataBind();


text:
Q: Caused by: com.android.tools.r8.utils.AbortException: Error: Program type already present: com.google.android.gms.security.ProviderInstaller Hello Fellows when i was trying to add the admob SDK i got this error :
Caused by: com.android.tools.r8.utils.AbortException: Error: Program type already present: com.google.android.gms.security.ProviderInstaller

*

*I've tried

*Invalidating cache

*cleaning and rebuilding

*using ./gradlew build --stacktrace --info command
but without success.
This is what im getting every time :
Caused by: com.android.tools.r8.utils.AbortException: Error: Program type already present: com.google.android.gms.security.ProviderInstaller

Here are my app build.grable :
    apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    buildToolsVersion '28.0.3'
    defaultConfig {
        applicationId "ar.rulosoft.mimanganu"
        versionCode 92
        versionName "1.92"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        minSdkVersion 15
    }
    signingConfigs {
        release {
            storeFile file("../mimanganu.jks")
            storePassword 'mimanganu'
            keyAlias 'mimanganu'
            keyPassword 'mimanganu'
        }
        debug {
            storeFile file("../mimanganu.jks")
            storePassword 'mimanganu'
            keyAlias 'mimanganu'
            keyPassword 'mimanganu'
        }
    }
    buildTypes {
        release {
            lintOptions {
                disable 'MissingTranslation'
                disable 'NewApi' //Avoid problems in Android Studio 2.4 preview 6
            }
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            signingConfig signingConfigs.release
        }
        debug {
            debuggable true
            signingConfig signingConfigs.debug
        }
    }
    compileOptions.encoding = 'UTF-8'
    flavorDimensions "builds"
    productFlavors {
        fdroid {
            signingConfig signingConfigs.release
            versionNameSuffix '-fdroid'
            dimension "builds"
        }
        github {
            signingConfig signingConfigs.release
             //removed to maintain updates as now are
            dimension "builds"
        }
    }
}

android.sourceSets {
    test {
        java.srcDirs += "$projectDir/src/testShare"
    }

    androidTest {
        java.srcDirs += "$projectDir/src/testShare"
    }
}

configurations.all {
    resolutionStrategy.force 'com.android.support:support-annotations:25.3.1'
}

dependencies {
    final ANDROID_SUPPORT = '28.0.0'
    implementation "com.android.support:support-v4:$ANDROID_SUPPORT"
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation "com.android.support:design:$ANDROID_SUPPORT"
    implementation "com.android.support:appcompat-v7:$ANDROID_SUPPORT"
    implementation "com.android.support:recyclerview-v7:$ANDROID_SUPPORT"
    implementation "com.android.support:preference-v7:$ANDROID_SUPPORT"
    api project(':imageviewtouchlibrary')
    implementation 'rapid.decoder:library:0.3.0'
    implementation 'rapid.decoder:jpeg-decoder:0.3.0'
    implementation 'rapid.decoder:png-decoder:0.3.0'
    implementation 'com.squareup.okhttp3:okhttp:3.11.0' //on 3.10.0 are deprecated some ciphers
    implementation 'com.squareup.okio:okio:1.15.0'
    implementation 'com.squareup.duktape:duktape-android:1.3.0'/* v 1.2.0 need 4+mb extra*/
    implementation 'com.github.franmontiel:PersistentCookieJar:v1.0.1'
    implementation 'com.evernote:android-job:1.2.5'
    githubImplementation 'com.google.android.gms:play-services-base:16.0.1'
    // ADDED BY O D I N
    implementation 'com.google.android.gms:play-services-ads:17.1.1'
    // ADDED BY O D I N
    implementation 'ch.acra:acra:4.9.2'
    fdroidApi project(':fakegps')
    // for device-based testing
    androidTestImplementation "com.android.support:support-annotations:$ANDROID_SUPPORT"
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    androidTestImplementation 'com.android.support.test:rules:1.0.2'
    androidTestImplementation 'junit:junit:4.12'
    // for host-based testing
    testImplementation 'junit:junit:4.12'
    testImplementation 'org.robolectric:robolectric:4.0-beta-1'

    android {
        testOptions {
            unitTests {
                includeAndroidResources = true
            }
        }
    }
}

Project's build.gradle
// Top-level build file where you can add configuration options common to all sub-projects/modules.

buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        jcenter()

        maven { url "https://jitpack.io" }
        // ADDED BY O D I N
        maven {
            url "https://maven.google.com"
        }
        // ADDED BY O D I N

        maven {
            url 'https://github.com/suckgamony/RapidDecoder/raw/master/repository'
        }
        google()
    }
}

after so many attempt to add the SDK i still can't find any solution for this, Hope i find it here

A: Add  maven { url 'https://maven.fabric.io/public' } to your Project build.gradle. Like below. This fixed it for me.
allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
       maven { url 'https://maven.fabric.io/public' }

    }

A: add
android {
    defaultConfig {
        ...
        minSdkVersion 15
        targetSdkVersion 28
        multiDexEnabled true
    }
    ...
}

dependencies {
  implementation 'com.android.support:multidex:1.0.3'
}

Multidex support prior to Android 5.0
 dependencies {
        def multidex_version = "2.0.1"
        implementation 'androidx.multidex:multidex:$multidex_version'
    }

https://developer.android.com/studio/build/multidex

A: I've met the same kind of error : com.android.tools.r8.utils.AbortException: Error: Program type already present: [com.some.lib].
After dumping all the dependencies in console (via ./gradlew dependencies > ./dept.txt), I found out a new added aar does contain the same  dependent library as reported above, so just exclude that out. It's done.
implementation ('the-new-library') {
    transitive = true
    exclude group : 'duplicate-lib-pkg', module:"duplicate-lib-name"
}


text:
Q: Parse Android SDK is not allowing delete request and returns [MongoError: exception: Mod on _id not allowed] in the log The Parse android SDK does not allow updating of a column in the user table
while I am using getCurrentUser() method to mark it as authenticated. When I call saveInBackground() on it I get the following error in the log file:

Uncaught internal server error. { [MongoError: exception: Mod on _id not allowed]
        name: 'MongoError'

Below is the code I am using for saving:
byte[] data = "Working at Parse is great!".getBytes();
        final ParseFile file = new ParseFile("abcdef.txt", data);

    ParseUser currentUser = ParseUser.getCurrentUser();
        if (currentUser != null) {
            // do stuff with the user
            currentUser.put("column_name", file);
            currentUser.saveInBackground(new SaveCallback() {
                @Override
                public void done(ParseException e) {
                    if (e == null) {
                        Log.i("KQ", "update successfully");
                    } else {
                        Log.i("KQ", "update error e = " + e);
                    }
                }
            });
        } else {
            // show the signup or login screen
            Log.i("KQ", "else");
        }

A: You have to save the ParseFile before attaching it to the User object.
Your code should be like this
byte[] data = "Working at Parse is great!".getBytes();
    final ParseFile file = new ParseFile("abcdef.txt", data);
    file.saveInBackground(new SaveCallback() {
        @Override
        public void done(ParseException e) {
            if(e==null)
            {
                ParseUser currentUser = ParseUser.getCurrentUser();
                if (currentUser != null) {
                    // do stuff with the user
                    currentUser.put("column_name", file);
                    currentUser.saveInBackground(new SaveCallback() {
                        @Override
                        public void done(ParseException e) {
                            if (e == null) {
                                Log.i("KQ", "update successfully");
                            } else {
                                Log.i("KQ", "update error e = " + e);
                            }
                        }
                    });
                } else {
                    // show the signup or login screen
                    Log.i("KQ", "else");
                }
            }
        }
    });

A: Till I get a good answer.I am currently using my cloud code beforeSave trigger in parse to remove the id field to get rid of the exception and unblock my work.
any good answer will still be appreciated.
code I am using right now is as follows in the cloud code.
Parse.Cloud.beforeSave(Parse.User, function(request, response) {
    // For Android SDK remove id field while updating a user becasue it was creating MongoDB Exception in android.
    if (request.object.get("updatedFrom") == 'android') {
        request.object.unset("updatedFrom");
        request.object.unset("id");
    }
    response.success();
});

thanks.


text:
Q: Launching an App from Custom URL from Safari not working as intended in iOS >12.3 We share the App deeplinks (Universal links) with our users over email, sometimes they get wrapped by email service providers for safety.
When user taps on these wrapped deeplinks, instead of opening the App directly it opens the url in Safari.
We have a page hosted on that url. We capture the deeplink there and try to open the App using Custom URL scheme (myurlscheme://). But if the App is not installed, we try to redirect the user to the App Store page.
It all worked okay until now, but seems like Apple made some changes in Safari in the new versions of iOS (>12.3).
What's happening now is, if the App is installed and we open the App from Safari (from Custom URL), the App Store page opens in a split second after opening our App.
This is the Javascript code that we are using:
window.location.href = 'myurlscheme://';
setTimeout(function() {
   window.location.href = "https://itunes.apple.com/us/app/myapp/id123456789?ls=1&mt=8";
}, 500);

Is anyone else experiencing this. If yes, were you able to find any solution?
Update:
If we set the timeout to 4000 (i.e. 4 seconds), then it does not redirect to the App Store after launching the App.


text:
Q: Create Laravel Nova Lens - Using $this when not in object context I am trying out larval Nova, particularly the lens
I have followed the guide https://nova.laravel.com/docs/1.0/lenses/defining-lenses.html
but it is complaining about the use of the $this in this line
   $query->select($this->columns())

with the error
$this when not in object context

here is the code
<?php

namespace App\Nova\Lenses;

use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Lenses\Lens;
use Laravel\Nova\Fields\Number;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Http\Requests\LensRequest;

class MostValuableUsers extends Lens
{
    /**
     * Get the query builder / paginator for the lens.
     *
     * @param  \Laravel\Nova\Http\Requests\LensRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return mixed
     */
    public static function query(LensRequest $request, $query)
    {
        return $request->withOrdering($request->withFilters(
            $query->select($this->columns())
                  ->join('licenses', 'users.id', '=', 'licenses.user_id')
                  ->orderBy('revenue', 'desc')
                  ->groupBy('users.id', 'users.name')
        ));
    }

    /**
     * Get the columns that should be selected.
     *
     * @return array
     */
    protected function columns()
    {
        return [
            'users.id',
            'users.name',
            DB::raw('sum(licenses.price) as revenue'),
        ];
    }

    /**
     * Get the fields available to the lens.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function fields(Request $request)
    {
        return [
            ID::make('ID', 'id'),
            Text::make('Name', 'name'),

            Number::make('Revenue', 'revenue', function ($value) {
                return '$'.number_format($value, 2);
            }),
        ];
    }

    /**
     * Get the filters available for the lens.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function filters(Request $request)
    {
        return [];
    }

    /**
     * Get the URI key for the lens.
     *
     * @return string
     */
    public function uriKey()
    {
        return 'most-profitable-users';
    }
}

Is there something else I need to configure?

A: The problem is you use $this in static function (a function that is not aware of $this context). I would suggest to create an instance inside your static function (if you really need a static function).

namespace App\Nova\Lenses;

use Laravel\Nova\Fields\ID;
use Illuminate\Http\Request;
use Laravel\Nova\Fields\Text;
use Laravel\Nova\Lenses\Lens;
use Laravel\Nova\Fields\Number;
use Illuminate\Support\Facades\DB;
use Laravel\Nova\Http\Requests\LensRequest;

class MostValuableUsers extends Lens
{
    /**
     * Get the query builder / paginator for the lens.
     *
     * @param  \Laravel\Nova\Http\Requests\LensRequest  $request
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return mixed
     */
    public static function query(LensRequest $request, $query)
    {
        $mostValuableUser = new MostValuableUsers();

        return $request->withOrdering($request->withFilters(
            $query->select($mostValuableUser->columns())
                  ->join('licenses', 'users.id', '=', 'licenses.user_id')
                  ->orderBy('revenue', 'desc')
                  ->groupBy('users.id', 'users.name')
        ));
    }

    ...


text:
Q: Delete Windows Share 'History' "the folders shared below were previously shared"? When trying to share a folder, if there have been previous shares on folders (which have since been removed), Windows will prompt: "the folders shared below were previously shared" and ask what you want to do with them.
Does anyone know how to remove those from the registry completely? These are no longer active shares, so they don't show up in computer management or any of the typical Windows Registry locations. I'd prefer if I remove a share that Windows just doesn't know anything about them anymore.
Previous Shares Prompt


text:
Q: Crystal Report Viewer - Export to/open a PDF after entering parameters I have a report viewer in place, and i would like the report in question to be opened in a PDF after the user enters parameters and clicks the submit button (instead of the report being opened in the report viewer window.)
I did some reading elsewhere and found this snippet
rptSP.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, "Report");

and i also found a posting where the following was recommended:

Write code to export the report to pdf inside of the CrystalReportViewer_BeforeRenderObject event.

but I haven't made it much past that.  Can anyone provide a code example, or link to one which shows this solution in place?

A: You can fetch report parameters on click event of submit button, and fetch report data based on these parameters, and after that, you can export it.
Here is a sample code for doing this.
ReportDocument rptDoc = new ReportDocument();
rptDoc.Load(Server.MapPath("ETR0040.rpt"));

// Fetch report parameters to retrieve report data.
...

// Retrieve report data.
DataSet dsResult = DBGateway.ExecuteCommand('command');
rptDoc.SetDataSource(dsResult);

// Report parameters - to be passed if there are any parameters which should be passed to report.
rptDoc.SetParameterValue("CustomerCode", customerCode);

DiskFileDestinationOptions diskOpts = new DiskFileDestinationOptions();
string targetFileName = Request.PhysicalApplicationPath + "Reports\\TempReports\\" + (new Random()).Next() + ".pdf";

rptDoc.ExportOptions.ExportDestinationType = ExportDestinationType.DiskFile;
rptDoc.ExportOptions.ExportFormatType = ExportFormatType.PortableDocFormat;

diskOpts.DiskFileName = targetFileName;
rptDoc.ExportOptions.DestinationOptions = diskOpts;

// Export report ... Server-Side.
 rptDoc.Export();

FileInfo file = new FileInfo(targetFileName);

Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/pdf";
Response.TransmitFile(file.FullName);

A: DataTable _table = RetObj.EgpReceipt_PrintFC(DummId);

rptDoc.Load(Server.MapPath("EgpReceiptPrintFC.rpt"));
rptDoc.SetDataSource(_table);

rptDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, HttpContext.Current.Response, false, "Redeemed");

A: I dug through an old codeproject article that I submitted back in 2006 - which exports to pdf from a Crystal Reports project. I'm not sure if the libraries are relevant anymore - and even worse, it's in VB. Hope this works, or at least points in the right direction.
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
'
' <snip>
Dim ExportToFile As New CsReports.Reports
ExportFile = ExportPath + Session.SessionID.ToString + ".pdf"
ExportToFile.ReportToPDF(crReportDocument, ExportFile)
Try
    ' Export the report
    crReportDocument.Export()
    Response.ClearContent()
    Response.ClearHeaders()
    Response.ContentType = "application/pdf"
    Response.WriteFile(ExportFile)
    Response.Flush()
    Response.Close()
    System.IO.File.Delete(ExportFile)
Catch err As Exception
    Throw err 'MessBox("Error: Export Failed.!" + err.Message.ToString)
End Try 'Adobe Acrobat Export***************************

Then there's the method ReportToPDF:
Imports CrystalDecisions.CrystalReports.Engine
Imports CrystalDecisions.Shared
Imports System
Imports System.Data
Imports System.Web.UI.Page
Imports System.IO

Namespace CsReports
Public Class Reports
    Inherits System.Web.UI.Page

    Dim crExportOptions As ExportOptions
    Dim crDiskFileDestinationOptions As DiskFileDestinationOptions

    Public Sub ReportToPDF(ByVal crReportName As ReportDocument, ByVal ExportFile As String)
        ' Create a new instance of the diskfiledestinationoptions class and
        ' set variable called crExportOptions to the exportoptions class of the reportdocument.
        crDiskFileDestinationOptions = New DiskFileDestinationOptions()
        crExportOptions = crReportName.ExportOptions

        'Set this file as the filename property for the DestinationOptions class
        crDiskFileDestinationOptions.DiskFileName = ExportFile

        'set the required report ExportOptions properties
        With crExportOptions
            .DestinationOptions = crDiskFileDestinationOptions
            .ExportDestinationType = ExportDestinationType.DiskFile
            .ExportFormatType = ExportFormatType.PortableDocFormat
        End With
    End Sub
End Class
End Namespace


text:
Q: GPU Compute on Android? How do I program the existing GPU architectures on Android. And is there a possibility that in the near future Android will be fully supported by CUDA perhaps maybe through an Android-based dev kit like Jetson TK1.
I've read about Renderscript but I think it is tailored more for image processing. But I'm planning on doing simulations instead. So is there a way I can get these simulations on the android platform.

A: I don't see much opportunities to develop CUDA apps for Android except for developing for devices that employ CUDA enabled GPU such as Tegra K1, example of such device is NVIDIA SHIELD. Then you can grab Tegra Android Development Pack and start your development right away.


text:
Q: jQuery: Rearranging Elements Without Repeating Let's say you have HTML like this:

bottom

top

bottom

top

and you want to move .top above .bottom in each .section with jQuery.
I'm trying to do this with:
$('.section').each(function (i, obj) {
    $('.bottom').insertAfter('.top');
});

But this is causing "bottom" to repeat itself four times in each section.
Fiddle: http://jsfiddle.net/TLejL/
What am I doing wrong?

A: Try to use the $(this) reference inside the .each() function,
$('.section').each(function (i, obj) {
    $(this).find('.bottom').insertAfter($(this).find('.top'));
});

or
$('.top').each(function() {
    $(this).closest('.section').prepend($(this));
});

DEMO

A: You need to target the top & bottom elements within the current section
$('.section .top').after(function (i, obj) {
    return $(this).prev()
});

Demo: Fiddle


text:
Q: WordPress 403 Forbidden when updating WooCommerce product Recently when I wanted to updated a specific product on my WordPress, I receive "403 Forbidden" error right after I click "Update" blue button.
There are several similar questions on both StackOverflow and WordPress Exchange but most of them happened just because they added code or it happens right after installing WordPress.
In this case here, I haven't made any specific change before making new changes. I published the product about a year ago and now I can't update it! I can't even private it to publish a newer version!
For this specific product, I used Attributes and Variations. I even checked related Brand, Attributes, Tags and Categories and I found no issue with any of them. All images, brands, attributes and anything else related to this product are accessible and public.
I know I should give deeper details and information but unfortunately, WordPress doesn't give me any more information that why this happens and what is wrong exactly with this product.
What I'm worry right now is that there can be many other product with this problem and I don't even know what to do with them now!
UPDATE: I've done more investigations and I realized that whatever styles I apply such as "H1", "H2", "H3", "H4", it redirects me to 403 Forbidden page!This happens ONLY for two available products.
If anybody here any any possible solution for this problem, please helps me and comments below. Thank you.

A: Problem is solved!
I found out that author has used this (¾") weird thing somewhere in descriptions and yes, it couldn't save this "¾" in database.


text:
Q: Reorder tableview rows according to a specific order stored in a SQLite table in iPhone I am working on an application that shows news feeds based on different categories. I have a list of categories stored on a server in a XML file which is parsed and its content is stored in a SQLite table.
The structure of the XML looks like this:
<categories>
<category>
<name>Lajme</name>
<image>
http://apps.shqip.mobi/Apps/An/Shqipcom/data/source/img/category/lajmet.png
</image>
<order>1</order>
</category>
</categories>

The idea is that I want to reorder the categories manually, i.e. i want the category "Maqedoni" to be shown above other categories in the news feed. (see screenshots below)

How can i retrieve somehow the current postition of the row and whenever the user moves it up or down to increase or descrease the order number from the database?
I have no idea how to approach this problem because this is one of my first projects. Any help would be appreciated.
Thanks in advance.
Granit.


text:
Q: Unable to get an IP for my Raspberry in WIndows 8 I have connected my Raspberry 2 to my PC with an ethernet cable and a USB cable. I use wifi. But when I try to enable sharing I see these options in the drop-down.
Ethernet
Virtualbox host-only network
VMWare network adapter vmnet 1
VMWare network adapter vmnet 8
Npcap loopback adapter

Which one should I use ?
If I choose 'Ethernet' and execute nmap I don't see the raspberry host name or IP in the result.
So I couldn't get an IP for my Raspberry.
Mine is a fresh pi. I hope I can use it like this. It should have NOOBS. Right ?

A: This is what I observed when I connected a monitor to the Pi.
The very first time the new Pi boots it didn't have access to the internet. The NOOBS boot screen showed a dialog message that it couldn't access the distribution list.
So I disconnected the ethernet cable from the PC and connected it to the router.
And it had access to the distribution list and the GUI showed other operating systems that I can choose. But NOOBS continued to show the initializing message for a long time. I found this other thread about the same issue.
I believe this prevented me from proceeding and connecting a monitor helped me.
But when I disconnected the ethernet cable from the router this message disappeared. So I could choose 'wheezy' and install it.
After connecting the ethernet cable back to the PC I just shared my 'wifi' connection by choosing 'Ethernet' as the option(See the question).
I didn't bridge it (See the comments).
This command showed the Pi's IP and I connected to it using Putty.
     arp -a | findstr b8-27-eb


text:
Q: C # Selenium problem to click a button with webdriver when there are 2 identical buttons on the page I ask for a hand to be able to click a button with webdriver.findelement;  the problem is that in the html the two buttons are identical in all properties and I cannot understand how to choose between the 2. The only field that changes is aria-labeledby but it changes at each refresh and therefore it is impossible to capture it with findElement .  I leave the images of the code of the two buttons below.  The tags are contained in a span, which has the usual characteristics for both buttons.
enter image description here
enter image description here

A: With the limited amount of information it is hard to say for sure, but in this event I would normally try xpath or full xpath. You didnt specify what you gave find element to use but Xpath should work.


text:
Q: A gem for saving report filters I'm building a new website where users can create their own reports.
The report consists of blocks and a block can be a graph or a table. So such a block visualizes some data. The user can chose which objects are the source of that block and the filters on that. From an existing block he can edit those filters. reports are saved so later on such a report can be called and the data in the graphs and tables is updates.
Are there any gems or methods in Ruby On Rails how I can achieve the saving of such data filtering?
One way could be generating SQL code when creating a block, but I have to save a lot of information then to be able to edit such a block.
Thanks
Laurens

A: You could store report filters in nosql database such as mongodb. With this solution it will be very easy to store and retrieve those params as JSON documents.


text:
Q: Extensions of the Ito integral
This is an extract from Oksendal's Stochastic Differential Equations (end of chapter 3). I cannot understand why we have taken the intersection, surely the union would have been more appropriate?

A: It all depends on what you want the set $\mathcal{V}^{m\times n}$ to be used for. In Oksendal's monograph, what it denotes is the following. Each set $\mathcal{V}^{m\times n}(0,T)$ denotes the set of $m\times n$ matrix processes with entries integrable over $(0,T]$. With Oksensdal's definition of $\mathcal{V}^{m\times n}$, this set becomes the set of $m\times n$ matrix processes with entries integrable over any interval (S,T] for $0 \le S \le T$. It's just a convenience, really, not any profound "extension" of the integral.


text:
Q: PHP index array to associative first element equals second and so on I have an array like this :
$actions = array(
   "controller",
   "index",
   "method",
   "default",
);

I want to get the first key equals the second key and so on like this
$actions = array(
  "controller" => "index",
  "method" => "default"
);

How can i do this thanks !!

A: Here is an example with for loop:-
<?php

$actions = array(
   "controller",
   "index",
   "method",
   "default",
);

for($i = 0; $i < count($actions); $i++)
{
   $arr[$actions[$i]] = $actions[$i += 1];
}

echo "<pre>";
print_r($arr);


text:
Q: pip not working on ubuntu 18, how to fix that? ubuntu@ip-172-31-18-233:my_folder$ lsb_release -a
No LSB modules are available.
Distributor ID: Ubuntu
Description:    Ubuntu 18.04.5 LTS
Release:        18.04
Codename:       bionic

I installed pip using:
sudo apt install python-pip

The python version:
python --version
Python 3.6.9

But, when I try to install any package, I am getting this error.
sudo pip install yamlpath
Traceback (most recent call last):
  File "/usr/bin/pip", line 9, in <module>
    from pip import main

sudo pip3 install yamlpath
sudo: pip3: command not found

 python -m pip install yamlpath
/usr/bin/python: No module named pip

A: #Below version is for python 2 only
sudo apt remove python-pip -y

#Python3 version of pip
sudo apt install -y python3-pip

#Setting as default version
sudo update-alternatives --install /usr/bin/pip pip /usr/bin/pip3 1

A: You might take a look at this stackoverflow question.
In short, you've got two pips that aren't playing nicely together. If you uninstall one, you might be able to manage with the other. There are too many viable solutions in the answers to justify writing them out here. Maybe just sudo apt-get remove pip3 and trying to find your existing pip. Personally, I'd cycle through these:
pip --version
pip3 --version
python3 -m pip --version
python3 -m pip3 --version

For example, I have 20.0.2 for pip3 --version and python3 -m pip --version
This should help you find your version once the conflicting install is removed.

A: To resolve these issues, I recommend trying the following steps:
Upgrade pip:
python -m ensurepip --upgrade

Try installing yamlpath using python -m pip:
python -m pip install yamlpath

If you still encounter errors, please provide more information about your system and the exact error message you receive, so I can help you better.


text:
Q: Why should identifiers not begin with a number? Most programming languages appear to be designed to not allow one to declare an identifier that starts with a number. I was just curious to know the reason. I have already searched the web, but couldn't find a satisfactory explanation.

A: In C/C++, a number followed by a letter is considered to be a numeric constant and the string that follows, qualifies the type of the constant.  So for example (these are VC++, not sure how standard they are):

*

*0 - signed integer

*0l - signed long integer

*0u - unsigned integer

*0i64 - 64 bit signed integer

So a) it is easier for the lexer as Daniel said but also b) it makes an explicit distinction since 0y might be a variable but 0u would never be.  Plus other qualifiers, like "i64" were added way later than "l" or "u" and they want to keep the option open of adding more if needed.

A: The convenience of the people implementing the lexer.  (No, seriously, that is about it.  Various languages have other reasons, but it ultimately comes down to that.)

A: Consider the following 2 cases:
Case 1
Lets assume that an identifier could begin with a number.
So a statement like below would be valid (since an identifier can have 1 or more characters)  :

int 3;

When I try to use the above variable in a program, it'll result in compiler ambiguity:

int 3,a;
  3=5;
  a=3;

In the statement a=3 what is the role of 3 (is it a variable with value 5 or is it the numeral 3) ?
Case 2
As opposed to the example above, lets assume that a language were to actually allow identifiers starting with a number while still disallowing numerals being used as identifiers. This can cause the following issues:

*

*The language rules regarding the variable which says that a variable can consist of 1 or more characters will have to be redefined to a complex rule like: A variable can have one or more characters and must be unique if it does not start with a number while it cannot be of single character length when starting with a number (etc..)

*The compiler will have to check for and report error cases when all numerals (eg 333) and valid alphabet suffixes (e.g. 34L) are being used as variable names. In loosely typed languages like Python and JS where you can use variables on the fly without declaring them, it may even be impossible to check for the special cases involving all numerals e.g. if (33==5) Here, 33 could be an erroneous undeclared variable that the user has declared. But the compiler will not be able to identify this and report the error.
Making this restriction will prevent the programmer from using numbers as identifier names.

A: For the most part this has nothing to do with making it easy for the compiler writers and parsing efficiency, but, more to do with designing a syntax that encourages clear readable and unambiguous code.
Its the language designers thought it would be nice to be able to write numeric literals like the number 1 as just plain 1 .
It would be quite possible to design a language syntax where numeric literals were quoted in some way for example tildas so the numberic literal for number one was encoded as ~1~ and anything not a keyword and not enclosed in quotes was treated as a variable name.
So you could code statements like:
1 = ~2~
two = 1 * ~2~

But also:
2 = ~3~
six = 2 + 2

Whatever syntax you choose ambiguous and hard to follow code is unavoidable.
The C language and most of the "curly brackets" languages descended from C also thought it a good idea to allow programmers to code Octal and Hexadecimal literals directly, and, to specify the type of the literal if this was important.  So
010  // Octal 10 = 8;
0x10 // Hexadecimal 10 = 16;
5l   // long integer with decimal value 5
2.0d // double float with value 2

So even if you allowed variable names start with a number followed by a combination of numbers and letter that included at least one letter you would present the programmer with the problem of deciding whether a given group formed a variable name or a numeric literal
so
2lll = 22 // OK
2ll  = 2  // compiler error

Such ambiguity would not help anyone writing or reading a program.
For a closely related real world example you could look at PL/1 language whose designers thought that being able to use keywords as variable names was a good idea so that:
IF THEN THEN THEN = ELSE; ELSE ELSE = THEN;
IF IF THEN ELSE = IF; ELSE THEN = ELSE;
DO WHILE (WHILE = DO); END = WHILE + DO; END;

Is valid code which compiles and executes.

A: Fortran had a huge effect on how later languages were designed. Early on (some of these problems have since been fixed) Fortran had almost no rules restricting what name you could give to an identifier. This made the language extremely difficult to parse both for compilers and for programmers. Here's one classic example:
if if .eq. then then = else else else = endif endif
K  I   K   K    I      I    K    I      I     K

Here I've marked the "language key words" with K and the identifiers (variable names) I. Given that there's no difference in spelling, I think you can probably understand how confusing this could be. Of course, this is an extreme example, and it's unlikely anybody ever wrote code quite like this on purpose. Sometimes people did "recycle" language key words as identifier names though -- and in a lot of cases a simple typo could result in code that the language spec said should be parsed this way, even though it wasn't intended at all. For another well-known example, compare this:
do 10 i = 1,10

to this:
do 10 i = 1.10

The first is a do loop -- iterating a block of code 10 times. The second, however, has had the comma changed to a decimal point, so it's assigning the value 1.10 to a variable named do 10 i.
This also meant that writing a Fortran parser was relatively difficult -- you couldn't be certain that the do at the beginning of the line was really a key word until you reached the end of the line, and verified that all the other elements of a do loop were present. The parser generally had to be ready to "backtrack", re-parsing the line from the beginning to come to the "correct" (but often unintended) answer of what was really there.
After a few years of this, language designers (most of them anyway) went toward the opposite extreme -- restricting nearly everything about the language as much as possible without the users complaining too much.
Early BASIC, for example, basically said you couldn't even use a key word as part of an identifier -- for example, fora=1 would be parsed as for a = 1 (i.e., the beginning of a for loop, not an assignment). That apparently generated enough complaints that it didn't last very long. The rule about starting an identifier with a digit apparently hasn't generated a lot of complaints, so it continues to be used (at least in most languages).

A: Likely this convention has evolved from very early historical language design decisions, as on early machines the entire compiler, including lexical analysis, had to run in a few kWords, less memory than even just the first-level processor data cache on current mobile devices, so the allowed variable names were very limited, and had to be easy to distinguish from numeric constants in very few op codes.
Thus, the convention became what generations of programmers are used to.

A: It's not a logically required rule for programming language but just the convention used by  many language designers.
I can design radically different language that allow all character for identifiers.
For all code lines, first 20 character will describe the statement type then next 20 character will define the first symbol for the statement, and next 20 character is operand for the statement. This language will be executed on a stack processor.
01234567890123456789 01234567890123456789 01234567890123456789

decl symbol          12345
assign value         12345                12345
decl symbol          99999
assign value         99999                12345
push                 12345
push                 99999
add
print top

This code could be translated in C as below:
int i12345 = 12345;
int i99999 = 12345;
printf("%d", i12345+i9999);

That's all. It's meaningless and the no-number-in-identifiers rule is also pointless in logical ground.

A: In addition to "convenience for the lexer", I think it is also worth considering "convenience for the reader".
When reading code, you need to quickly and repeatedly identify which words are identifiers, and which are numbers.   Looking for a digit at the beginning is easier on our visual pattern-matching; it would be a chore if we had to carefully check all the characters to make sure.

A: The answer to this question lies in automata or more precisely finite automata that defines the regular expression. The rule is...compilers need exact algorithms or rules to decide at every character that they parse. If identifiers were allowee  to start with a number then the compiler will be in a fix..about the nature of the token coming...will it be a number or an identifier...and as compilers cant backtrack to earlier positions...so..to make it clear to the compiler that the coming token is precisely an identifier or a number...this restriction is there...coz of this...compiler knows just by scanning the first character that the coming token is an identifier or a number.


text:
Q: Correct use of Android SQLiteStatement's simpleQueryForBlobFileDescriptor() The function simpleQueryForBlobFileDescriptor() in Android's SQLiteStatement is a mystery to me. And no one seems to use it anywhere.  It seems as though it would be a fast method for individual blob access and in terms of performance (if the documentation is to be believed) the combination of SQLiteStatement and Parcel should yield a very fast result when used to stream blob data out of a db. I don't know because I can't get the thing to work so that I could test... Any help with this or insight would be appreciated:
SQLiteStatement get = mDb.compileStatement(
    "SELECT blobColumn" +
    " FROM tableName" +
    " WHERE _id = 1" +
    " LIMIT 1"
);

ParcelFileDescriptor result = get.simpleQueryForBlobFileDescriptor();
// now what?

I should probably note that I am using and only really care about Honeycomb (3.2) and thank you in advance for any insight.

A: SQLiteStatement get = mDb.compileStatement(
    "SELECT blobColumn" +
    " FROM tableName" +
    " WHERE _id = 1" +
    " LIMIT 1"
);

ParcelFileDescriptor result = get.simpleQueryForBlobFileDescriptor();
FileInputStream fis = new FileInputStream(result.getFileDescriptor()); // read like any other

and I can verify that this is very fast for my use cases.
Where I found this particularly useful (if you need to create your own custom offline webview file cache like I did) was in the openFile override for a content provider where you can just return the descriptor straight up (or ideally override openTypedAssetFile())
examples:
files is a DB helper and getFileDescriptor(String) is similar to the code above
public AssetFileDescriptor openTypedAssetFile(Uri uri, String mimeTypeFilter, android.os.Bundle opts) throws FileNotFoundException {
    ParcelFileDescriptor pfd = files.getFileDescriptor(uri.toString());
    if (pfd != null) {
        return new AssetFileDescriptor(pfd, 0, AssetFileDescriptor.UNKNOWN_LENGTH);
    }
    return null;
}

or another great use for a similar problem:
(where you want to serve custom file from a db to a webview)
private WebViewClient webViewClient = new WebViewClient() {
    @Override
    public WebResourceResponse shouldInterceptRequest(WebView view, String url) {

        ParcelFileDescriptor pfd = files.getFileDescriptor(url);
        if (pfd != null) {
            return new WebResourceResponse(null, null, new FileInputStream(pfd.getFileDescriptor()));
        }

        return null;
    }


text:
Q: I'm getting from the database dictionary in which there is one or more objects NSNull I'm getting from the database dictionary in which there is one or more objects NSNull. In the future, I can not in any way to work with him as the app crash. I tried many ways to remove from the dictionary NSNull objects, method removeObjectForKey but any attempt to do this I get an error that is an array of reason:
- [__ NSArrayM removeObjectForKey:]: unrecognized selector sent to an instance

And I can not remove these objects by method the array removeObjectAtIndex as this dictionary. I only thought of how to do this is to remove these objects by type. Is it possible to do so, remove the object from the dictionary that match NSNull type? Or maybe there is another solution to this problem?
Thank you for any help!

A: This loop (adapted from this post) should help you substitute the NSnull entries with a string of your choice (forgive typos, I am not in front of my computer).
for(NSString *key in yourDictionary) {
  id dictionaryEntry= [yourDictionary objectForKey:key];
  if(!dictionaryEntry) {
     [newDictionary setObject:@"string" forKey:key];
  } else {
     [newDictionary setObject:[yourDictionary objectForKey:key] forKey:key];
  }
}

A: You say:

And I can not remove these objects by method the array "removeObjectAtIndex" as this dictionary.

Unfortunately your error:

[__ NSArrayM removeObjectForKey:]: unrecognized selector

Does not agree with you.  You have an array.  And the reason you cannot use removeObjectAtIndex is because it is immutable.

A: You are removing a key from an array

Note down that you cannot remove a key from an array. Than this error is obvious.

Also for removeObjectAtIndex

Make sure your array should be mutable. Then you can use removeObjectAtIndex.

Hope it works for you.


text:
Q: SwingWorker get() freezing interface I am using SwingWorker to get some long running database calls done in the background. Right before executing the SwingWorker I launch a jpanel with label to inform user that the app is doing some background work. The problem is that if I use the SwingWorker get() method to fetch the results of the long running operations, my jpanel freezes and nothing gets displayed. If I don't use the get() method, the jpanel appears normally.
Can you please let me know what I may be doing wrong? I already spend hours on this without figuring out why. The SwingWorker gets executed after all jpanel creation is done, I don't understand why it's getting hang.
Thanks a lot!
Function that creates jpanel and starts SwingWorker:
private void snapshotOldVariables() {

    JFrame loadingJFrame = new JFrame();
    LoadingJPanel loadingJPanel = new LoadingJPanel();

    Dimension d1 = new Dimension();
    d1.setSize(500, 500);
    loadingJFrame.setResizable(false);
    loadingJFrame.setMinimumSize(d1);
    loadingJFrame.setTitle("Loading...");
    loadingJFrame.setLocationRelativeTo(null);
    loadingJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    loadingJFrame.add(loadingJPanel);
    loadingJFrame.setVisible(true);

    loadingJPanel.updateStatus("Creating snapshot of values...");

    MySwingWorker worker = new MySwingWorker(tableRows, selectedItems);
    worker.execute();

    GMSnapshotVO snap = null;
    try {
        snap = worker.get();
    } catch (InterruptedException | ExecutionException e) {
        System.out.println(e);
    }

    loadingJPanel.updateStatus("Complete");
    loadingJFrame.dispose();

    productIds = snap.getProductIds();
    oldLocationIds = snap.getOldLocationIds();
    oldStatusIds = snap.getOldStatusIds();

}

Screenshot of jpanel freezed while function waits for worker.get():

Function with commented worker.get() code block:
    private void snapshotOldVariables() {
    JFrame loadingJFrame = new JFrame();
    LoadingJPanel loadingJPanel = new LoadingJPanel();

    Dimension d1 = new Dimension();
    d1.setSize(500, 500);
    loadingJFrame.setResizable(false);
    loadingJFrame.setMinimumSize(d1);
    loadingJFrame.setTitle("Loading...");
    loadingJFrame.setLocationRelativeTo(null);
    loadingJFrame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

    loadingJFrame.add(loadingJPanel);
    loadingJFrame.setVisible(true);

    loadingJPanel.updateStatus("Creating snapshot of values...");

    MySwingWorker worker = new MySwingWorker(tableRows, selectedItems);
    worker.execute();

    /* COMMENT STARTS HERE
    GMSnapshotVO snap = null;
    try {
        snap = worker.get();
    } catch (InterruptedException | ExecutionException e) {
        System.out.println(e);
    }

    loadingJPanel.updateStatus("Complete");
    loadingJFrame.dispose();

    productIds = snap.getProductIds();
    oldLocationIds = snap.getOldLocationIds();
    oldStatusIds = snap.getOldStatusIds();
    COMMENT ENDS HERE */

}

Screenshot of jpanel not freezed and appearing correctly:

A: As far as I know you should not call SwingWorker's get() method directly from UI thread unless you are sure it is done processing. Instead you should call it inside overriden MySwingWorker.done(), where you can be sure that background task finished executing.
It is not relevant, that all JPanel creation is done before blocking as Swing still needs its main UI thread for repainting and updating UI and to stay responsive. By calling get() you are blocking it.
From UI thread you should just call execute() and all the processing of results (productIds = snap.getProductIds(); oldLocationIds = snap.getOldLocationIds(); oldStatusIds = snap.getOldStatusIds(); in your case) should be done inside done() callback.
A simple example is available in this answer.
In your case it should go something like this:
//inside MySwingWorker
@Override
protected void done() {
    try {
        System.out.println("My long running database process is done. Now I can update UI without blocking/freezing it.");
        GMSnapshotVO snap = get();
        loadingJPanel.updateStatus("Complete");
        loadingJFrame.dispose();
        productIds = snap.getProductIds();
        oldLocationIds = snap.getOldLocationIds();
        oldStatusIds = snap.getOldStatusIds();
        //..do other stuff with ids
    } catch (InterruptedException | ExecutionException e) {
        e.printStackTrace();
    }
}

Hope it helps.


text:
Q: For a given even integer $k >14$ is there always a prime $p$ such that $k \leq p-3$ and $p|B_k$? Let $k$ be a sufficiently large positive even integer. (I think $k > 14$ should do.) Can one always find a prime $p$ such that $p$ divides the numerator of the $k$-th Bernoulli number $B_k$ and $k \leq p-3$? A quick inspection of the table of Bernoulli numerators suggests that this is indeed the case. Am I missing something obvious that would prove this or is it one of those notorious "easy-to-state-but-hard-to-prove" questions?
Certainly, the lower bound $|B_k| > 2(k/\pi e)^{k}$ tells us that
 the numerator of $|B_k|$ is way larger than $k$ but this doesn't discount the possibility that the numerator consists only of (powers of) small primes.

A: All pertinent results on the divisibility of Bernoulli numbers I have come across in the literature are negative in nature, including what is possibly the only one pertaining to an index of a specific form: that $B_{(p+1)/2}$ is not divisible by $p$ if $p \equiv 3 \bmod{4}$. The idea behind this statement traces back to Augustin Cauchy, "Mémoires sur la théorie des nombres," Mémoires de l'Académie Royale des Sciences de l'Institut de France 17 (1840): 249–768, at p. 445, and it is clearly implied in A. Friedmann and J. Tamarkine, "Quelques formules concernant la théorie de la fonction [x] et des nombres de Bernoulli," Journal für die reine und angewandte Mathematik 135 (1909): 146–56, at p. 156 (which however contains a misprint). More modern-style proofs appear in Leonard Carlitz, "The first factor of the class number of a cyclic field," Canadian Journal of Mathematics 6 (1954): 23–26, at p. 25, and in Wells Johnson, "$p$-adic Proofs of Congruences for the Bernoulli Numbers," Journal of Number Theory 7 (1975): 251–265, at p. 257, where it is described as "one of the few general results which seems to be known along these lines." Stephen V. Ullom, "Upper bounds for $p$-divisibility of sets of Bernoulli numbers," Journal of Number Theory 12 (1980): 197–200, showed that at most one-half of the $B_{2k}$ with $2k \le p-3$ are divisible by $p$, and Ullom's result is sharpened in Samuel S. Wagstaff, Jr., "$p$-Divisibility of Certain Sets of Bernoulli Numbers," Mathematics of Computation 34 (1980): 647–649.


text:
Q: FlorientR/laravel-gentelella: npm install --global bower gulp fails I want to use the following framework:
https://github.com/FlorientR/laravel-gentelella
But when I follow the installation guide I need to run the following commands:
php artisan key:generate
npm install --global bower gulp
npm install
bower install
gulp

The first command works fine, but: npm install --global bower gulp fails. It gives the following error:
> C:\Program Files\nodejs\node_modules\npm\node_modules\request\node_modules\har-valid
ator\src\index.js:1
(function (exports, require, module, __filename, __dirname) { ����������������
                                                              ^
SyntaxError: Unexpected token ILLEGAL
    at exports.runInThisContext (vm.js:73:16)
    at Module._compile (module.js:443:25)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Module.require (module.js:365:17)
    at require (module.js:384:17)
    at Object.<anonymous> (C:\Program Files\nodejs\node_modules\npm\node_modules\req
uest\lib\har.js:5:16)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
npm ERR! Windows_NT 6.3.9600
npm ERR! argv "C:\\Program Files\\nodejs\\\\node.exe" "C:\\Program Files\\nodejs\\no
de_modules\\npm\\bin\\npm-cli.js" "install" "--global" "bower" "gulp"
npm ERR! node v0.12.7
npm ERR! npm  v2.11.3

> npm ERR! C:\Program Files\nodejs\node_modules\npm\node_modules\request\node_modules\
har-validator\src\index.js:1
npm ERR! (function (exports, require, module, __filename, __dirname) { �������������
���
npm ERR!                                                               ^
npm ERR! Unexpected token ILLEGAL
npm ERR!
npm ERR! If you need help, you may report this error at:
npm ERR!     <https://github.com/npm/npm/issues>

The package.json contains:
{
  "private": true,
  "scripts": {
    "prod": "gulp --production",
    "dev": "gulp watch"
  },
  "devDependencies": {
    "gulp": "^3.9.1",
    "laravel-elixir": "^5.0.0",
    "bootstrap-sass": "^3.0.0"
  }
}

Do you guys see the problem?

A: I reinstalled NodeJs. That was the problem..


text:
Q: How do I conditionally add the Access-Control-Allow-Origin header for fonts served through an X-Accel-Redirect in nginx I am trying to serve some webfonts through a PHP script that tells nginx to do an internal redirect using X-Accel-Redirect.
As the script serves many types of files, I only wish to add the Access-Control-Allow-Origin header for fonts.
This is a configuration I have tried that works:
location /deploys/ {
  internal;
  alias   /www/deploys/;
  expires 1y;

  add_header Access-Control-Allow-Origin *;
}

The problem with this approach is that ALL files now contain the Access-Control-Allow-Origin header. I only want my fonts to have that header.
So, I tried a conditional:
location /deploys/ {
  internal;
  alias   /www/deploys/;
  expires 1y;

  if ($request_filename ~* ^.?/([^/]?)$)
  {
     set $filename $1;
  }

  if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
     add_header Access-Control-Allow-Origin *;
  }
}

Unfortunately, this does not work (and I suspect it would be due to the internal redirect using `X-Accel-Redirect).
How does one go about appending the Access-Control-Allow-Oirgin header for some extensions using X-Accel-Redirect?

A: It looks like alias will change the request file. I did not have time to compile and install the echo module to verify, but using the following config fixed the problem:
location /deploys/ {
  internal;

  if ($request_filename ~* ^.?/([^/]?)$)
  {
     set $filename $1;
  }

  if ($filename ~* ^.*?\.(eot)|(ttf)|(woff)$){
     add_header Access-Control-Allow-Origin *;
  }

  alias   /www/deploys/;
  expires 1y;
}


text:
Q: Deriving Jacobi triple from the Weyl-Kac denominator formula of affine $\mathfrak{sl}_2$ The Weyl-Kac denominator formula states
$$\prod_{\alpha\in\Phi^+}(1-e(-\alpha))^{mult(\alpha)}=\sum_{w\in W}\epsilon(w)e(w(\rho)-\rho))$$
Where the product is taken over the positive roots and the sum is taken over the Weyl group. Here $\epsilon(w)=(-1)^{l(w)}$ where $l(w)$ denotes the length of $w$ and $e(\alpha)$ is the formal exponential.
I'm trying to apply this to the affinization of $\mathfrak{sl}_2$ with simple roots $\{\alpha_0,\alpha_1\}$. In this case the $\rho=\frac{\alpha_1}{2}+2\Lambda_0$ seems to work. Here $\Lambda_0$ is defined on the coroots st. $\Lambda_0(\alpha_i^\vee)=\delta_{i0}$.
The Weyl group of the affinization of $\mathfrak{sl}_2$ is generated by $s_0,s_1$ st. $s_0^2=s_1^2=1$ (it's the infinite dihedral group). The generators works on $\rho$ in the following way
$$s_0(\rho)=\rho-\rho(\alpha_0^\vee)\alpha_0=\rho+\alpha_0=\rho-\alpha_1+\delta$$
$$s_1(\rho)=\rho-\rho(\alpha_1^\vee)\alpha_1=\rho-\alpha_1$$
Now for the formula. The positive roots are exactly $\alpha_1+k\delta$ for $k\geq 0$, $-\alpha_1+k\delta$ for $k\in\mathbb{N}$ and $k\delta$ for $k\in\mathbb{N}$. Here $\delta=\alpha_0+\alpha_1$. Writing $e(-\delta)=q$ and $e(-\alpha_1)=r$ then the left side is
$$\prod_{k>0}(1-q^k)(1-q^{k-1}r)(1-q^kr^{-1})$$
Turning to the right side, is where I get in trouble. I've seen it should equal $\sum_{k\in\mathbb{Z}}(-1)^kr^kq^{\frac{k(k-1)}{2}}$, so working my way backwards then $\sum_{w\in W}\epsilon(w)e(w(\rho)-\rho)$ should equal
\begin{align*}
\sum_{k\in\mathbb{Z}}(-1)^ke(-k\alpha_1)e(-\frac{k(k-1)}{2}\delta) &= \sum_{k\in\mathbb{Z}}(-1)^ke(-k\alpha_1-\frac{k(k-1)}{2}\delta) \\
&=\sum_{m\in\mathbb{Z}}e(-2m\alpha_1-\frac{2m(2m-1)}{2}\delta)\\
&-e(-(2m+1)\alpha_1-\frac{(2m+1)((2m+1)-1)}{2}\delta) \\
&=\sum_{m\in\mathbb{Z}}e(-2m\alpha_1-m(2m-1)\delta)\\
&-e(-(2m+1)\alpha_1-(2m+1)m\delta)
\end{align*}
Which is where I'm stuck.

A: Let $(\delta, \varpi_1, \Lambda_0)$ be the basis of $\mathfrak{h}^*$ which is dual to the basis $(d, \alpha_1^\vee, c)$ of $\mathfrak{h}$, where $c$ is the canonical central element and $d$ is the derivation. The element $\varpi_1$ is a lift of the fundamental weight of $\mathfrak{sl}_2$ to the affine algebra, but is not a fundamental weight of the affine algebra: instead the element $\Lambda_1 = \varpi_1 + \Lambda_0$ is. In this basis the missing roots and coroots are
$$ \alpha_1 = 2 \varpi_1, \quad \alpha_0 = \delta - 2 \varpi_1, \quad \alpha_0^\vee = c - \alpha_1^\vee.$$
The reason we use this basis is because it shows the structure of the Weyl group a bit better: abstractly, the affine Weyl group (for untwisted affine Lie algebras) is the semidirect product of the finite coroot lattice and the finite Weyl group. In terms of the basis $(\delta, \varpi_1, \Lambda_0)$ of $\mathfrak{h}^*$, the matrices (with zeros omitted) of the simple reflections are
$$ s_0 = \begin{pmatrix} 1 & 1 & -1 \\ & -1 & 2 \\ & & 1 \end{pmatrix}, \quad s_1 = \begin{pmatrix} 1 & & \\ & -1 & \\ & & 1\end{pmatrix}. $$
We can see the semidirect product structure by defining $t = s_0 s_1$, then we have $s_1 t^k = t^{-k} s_1$, and the Weyl group is the semidirect product of $\mathbb{Z}$ (generated by $t$) and $\mathbb{Z}_2$ (generated by $s_1$). In terms of matrices, we have
$$ t^k = \begin{pmatrix} 1 & -k & -k^2 \\ & 1 & 2k \\ & & 1 \end{pmatrix}.$$
A little computation shows that
$$ t^k \rho - \rho = (-k - 2k^2)\delta + 4k \varpi_1, \quad s_1 t^k \rho - \rho = (-k -2k^2) \delta + (-4k - 2) \varpi_1.$$
Therefore letting $q = e^{-\delta}$ and $r = e^{\alpha_1} = e^{2 \varpi_1}$ we get
$$ \begin{aligned}
\sum_{w \in W} (-1)^w e^{w \rho - \rho}
&= \sum_{k \in \mathbb{Z}}(e^{t^k \rho - \rho} - e^{s_1 t^k \rho - \rho}) \\
&= \sum_{k \in \mathbb{Z}}q^{k + 2k^2}r^{2k} - \sum_{k \in \mathbb{Z}}q^{k + 2k^2}r^{-2k-1} \\
&= \sum_{l \in 2\mathbb{Z}} q^{(l^2 + l)/2} r^l - \sum_{l \in 2\mathbb{Z} + 1}q^{(l^2 - l)/2} r^{-l} \\
&= \sum_{l \in 2\mathbb{Z}} q^{(l^2 + l)/2} r^l - \sum_{l \in 2\mathbb{Z} + 1}q^{(l^2 + l)/2} r^{l} \\
&= \sum_{l \in \mathbb{Z}} (-1)^l q^{(l^2 + l)/2} r^l.
\end{aligned}$$
The first equality is using the semidirect product fact, the third  equality is reindexing the first sum over even integers $l = 2k$ and the second sum over odd integers $l = 2k + 1$, and the fourth equality is using the $l \mapsto -l$ symmetry in the second sum. The final answer is equivalent to yours because I used $r = e^{\alpha_1}$ rather than $r = e^{- \alpha_1}$.

A: +) Your $s_0$ should be $s_0(\rho)=\rho-\langle \rho,\alpha_0^{\vee}\rangle \alpha_0=\rho-\alpha_0=\rho+\alpha_1-\delta$.
+) The Weyl group $W\cong \mathbb{Z} \rtimes S_2$ is generated by $1\in \mathbb{Z}$ (which is $s_0s_1$) and $s\in S_2$ (which is $s_1$).
In other words, its elements are of the form $\{s_1(s_0s_1)^m,(s_0s_1)^m\}$.
One can show $(s_0s_1)^m:\rho \mapsto \rho+2m\alpha_1-(2m^2+m)\delta$ and $s_1(s_0s_1)^m:\rho\mapsto \rho-(2m+1)\alpha_1-(2m^2+m)\delta$.
+) Summing over all elements in the Weyl group we get the desired answer.


text:
Q: Sum on a specific day obeying a status I have a table that applies the following format:
   Date    Value    Situation
01/01/2015  $100     Expected
01/01/2015  $150     Paid - Cash
01/02/2015  $100     Expected
01/06/2015  $200     Paid - Credit card

Where I update the status by a dropdown menu as the values become real.
And I also have a database which has day and value cells. I found around here a way to sum the values per day (btw, thank you logan and chuff). But I'm having headaches to sum the values obeying the dates AND ALSO the status.
In the database where there are cells indicating the day and values, I have the following formula:
{=SUM(IF(AND((DAY(IncomeJan[Date])=DAY(A1));IncomeJan[Status]<>"Expected");IncomeJan[Value];0))}

And it returns the value 0.
I need to sum only real values. And to avoid creating multiple IFs to specify the payment method, I would like to sum only the values that follow a specific day and contains in status the word 'Paid'.
Thanks in advance!

A: Hopefully:
=SUMIFS(B:B,A:A,A2,C:C,"=*Paid*")

meets the requirement to "I want to get all entries for a specific day that meet the status "Paid" and sum them".
Available for Excel 2007 and later, the SUMIFS syntax is:

SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2], ...)

The sum_range, switched to be the first parameter rather than the last for SUMIF, is the Value column (here assumed to be ColumnB), one criteria range (criteria_range1) is Date(so assumed to be ColumnA) with A2 (criteria1) taken as an example of the required specific date (assumed to be 01/01/2015 = in part because not clear from the question whether the date examples are US style or UK style, though likely US), one additional criterion range (there could be more) is (criteria_range2) that theSituation column (assumed to be ColumnC) contains Paid.  This last criterion (criteria2) wraps Paid in wildcards (*) so that it triggers wherever Paid may be found in any one Situation cell, even if there surrounded by other text.
Based on the sample, the above formula returns $150 since that is the only entry shown as Paid on 01/01/2015 but would return $350 were the date of the last entry in the sample changed to 01/01/2015.
The Dates need not be date/time indexes (numeric) but could be strings.

A: If you use sumproducts as an array forumla you can sum based on multiple If statements.
=sumproducts(IF(x1:x10=y,1,0),z1:z10)

So if the IF is not meet the z value is timed by 0, therefore equals 0, otherwise by 1 and the Z value will be evaluated; You can add additional IF. So can have a If for date and a if for "paid".


text:
Q: How to stop/relaunch docker container without losing the changes? I did the following and lost all the changed data in my Docker container.

*

*docker build -t <name:tag> .

*docker run *-p 8080:80* --name <container_name> <name:tag>

*docker exec (import and process some files, launch a server to host them)

Then I wanted to run it on a different port. docker stop & docker run does not work. Instead I did

*docker stop

*docker rm <container_name>

*docker run (same parameters as before)

After the restart I saw the changes that happened in the container at 1-3 had disappeared, and had to re-run the import.
How do I do this correctly next time?

A: Every time you do a docker run it will spin up a fresh container based on your image. And once a container is started, there are very few things that docker allows you to change with the docker update. So instead, you should preserve your data in an external volume that needs to persist between instances of a container. E.g.
docker run -p 8080:80 -v app-data:/data --name <container_name> <name:tag>

The volume name (app-data) and mount point in the container (/data) can be changed for your own requirements. Then when you destroy and restart a new container, you can mount the same volume in the new container.

A: what you have to do is build the image from the container you just stopped after making changes. Because your old command still using the old image which doesn't have new changes(you have made changes in container which you just stopped not in image )
docker commit --help

Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

docker commit -a me new_nginx  myrepo/nginx:latest
then you can start container with the new image you just built
but if you dont want create image with the changes you made(like you dont want to put config containing password in the image) you can use volume mount
docker run -d -P --name web -v /src/webapp:/webapp training/webapp python app.py
This command mounts the host directory, /src/webapp, into the container at /webapp. If the path /webapp already exists inside the container's image, the /src/webapp mount overlays but does not remove the pre-existing content. Once the mount is removed, the content is accessible again. This is consistent with the expected behavior of the mount command.
Manage data in containers


text:
Q: Mitchell's Embedding Theorem for not-necessarily-small categories Mitchell's Embedding Theorem states that if $\mathcal{A}$ is a small abelian category, then there is a ring $R$ and a fully-faithful exact functor $F:\mathcal{A}\rightarrow R\mathsf{Mod}$.
To what extent does this still hold if $\mathcal{A}$ is not-necessarily-small?  Does it still hold in general?  Do we need to impose extra hypotheses?

A: Freyd proved in his paper Concrenteness (1973) that an abelian category which admits a faithful exact functor to $\mathsf{Ab}$ is well-powered; actually also the converse. There are abelian categories which are not well-powered, see MO/93853. Another example is mentioned in the foreword of the tac reprint of Freyd's book Abelian categories (2003) with details in his paper Stable homotopy (1966): The stable homotopy category embeds fully faithfully into an abelian category (which thus is not concretizable).


text:
Q: CSS Transitions not finishing before next? Fiddle: http://jsfiddle.net/wczTW/1/
Basically, I have a set of elements that I'm moving up and down.  Think "Cover Flow" except vertical (Yuck, I know).  It works great unless you hit up or down really quick, in which case it seems that the CSS transition starts before the last one finished and they begin to get too close together.  I'm not even 100% sure that's what's going on, but if you play with the fiddle above for a couple seconds you should see what I'm talking about.
Relevant CSS:
        .game {
            position: absolute;
            width: 150px;
            height: 100px;
            left: 200px;
            margin-left: -125px;
            background-color: gray;
            border: 1px solid white;
            -webkit-transition: all .2s ease-in-out;
            -webkit-transform: scale(1);
            overflow: hidden;
            z-index: 10;
        }

        .selected {
            transform-origin: 0 0;
            border: 1px solid green;
            -webkit-transition: all .2s ease-in-out;
            -webkit-transform: scale(1.25);
            z-index: 100;
        }

Relevant Javascript:
        $(document).ready(function () {
            keyDown = false;
            lTop = ($(window).height() / 2) - 50;

            $('.game').each(function () {
                $(this).css('top', lTop);
                lTop += 120;
            });
        });

        $(document).keydown(function (e) {
            if (!keyDown) {
                if (e.keyCode == 40) { //down
                    var selected = $('.selected');
                    var next = selected.next()
                    if (next.length) {
                        selected.removeClass('selected');
                        next.addClass('selected');
                        $('.game').css('top', function (i, v) {
                            return (parseFloat(v) - 120) + 'px';
                        });
                    }
                    keyDown = true;
                } else if (e.keyCode == 38) { //up
                    var selected = $('.selected');
                    var next = selected.prev()
                    if (next.length) {
                        selected.removeClass('selected');
                        next.addClass('selected');
                        $('.game').css('top', function (i, v) {
                            return (parseFloat(v) + 120) + 'px';
                        });
                    }
                    keyDown = true;
                }
            }
        });

        $(document).keyup(function (e) {
            keyDown = false;
        });

Is there a simple way to queue CSS transitions?  Or block input until the current transition is done?
edit: I think I would much prefer just aborting the animation and moving it immediately, if possible.  The two options above would be bad user experience I think.

A: What's happening is that the keypresses are happening before the top CSS value has updated to its new value, so the v variable is not what you're expecting. One way to fix would be to use setTimeout() to prevent keypresses until the animation is done, but the better way would be to use another way to calculate the top value. I'm putting together a fiddle for you.
FIDDLE HERE http://jsfiddle.net/wczTW/2/
Here's your new javascript:
        var currentTop, lTop, keyDown;

        $(document).ready(function () {
            keyDown = false;
            currentTop = lTop = ($(window).height() / 2) - 50;
                            console.log(lTop);

            $('.game').each(function () {
                $(this).css('top', lTop);
                lTop += 120;
            });
        });

        var index = 0;
        $(document).keydown(function (e) {
            var selected = $('.selected');
            if (!keyDown) {
                if (e.keyCode == 40) { //down
                    var next = selected.next()
                    if (next.length) {
                        index++;
                        selected.removeClass('selected');
                        next.addClass('selected');

                        $('.game').css('top', function (i, v) {
                            return ((i * 120) - (index * 120) + currentTop) + 'px';
                        });
                    }
                    keyDown = true;
                } else if (e.keyCode == 38) { //up
                    var next = selected.prev()
                    if (next.length) {
                        index--;
                        selected.removeClass('selected');
                        next.addClass('selected');
                        $('.game').css('top', function (i, v) {
                            return ((i * 120) - (index * 120) + currentTop) + 'px';
                        });
                    }
                    keyDown = true;
                }
            }
        });

        $(document).keyup(function (e) {
            keyDown = false;
        });

So what I changed is:

*

*Added a new variable currentTop that is the value that we always want the .selected item to be at

*Changed the $('.game').css() so that it doesn't use v to calculate the new top, it now calculates it based on the i variable (which is the index of that item) and a new index variable

*Added the index variable, which keeps track of which index is currently selected. This works using index++ and index-- on keypress.


text:
Q: STAX to modify a nested XML with conditions and write back for Huge XML- around 6 GB I am a beginner to java and have been working on a code to unzip a zip file containing around 100 000 XML files and then merging those files into 1 XML file so that I can process one file instead of loading these many files.
I unzipped the file and merged it into 1 file and parsed using DOM parser but now I need to modify this Merged XML file and then write it back in 1 file. I am able to do it using DOM parser and StringBuilder but looks like StringBuilder is not able to handle this big file as it gives java heap space error.
As I did further research I understood STAX parser might be a good fit to handle large files with better performance.
I have been going through multiple articles and tutorials but could not yet managed to write the code which can suffice my requirement.
So, my XML has multiple tags, after merging I have a structure something like this:
<Items>
   <Item >
      <Tag1>
</Tag1>
         <Tag2>
</Tag2>
            <Images>
               <Image>
                  <width>200</width>
                  <height>200</height>
                  <url>xyz.com</url>
                  <action>update</action>
               </Image>
               <Image>
                  <width>400</width>
                  <height>600</height>
                  <url>xyz.com</url>
                  <action>update</action>
               </Image>
            </Images>
   </Item>
   <Item >
      <Tag1>
</Tag1>
         <Tag2>
</Tag2>
            <Images>
               <Image>
                  <width>100</width>
                  <height>400</height>
                  <url>abc.com</url>
                  <action>update</action>
               </Image>
               <Image>
                  <width>400</width>
                  <height>200</height>
                  <url>xyz.com</url>
                  <action>update</action>
               </Image>
            </Images>
   </Item>
</Items>

My requirement is to check if width and height under Image tag is greater than some value then only take Image Tag else delete it from Images section.
Same way some other tags I will need to remove from the file and once all the processing is done return the whole XML file back with changes.
I went through many articles for STAX implementation but I could not get myself clear on how to access Image tag which is kind of great grandchild of root tag <Items>.

A: It's very easy using XSLT 3.0 streaming:
<xsl:mode streamable="yes" on-no-match="shallow-copy"/>
<xsl:template match="Image">
  <xsl:variable name="image" select="copy-of(.)"/>
  <xsl:sequence select="$image[width*height gt 100000]"/>
</xsl:template>

Of course you could use any predicate here on width and height. The stylesheet outputs the image if and only if the predicate is true.
However, if you've got 6Gb of XML distributed over 100K files then I'm not sure why you're concatenating them before processing. That's going to be much more memory-intensive than processing them individually (which can also be done with a few lines of XSLT code).


text:
Q: VSCode, Intellisense C++ Autocomplete not working, ubuntu 20.04 I have installed Vscode under ubuntu 20.04. I cannot code without having intellisense autocomplete. But it is not working. I have used autocomplete in previous ubuntu LTS(16.04 , 18.04) with no problem.
I have configured c_cpp_properties.json.
    {
    "configurations": [
        {
            "name": "Linux",
            "browse": {
                "path": [
                    "/usr/include",
                    "/usr/include/x86_64-linux-gnu/qt5",
                    "/usr/include/pcl",
                    "/usr/include",
                    "/usr/lib",
                    "/usr/share"
                ],
                "limitSymbolsToIncludedHeaders": true
            },
            "includePath": [
                "/home/atas/colcon_ws/src/ROS_CB/chiconybot_ui/include/",
                "/home/atas/colcon_ws/build/chiconybot_ui/",
                "/usr/include/opencv4/",
                "/opt/ros/foxy/include/",
                "/usr/include/",
                "/usr/include/x86_64-linux-gnu/qt5/"
            ],
            "defines": [],
            "compilerPath": "/usr/bin/gcc",
            "cStandard": "c11",
            "cppStandard": "c++17",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

The header files are found correctly. I also installed all necessary extensions from VSCode marketplace.

I followed steps for configuring settings.json herelink
Finally, my settings.json looks like;
{
    "files.associations": {
        "cctype": "cpp",
        "cmath": "cpp",
        "csignal": "cpp",
        "cstdarg": "cpp",
        "cstddef": "cpp",
        "cstdio": "cpp",
        "cstdlib": "cpp",
        "cstring": "cpp",
        "ctime": "cpp",
        "cwchar": "cpp",
        "cwctype": "cpp",
        "atomic": "cpp",
        "strstream": "cpp",
        "chrono": "cpp",
        "cstdint": "cpp",
        "initializer_list": "cpp",
        "iosfwd": "cpp",
        "mutex": "cpp",
        "ratio": "cpp",
        "system_error": "cpp",
        "thread": "cpp",
        "cinttypes": "cpp",
        "typeindex": "cpp",
        "deque": "cpp",
        "vector": "cpp",
        "array": "cpp",
        "*.tcc": "cpp",
        "bitset": "cpp",
        "clocale": "cpp",
        "complex": "cpp",
        "condition_variable": "cpp",
        "list": "cpp",
        "unordered_map": "cpp",
        "exception": "cpp",
        "fstream": "cpp",
        "functional": "cpp",
        "iomanip": "cpp",
        "iostream": "cpp",
        "istream": "cpp",
        "limits": "cpp",
        "memory": "cpp",
        "new": "cpp",
        "ostream": "cpp",
        "numeric": "cpp",
        "sstream": "cpp",
        "stdexcept": "cpp",
        "streambuf": "cpp",
        "type_traits": "cpp",
        "tuple": "cpp",
        "typeinfo": "cpp",
        "utility": "cpp",
        "valarray": "cpp",
        "*.ipp": "cpp",
        "codecvt": "cpp",
        "future": "cpp",
        "hash_map": "cpp",
        "hash_set": "cpp",
        "core": "cpp",
        "dense": "cpp",
        "numericaldiff": "cpp",
        "unordered_set": "cpp",
        "algorithm": "cpp",
        "cfenv": "cpp",
        "random": "cpp",
        "optional": "cpp",
        "string_view": "cpp",
        "iterator": "cpp",
        "map": "cpp",
        "memory_resource": "cpp",
        "set": "cpp",
        "string": "cpp",
        "slist": "cpp",
        "shared_mutex": "cpp",
        "forward_list": "cpp",
        "qvboxlayout": "cpp",
        "qstringlist": "cpp",
        "qspinbox": "cpp",
        "qstatusbar": "cpp",
        "qpushbutton": "cpp",
        "qcombobox": "cpp",
        "qgraphicsopacityeffect": "cpp",
        "qmovie": "cpp",
        "qtimer": "cpp",
        "qpainter": "cpp",
        "qwidget": "cpp",
        "qtwidgets": "cpp",
        "regex": "cpp",
        "qhostaddress": "cpp",
        "qaction": "cpp",
        "qlayout": "cpp",
        "qframe": "cpp",
        "qlayoutitem": "cpp",
        "qsize": "cpp",
        "qset": "cpp"
    },
    "editor.formatOnSave": true,
    "python.pythonPath": "/usr/bin/python3",
    "git.ignoreLimitWarning": true,
    // Controls if quick suggestions should show up while typing
    "editor.quickSuggestions": {
        "other": true,
        "comments": false,
        "strings": false
    },
    // Controls whether suggestions should be accepted on commit characters. For example, in JavaScript, the semi-colon (`;`) can be a commit character that accepts a suggestion and types that character.
    "editor.acceptSuggestionOnCommitCharacter": true,
    // Controls if suggestions should be accepted on 'Enter' - in addition to 'Tab'. Helps to avoid ambiguity between inserting new lines or accepting suggestions. The value 'smart' means only accept a suggestion with Enter when it makes a textual change
    "editor.acceptSuggestionOnEnter": "on",
    // Controls the delay in ms after which quick suggestions will show up.
    "editor.quickSuggestionsDelay": 10,
    // Controls if suggestions should automatically show up when typing trigger characters
    "editor.suggestOnTriggerCharacters": true,
    // Controls if pressing tab inserts the best suggestion and if tab cycles through other suggestions
    "editor.tabCompletion": "on",
    // Controls whether sorting favours words that appear close to the cursor
    "editor.suggest.localityBonus": true,
    // Controls how suggestions are pre-selected when showing the suggest list
    "editor.suggestSelection": "recentlyUsed",
    // Enable word based suggestions
    "editor.wordBasedSuggestions": true,
    // Enable parameter hints
    "editor.parameterHints.enabled": true,
    "cmake.configureOnOpen": false,
}

I cannot think of a reason why the autocomplete wont work now. Please see whether you spot a mistake. Let me know in comments if more information is needed.
Thank you

A: Turns out that some problem related to VSCode itself. I checked for the new updates on help -> Check for Updates , after a new update things get back to normal. The current version that works is ;


text:
Q: Relation betwwen the expectation value of the position operator in Bloch state with unitary position operator Recently, I want to get some knowledge about topological insulators, so I read the A short course on topological insulators. In the chapter 3, the author try to explain why polarization connects with Berry phase. Author show a unitary position operator:

Then he show the connection between the expectation value of the position operator in Bloch State with the phase of the expectation value of X, but I cannot get the some result

In my way, I think the $|m\rangle$ just mean the atomic orbital wave functions in the mth unit cell, then I would get $\langle\Psi|\hat{X}|\Psi\rangle=0$. I don't know how to get this relation, wish you can help me.


text:
Q: VBA DoCmd.TransferSharePointList Not Linking I have an Access 2010 tool that I created that links to some SharePoint lists. This solution was working fine until my end users decided they needed more People/Group fields which put us over the view threshold for lookups. I do not have access to central administration so this is a hard stop. So I decided that I could link to three views and join the data with a query and all should be good. To be able to link to a SharePoint list view you have to use DoCmd.TransferSharePointList instead of using the External Data option. External Data links to the entire table thus the threshold prevents data from being returned.
I need to link to three views so my code is:
 Function SPVLink()

DoCmd.TransferSharePointList acLinkSharePointList, "http://server/sites/sitename/", "{94E4E5D3-77C8-4170-BBA2-3F9533C24627}", "{CF2A3189-B45B-4527-A4F3-CF323C9E7E21}", "IssueTracker0", True
DoCmd.TransferSharePointList acLinkSharePointList, "http://server/sites/sitename/", "{94E4E5D3-77C8-4170-BBA2-3F9533C24627}", "{C6C7ABBA-C159-400F-8402-F6B56954BA5C}", "IssueTracker1", True
DoCmd.TransferSharePointList acLinkSharePointList, "http://server/sites/sitename/", "{94E4E5D3-77C8-4170-BBA2-3F9533C24627}", "{290947AD-8BC4-4610-82C1-E636CFBBF06C}", "IssueTracker2", False

 End Function

This runs without error however the linked views are not created. I also tried running this as a Macro and the result is the same in that it runs with no error yet no links are created. I did some searching but didn't find this kind of issue.
Any help would be greatly appreciated.

A: DoCmd.TransferSharePointList in VBA will not let you link to multiple views.
acLinkSharePointList will link to the entire list like External Data does.
acImportSharePointList will let you import only the data displayed in the associated view.
Because the database was already linked to the lists it would not create new links with different names.


text:
Q: Table builder rails gem only displaying 5 dates Im using the table builder gem in my Rails app and its working fine but only displaying 5 events per month.. Any clue why?
https://github.com/watu/table_builder

    <%= link_to "<", :month => (@date.beginning_of_month-1).strftime("%Y-%m") %>
    <%=h @date.strftime("%B %Y") %>
    <%= link_to ">", :month => (@date.end_of_month+1).strftime("%Y-%m") %>

  <%= calendar_for @occasions, :year => @date.year, :month => @date.month do |calendar| %>
    <%= calendar.head('sun','mon', 'tue', 'wed', 'thu', 'fri', 'sat') %>
    <%= calendar.day(:day_method => :dateg) do |date, occasions| %>
      <%= date.day %>
      <% occasions.each do |occasion| %>
        <%= h(occasion.pname) %><%= '\'s' %> <%= h(occasion.name) %>
      <% end %>
    <% end %>
  <% end %>