text:
Q: Case statement not working for all conditions with member test as
case
  when ([All Products].[All Products].[Group 2].&[1],[Measures].[minus-prod-trx])>0
  then (ancestor([All Products].[All Products].[Group 2].&[1],2),[Measures].[minus-prod-trx])
   when ([All Products].[All Products].[Group 2].&[2],[Measures].[minus-prod-trx])>0
  then (ancestor([All Products].[All Products].[Group 2].&[2],2),[Measures].[minus-prod-trx])
end

Problem: How can I get both the values for if above both conditions satisfies? Now only one result returning though both condition satisfies. I tried with:
case
  when [All Products].[Group 2].CURRENTMEMBER IS [All Products].[Group 2].&[1]
  then...

But it's not working.

A: Assuming this hierarchy is ON ROWS:
[All Products].[All Products]

Then something like the following:
WITH MEMBER [Measures].test AS
  CASE
    WHEN
     [All Products].[All Products].CURRENTMEMBER
         IS [All Products].[All Products].[Group 2].&[1]
       AND [Measures].[minus-prod-trx] > 0
         THEN
          (ancestor([All Products].[All Products].[Group 2].&[1],2),[Measures].[minus-prod-trx])
   WHEN
     ....

Here is an example of the above in use against MS's AdvWrks cube:
WITH
  MEMBER [Measures].test AS
    CASE
      WHEN
            [Product].[Product Categories].CurrentMember
          IS
            [Product].[Product Categories].[Product].[Hitch Rack - 4-Bike]
        AND
          [Measures].[Internet Sales Amount] > 0
      THEN
        (
          Ancestor
          (
            [Product].[Product Categories].[Product].[Hitch Rack - 4-Bike]
           ,2
          )
         ,[Measures].[Internet Sales Amount]
        )
      WHEN
            [Product].[Product Categories].CurrentMember
          IS
            [Product].[Product Categories].[Product].[Road Bottle Cage]
        AND
          [Measures].[Internet Sales Amount] > 0
      THEN
        (
          Ancestor
          (
            [Product].[Product Categories].[Product].[Road Bottle Cage]
           ,3
          )
         ,[Measures].[Internet Sales Amount]
        )
    END
SELECT
  NON EMPTY
    {
      [Measures].[Internet Sales Amount]
     ,[Measures].test
    } ON 0
 ,[Product].[Product Categories].[Product] ON 1
FROM [Adventure Works];

Results in the following:

In comments you put the following
with member [Measures].Test as
case
when [Dim Date].[Hierarchy].currentmember
  IS [Dim Date].[Hierarchy].[Calendar Year].&[2007].&[1].&[2]
    then (ancestor([Dim Date].[Hierarchy].[Calendar Year].&[2007].&[1].&[2],2),[Measures].[Amount]) end
select {[Measures].Test} on 0
from [My Adventure Works];

This code looks ok to me. [Dim Date].[Hierarchy].currentmember is not equal to the member you have specified in the above - currentmember looks at each row of the output and returns the current member but in the above you do not have  this hierarchy on your rows ... so the currentmember is the All member so your WHEN condition is false.
Sourav has fixed the above for you by creating the context so that currentmember returns a member other than the All member of the hierarchy:
with member [Measures].Test as
case
when [Dim Date].[Hierarchy].currentmember
  IS [Dim Date].[Hierarchy].[Calendar Year].&[2007].&[1].&[2]
    then (ancestor([Dim Date].[Hierarchy].[Calendar Year].&[2007].&[1].&[2],2),[Measures].[Amount]) end
select
   {[Measures].Test} on 0,
    [Dim Date].[Hierarchy].[Calendar Year].&[2007].&[1].&[2] on 1 //<<including this means that the currentmember has something to work with!!
from [My Adventure Works];

Please have a read of the definition of the currentmember function: https://msdn.microsoft.com/en-us/library/ms144948.aspx


text:
Q: What is the point of delays on redstone repeaters? I think that redstone in Minecraft is quite confusing, so I'm learning about it. Then I came across redstone repeaters. I read about them and it says they repeat signals and can delay ticks. What does that do (and what does it mean)?

A: The delay just increases the time for the propagation of a redstone signal which can be anywhere from 1 to 4 redstone ticks. A redstone tick is defined as:

A redstone tick describes two game ticks. This creates a 1/10 of a
  second delay in the signal of a redstone circuit. That is, the
  signal's time to travel from a location A to location B is increased
  by 0.1 seconds. A tick only pertains to the increase in signal time,
  thus, a signal's travel time can never be decreased in reference to
  ticks.

You can use this delay to your advantage to create things like a clock signal, pulse generators, or just use it to have different components react at different times like having having one dispenser fire 0.5 seconds after another. There's a lot that's possible so just play around with it and see what you come up with.

A: Repeating a redstone signal.
Think of a signal as in sending power to a redstone circuit.
Every redstone signal can travel up to 15 blocks before running out of power.
So basically every signal has a power level of 0-15. A repeater resets the signal back to maximum power[15]. That way you can extend the signal on  redstone circuits that are longer than 15 blocks.
Delaying signals.
In minecraft, 20 ticks happen each second, so one tick happens every
0.05 seconds.
There is another type of ticks in minecraft, called a redstone tick.
Every redstone tick is equal to 2 game ticks(0.1 seconds).
Redstone ticks occur during redstone operations.
A repeater, by default, is set to one redstone tick (1/10th of a second delay). You can set it(by right-clicking it) up to 4 redstone ticks (4/10 of a second or 0.4 seconds).

Why would you want to add delays to a signal?

Lets say you made a redstone circuit that activates and deactivates all the redstone lamps in a tunnel, and you want each set of lamps to activate/deactivate with an 1 second delay between each set. You would need to add 2 repeaters on 4 ticks and 1 more repeater at 2 ticks for a total of an 1 second delay.
Obviously, this a very simple way to use redstone repeater delays, but you understand the concept. Delays can be used for redstone clocks, pulse generators and lots more.
More information on the above:

*

*Redstone Repeater

*Minecraft Tick

A: Synchronization and general delays are one thing, but a clock circuit is actually very important. There are blocks that activate on redstone input not constantly, but "on edge", i.e. when it changes from off to on. Most notably droppers and dispensers.
The easiest way to create a pipeline for transporting items upwards (and cheapest that transports in any other direction; hoppers cost a lot of iron) is to line up lots of droppers and power them up with a clock signal.
Another application is with dispenser that doesn't hold any backlog of items: a redstone event is triggered before the item is gathered by a hopper, then deployed by a dispenser fed from that hopper - you need a delay before triggering the dispenser (example: my automatic cow butchery which uses a cactus to break a cart and eject the cow before redeploying the cart.)

A: with a redstone repeater, if the two torches are the closest together, it will have 0.1 sec delay, if the moveable torch is close to the nonmovable one but is close to the center that is a 0.2 sec delay, if they are far away but the moveable one is still close to the middle its a 0.3 sec delay, if they are the furthest away posible thats a 0.4 sec delay

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get OS in c++ win32 for all versions of win? How to get the OS version for all windows, at least the name for win95,98,me,xp,vista,7?
Im using visual c++ 2010 and I want to include this feature in a pure win32 app.

A: How about something like this:
#include <windows.h>
#include <string>
#include <lm.h>
#pragma comment(lib, "netapi32.lib")

bool GetWinMajorMinorVersion(DWORD& major, DWORD& minor)
{
    bool bRetCode = false;
    LPBYTE pinfoRawData = 0;
    if (NERR_Success == NetWkstaGetInfo(NULL, 100, &pinfoRawData))
    {
        WKSTA_INFO_100* pworkstationInfo = (WKSTA_INFO_100*)pinfoRawData;
        major = pworkstationInfo->wki100_ver_major;
        minor = pworkstationInfo->wki100_ver_minor;
        ::NetApiBufferFree(pinfoRawData);
        bRetCode = true;
    }
    return bRetCode;
}

std::string GetWindowsVersionString()
{
    std::string     winver;
    OSVERSIONINFOEX osver;
    SYSTEM_INFO     sysInfo;
    typedef void(__stdcall *GETSYSTEMINFO) (LPSYSTEM_INFO);

    __pragma(warning(push))
    __pragma(warning(disable:4996))
    memset(&osver, 0, sizeof(osver));
    osver.dwOSVersionInfoSize = sizeof(osver);
    GetVersionEx((LPOSVERSIONINFO)&osver);
    __pragma(warning(pop))
    DWORD major = 0;
    DWORD minor = 0;
    if (GetWinMajorMinorVersion(major, minor))
    {
        osver.dwMajorVersion = major;
        osver.dwMinorVersion = minor;
    }
    else if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2)
    {
        OSVERSIONINFOEXW osvi;
        ULONGLONG cm = 0;
        cm = VerSetConditionMask(cm, VER_MINORVERSION, VER_EQUAL);
        ZeroMemory(&osvi, sizeof(osvi));
        osvi.dwOSVersionInfoSize = sizeof(osvi);
        osvi.dwMinorVersion = 3;
        if (VerifyVersionInfoW(&osvi, VER_MINORVERSION, cm))
        {
            osver.dwMinorVersion = 3;
        }
    }

    GETSYSTEMINFO getSysInfo = (GETSYSTEMINFO)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetNativeSystemInfo");
    if (getSysInfo == NULL)  getSysInfo = ::GetSystemInfo;
    getSysInfo(&sysInfo);

    if (osver.dwMajorVersion == 10 && osver.dwMinorVersion >= 0 && osver.wProductType != VER_NT_WORKSTATION)  winver = "Windows 10 Server";
    if (osver.dwMajorVersion == 10 && osver.dwMinorVersion >= 0 && osver.wProductType == VER_NT_WORKSTATION)  winver = "Windows 10";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 3 && osver.wProductType != VER_NT_WORKSTATION)  winver = "Windows Server 2012 R2";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 3 && osver.wProductType == VER_NT_WORKSTATION)  winver = "Windows 8.1";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2 && osver.wProductType != VER_NT_WORKSTATION)  winver = "Windows Server 2012";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 2 && osver.wProductType == VER_NT_WORKSTATION)  winver = "Windows 8";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1 && osver.wProductType != VER_NT_WORKSTATION)  winver = "Windows Server 2008 R2";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 1 && osver.wProductType == VER_NT_WORKSTATION)  winver = "Windows 7";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0 && osver.wProductType != VER_NT_WORKSTATION)  winver = "Windows Server 2008";
    if (osver.dwMajorVersion == 6 && osver.dwMinorVersion == 0 && osver.wProductType == VER_NT_WORKSTATION)  winver = "Windows Vista";
    if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2 && osver.wProductType == VER_NT_WORKSTATION
        &&  sysInfo.wProcessorArchitecture == PROCESSOR_ARCHITECTURE_AMD64)  winver = "Windows XP x64";
    if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 2)   winver = "Windows Server 2003";
    if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 1)   winver = "Windows XP";
    if (osver.dwMajorVersion == 5 && osver.dwMinorVersion == 0)   winver = "Windows 2000";
    if (osver.dwMajorVersion < 5)   winver = "unknown";

    if (osver.wServicePackMajor != 0)
    {
        std::string sp;
        char buf[128] = { 0 };
        sp = " Service Pack ";
        sprintf_s(buf, sizeof(buf), "%hd", osver.wServicePackMajor);
        sp.append(buf);
        winver += sp;
    }

    return winver;
}

A: Use GetVersionEx
http://msdn.microsoft.com/en-us/library/ms724451%28v=VS.85%29.aspx

A: I had a similar problem. Here is some code with Win 11 support. It won't work for server versions, but it is easy to implement add this feature (just another mapping for servers).
 // To Workaround Win 10 problem for User Mode VerifyVersionInfo
bool VerifyWindowsVersionInfo(PRTL_OSVERSIONINFOEXW versionInfo, ULONG typeMask, ULONGLONG conditionMask)
{
    HMODULE hMod = nullptr;
    if ((TRUE != ::GetModuleHandleEx(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"ntdll.dll", &hMod)) || !hMod)
        return false;

    typedef NTSTATUS(WINAPI* _RtlVerifyVersionInfo)(PRTL_OSVERSIONINFOEXW, ULONG, ULONGLONG);
    const auto RtlVerifyVersionInfo =
        reinterpret_cast<_RtlVerifyVersionInfo>(::GetProcAddress(hMod, "RtlVerifyVersionInfo"));

    if (!RtlVerifyVersionInfo)
        return false;

    return NT_SUCCESS(RtlVerifyVersionInfo(versionInfo, typeMask, conditionMask));
}

bool IsWindowsVersionOrGreater(int wMajorVersion, int wMinorVersion, int wBuildNumber, int wServicePackMajor)
{
    RTL_OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
    osvi.dwMajorVersion = wMajorVersion;
    osvi.dwMinorVersion = wMinorVersion;
    osvi.dwBuildNumber = wBuildNumber;
    osvi.wServicePackMajor = static_cast<WORD>(wServicePackMajor);

    DWORDLONG dwlConditionMask = 0;
    VER_SET_CONDITION(dwlConditionMask, VER_MAJORVERSION, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_MINORVERSION, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_BUILDNUMBER, VER_GREATER_EQUAL);
    VER_SET_CONDITION(dwlConditionMask, VER_SERVICEPACKMAJOR, VER_GREATER_EQUAL);

    return VerifyWindowsVersionInfo(&osvi,
        VER_MAJORVERSION | VER_MINORVERSION | VER_BUILDNUMBER | VER_SERVICEPACKMAJOR,
        dwlConditionMask);

}

std::wstring GetVerbalOsVersion()
{
    // see https://msdn.microsoft.com/ru-ru/library/windows/desktop/ms724832(v=vs.85).aspx for details
    using OsMajorVersion = int;
    using OsMinorVersion = int;
    using OsBuildVersion = int;
    using OsServicePackMajorVersion = int;

    using VersionStrWithNumberPair =
        std::pair<std::wstring, std::tuple<OsMajorVersion, OsMinorVersion, OsBuildVersion, OsServicePackMajorVersion>>;

    const auto win11BuildNumber = 22000;

    const std::vector<VersionStrWithNumberPair> winVersionMapping = {
        {L"Windows 11 ",
         std::make_tuple(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), win11BuildNumber, 0)},
        {L"Windows 10 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN10), LOBYTE(_WIN32_WINNT_WIN10), 0, 0)},

        {L"Windows 8.1", std::make_tuple(HIBYTE(_WIN32_WINNT_WINBLUE), LOBYTE(_WIN32_WINNT_WINBLUE), 0, 0)},
        {L"Windows 8 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN8), LOBYTE(_WIN32_WINNT_WIN8), 0, 0)},

        {L"Windows 7  Service Pack 1", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0, 1)},
        {L"Windows 7 ", std::make_tuple(HIBYTE(_WIN32_WINNT_WIN7), LOBYTE(_WIN32_WINNT_WIN7), 0, 0)},

        {L"Windows Vista Service Pack 2",
         std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 2)},
        {L"Windows Vista Service Pack 1",
         std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 1)},
        {L"Windows Vista", std::make_tuple(HIBYTE(_WIN32_WINNT_VISTA), LOBYTE(_WIN32_WINNT_VISTA), 0, 0)},

        {L"Windows XP  Service Pack 3",
         std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 3)},
        {L"Windows XP Service Pack 2",
         std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 2)},
        {L"Windows XP Service Pack 1",
         std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 1)},
        {L"Windows XP ", std::make_tuple(HIBYTE(_WIN32_WINNT_WINXP), LOBYTE(_WIN32_WINNT_WINXP), 0, 0)} };

    const auto it = std::find_if(std::begin(winVersionMapping),
        std::end(winVersionMapping),
        [](const VersionStrWithNumberPair& el)
        {
            return IsWindowsVersionOrGreater(std::get<0>(el.second),
                std::get<1>(el.second),
                std::get<2>(el.second),
                std::get<3>(el.second));
        });

    if (it == std::end(winVersionMapping))
        return L"Unknown windows version";

    return it->first;
}

A: Take a look at the MSDN article Getting the System Version
While the article only mentions currently supported Windows versions, see this knowledge base article for the numbers you'll see in the  OSVERSIONINFO structure for Win 95, 98 etc.

A: It all depends on why you need to know OS version:

*

*To use certain feature that may not be available in older OS. In this case I would strongly suggest checking if the API itself is available using LoadLibrary and GetProcAddress functions. Otherwise, I guess you can dynamically import RtlGetVersion from ntdll.dll and use it, but again, there're too many ways it can return inaccurate information (the ones that come to mind are compatibility mode and API trampolines that can be installed by malware, AVP, and even OS itself.)

*For display purposes only. (ex: in About window for your app, or to include it in your diagnostic event log, etc.) In this case a quick and easy hack is to read it as text from the System Registry:

The downside of this approach though, is that the names and numbers can be localized for the end-user's system.
Use the following key that is available since Windows XP:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion

and its following REG_SZ (or string) values:

*

*ProductName = for OS name

*CurrentVersion = for OS version

*BuildLab = for full build number

*BuildLabEx = extended build number (available since Windows 7)

*ReleaseId = Release number (available since Windows 10)


text:
Q: Alarm Manager won't work when the app is killed in the background and device is locked I have been stuck in this situation for a long time...
I want to use the alarm manager to show notification at the specific time, and now it worked in the situation listed below:

*

*when the app runs in the background, notification will be shown at the correct time, and no matter the device is locked or not.

*after the app has been killed in the background, i will still get correct notification when device is not locked, but things turn wrong when the device is locked, i can't receive any notification.

Here's the code AlarmReceiver.java, all the needed permission has been added into AndroidManifest.xml already:
@Override
public void onReceive(Context context, Intent intent) {
    WakeLocker.acquire(context);

    String action = intent.getAction();

    Log.d(TAG, action); //when app is killed and device is locked, no info is shown at the logcat

    if (ACTION_ALARM.equals(action)) {
        Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        vibrator.vibrate(2 * 1000);

        notify(context, "Jello!");
    }

    WakeLocker.release();
}

public static void alarm(Context context) {
    AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
    Intent intent = new Intent(context, AlarmReceiver.class);
    intent.setAction(ACTION_ALARM);
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 5 * 1000, pi);
    }
}

private void notify(Context context, String msg) {
    NotificationManager notificationManager = (NotificationManager)
            context.getSystemService(Context.NOTIFICATION_SERVICE);

    PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
            new Intent(context, InfoActivity.class), 0);

    Notification notification =
            new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle(context.getString(R.string.alarm))
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                    .setContentText(msg)
                    .setAutoCancel(true)
                    .setContentIntent(contentIntent).build();

    notificationManager.notify(1, notification);
}

Permissions added:
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE"/>

A: I just found the solution, set flag named FLAG_INCLUDE_STOPPED_PACKAGES to intent of the alarm, things will go right.
Here are the illustration in Android Developers

A: I had a similar issue one day and found a solution online, which was wakelocking the phone when the broadcastreceiver was called.
So try creating this class, and calling MyWakeLock.acquire() when the broadcastreceiver gets called. You should also call MyWakeLock.release() when you are done executing whatever your alarm does.
package your.package.name;

import android.content.Context;
import android.os.PowerManager;

public abstract class MyWakeLock {
    private static PowerManager.WakeLock wakeLock;

    public static void acquire(Context c) {
        if (wakeLock != null) wakeLock.release();

        PowerManager pm = (PowerManager) c.getSystemService(Context.POWER_SERVICE);
        wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK |
                PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.ON_AFTER_RELEASE, MainActivity.APP_TAG);
        wakeLock.acquire();
    }

    public static void release() {
        if (wakeLock != null){
            wakeLock.release();
        }
        wakeLock = null;
    }
}

A: i had this problem and finally found wrong targetSdkVersion is above 22 and no handle permission.
set targetSdkVersion 22 and worked ^_^


text:
Q: Refer other properties in Spring expression language I have a field as shown below which works
@Value("#{T(java.util.regex.Pattern).compile('[0-9]+')}")
private Pattern myPattern;

But if I change it to
@Value("#{T(java.util.regex.Pattern).compile(${myProp})}")
private Pattern myPattern;

it does not work. Is there a way to refer properties inside Spring expression?

A: I would guess that the 's are the problem.
I would expect that SpEL handle '${myProp}' as a string but not as a property.
Therefore I would try to remove the 's
See my last comment

I have had a look at my code and found this:
@Value("#{new java.text.SimpleDateFormat('yyyy-MM-dd').parse('${showAfterDate}')}")
-- So '${myProp}' should work


text:
Q: Three.js: Construct plane through points on axes I'm trying to create a plane that passes through (say) 2 on the x-axis, 3 on the y-axis and 12 on the z-axis (in other words, the plane 6x + 4y + z = 12).
I've so far tried creating a horizontal plane and rotating it around the 3 axes using the dot product, which gave me close to the desired plane, but it would never be exactly right.
I suspect I need to use Matrix4, but couldn't find a suitable example.

A: Here's one way to build it, from your example you have three vectors which are multiples of the canonical basis i,j,k e.g.
x = x_0 * [1 0 0]
y = y_0 * [0 1 0]
z = z_0 * [0 0 1]

A plane is defined with two things:

*

*a normal (a vector perpendicular to the plane)

*a distance from the origin to the plane

The normal can be built from the cross product of any two non-parallel vectors that lie on the plane, e.g. y - x and z - x therefore
normal = normalize(cross(y - x, z - x))

Now when the plane is rendered it will have an initial normal N, we can create a quaternion rotates the vector N to normal, I'll use the axis angle form where
q_{axis} = cross(N, normal)
q_{angle} = acos(dot(N, normal))

Next the distance to the plane can be found with the dot product of the normal and any point on the plane e.g.
distance = dot(normal, x)

Note that this is a signed value which is awesome since all you have to do to move the plane is move it distance units in the normal direction
Implementation
var plane = new THREE.Mesh(
  new THREE.PlaneGeometry(10, 10),
  new new THREE.MeshNormalMaterial()
)
// ...
function rotatePlane(x, y, z) {
  var xy = new THREE.Vector3().subVectors(y, x)
  var xz = new THREE.Vector3().subVectors(z, x)
  var normal = new THREE.Vector3().crossVectors(xy, xz).normalize()

  // initial normal vector of the plane
  var Z = new THREE.Vector3(0, 0, 1)
  var axis = new THREE.Vector3().crossVectors(Z, normal).normalize()
  var angle = Math.acos(Z.dot(normal))
  var q = new THREE.Quaternion().setFromAxisAngle(axis, angle)
  plane.rotation.setFromQuaternion(q)

  var distanceToPlane = x.dot(normal)
  plane.position.copy(normal.clone().multiplyScalar(distanceToPlane))
}

Demo
Edit 1: as @WestLangley commented you can use plane.quaternion.setFromUnitVectors( Z, normal ) which under the hood simplifies the quaternion described above by avoiding the use of trig functions among other things, you can read more about the simplification in this awesome article
Edit 2: @WestLangley added a comment about the direction of the normal which is completely valid, in the implementation instead of checking for this I decided to render both faces of the triangles that make the plane, if you also want to make the plane to never look at the origin first you realize from the above equations that if distance is negative that means that the plane moved away from the origin while looking at it, if this happens you need to flip the direction of the normal which also makes distance to always be positive
if (distance < 0) {
  distance *= -1
  normal.multiplyScalar(-1)
}


text:
Q: Is there a way to break out of deeply nested async calls? I have the following pattern in my code.

function serverGet(callback) {
   return callback("this is the real data");
}

function getData(callback) {
   var c1= true, c2, c3, c4; //c1 set to true as illustration to make snippet run
   if (c1) {
      serverGet(function(data) {
       console.log(data);
          return callback(data);  //line 10
      })
    } else {
      //other conditions
      if (c2) {
        //....
      } else {
          if (c3) {
            //....
          } else {
              if (c4) {
                // ....
              } else {
                  // ....
                }
}

function main() {
  getData(function(data) {
    console.log("Finally, the data is: "+data);
  });
}

main();

Is there a way at line 10 to return back to main so as to avoid all those if/else block and deep indentations?

A: Promises are just syntax sugar for callbacks. You can do it in the same way as in case of promises.
On line 10 throw an exception and
a) let it bubble through all callbacks so you will have try/catch block everywhere
b) catch it at top level callback
a) is better because you can do necessary cleanup at all levels


text:
Q: Number of Galois conjugates Let $L/\mathbb Q$ be a (finite) Galois extension of degree $n$ with Galois group $\Gamma$. We know that there is a primitive element or generator $\alpha$ of this extension.
My question:

Is the number of Galois conjugates of $\alpha$ (i.e. the length of the orbit of $\alpha$ under $\Gamma$) smaller than or equal to the order of the Galois group?

And under which conditions are they the same?

A: What does the Orbit-Stabilizer theorem tell us? If $\Gamma = \textrm{Gal}(L/\mathbb{Q})$, then because the extension is finite,
$$
|\Gamma | = |\Gamma \cdot \alpha| \cdot | \textrm{Stab}_{\Gamma}(\alpha)|.
$$
In particular, the number $|\Gamma \cdot \alpha|$ of Galois conjugates of $\alpha$ is less than or equal to the order $|\Gamma|$ of the Galois group. (It will, in fact, be an equality: the stabilizer of $\alpha$ must be trivial, else $\alpha$ would not be a generator.)


text:
Q: I Can't open port 30120 - Ubuntu Server 16.04 I want to host a FiveM server on my VPS, but I'm unable to open a port for this (30120). I've already added a rule to UFW and iptables, but I can't still pass the nmap test. Here is what i got:
Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-06 14:53 CEST
Nmap scan report for localhost (127.0.0.1)
Host is up.
Other addresses for localhost (not scanned): ::1
PORT      STATE    SERVICE
30120/tcp filtered unknown

Nmap done: 1 IP address (1 host up) scanned in 2.04 seconds
root@VPS:~# nmap -sV 30120 localhost

Starting Nmap 7.01 ( https://nmap.org ) at 2017-10-06 14:53 CEST
setup_target: failed to determine route to 30120 (0.0.117.168)
Nmap scan report for localhost (127.0.0.1)
Host is up (0.0000040s latency).
Other addresses for localhost (not scanned): ::1
Not shown: 995 closed ports
PORT     STATE SERVICE VERSION
21/tcp   open  ftp     vsftpd 3.0.3
22/tcp   open  ssh     OpenSSH 7.2p2 Ubuntu 4ubuntu2.2 (Ubuntu Linux; protocol 2.0)
53/tcp   open  domain  ISC BIND 9.10.3-P4-Ubuntu
80/tcp   open  http    Apache httpd 2.4.18 ((Ubuntu))
3306/tcp open  mysql   MySQL 5.5.5-10.0.31-MariaDB-0ubuntu0.16.04.2
Service Info: OSs: Unix, Linux; CPE: cpe:/o:linux:linux_kernel

Service detection performed. Please report any incorrect results at https://nmap.org/submit/ .
Nmap done: 1 IP address (1 host up) scanned in 9.07 seconds

As you can see port 30120 is filtered and the reason for this is that it can't determine route (I'm not sure what does it mean). UFW and netstat -aunt says that I'm already lisening on this port
root@VPS:~# ufw status
Status: active

To                         Action      From
--                         ------      ----
Apache                     ALLOW       Anywhere
Apache Full                ALLOW       Anywhere
22                         ALLOW       Anywhere
9987                       ALLOW       Anywhere
10011                      ALLOW       Anywhere
30033                      ALLOW       Anywhere
25565                      ALLOW       Anywhere
20                         ALLOW       Anywhere
21                         ALLOW       Anywhere
30110                      ALLOW       Anywhere
30120                      ALLOW       Anywhere
3306                       DENY        Anywhere
Apache (v6)                ALLOW       Anywhere (v6)
Apache Full (v6)           ALLOW       Anywhere (v6)
22 (v6)                    ALLOW       Anywhere (v6)
9987 (v6)                  ALLOW       Anywhere (v6)
10011 (v6)                 ALLOW       Anywhere (v6)
30033 (v6)                 ALLOW       Anywhere (v6)
25565 (v6)                 ALLOW       Anywhere (v6)
20 (v6)                    ALLOW       Anywhere (v6)
21 (v6)                    ALLOW       Anywhere (v6)
30110 (v6)                 ALLOW       Anywhere (v6)
30120 (v6)                 ALLOW       Anywhere (v6)
3306 (v6)                  DENY        Anywhere (v6)

And here is the netstat output (xxx.xx.xx.xx - IP adress of my VPS):
root@VPS:~# netstat -aunt
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 0.0.0.0:30120           0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:30033           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:21              0.0.0.0:*               LISTEN
tcp        0      0 xxx.xx.xx.xx:53         0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:53            0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:953           0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:10011           0.0.0.0:*               LISTEN
tcp        0      0 xxx.xx.xx.xx:22         37.47.130.222:4372      ESTABLISHED
tcp        0      0 xxx.xx.xx.xx:22         54.197.3.109:37996      SYN_RECV
tcp        0      0 xxx.xx.xx.xx:22         218.65.30.25:29523      ESTABLISHED
tcp        0    448 xxx.xx.xx.xx:22         37.47.130.222:16716     ESTABLISHED
tcp        0      0 xxx.xx.xx.xx:22         221.194.47.224:53806    TIME_WAIT
tcp        0      0 xxx.xx.xx.xx:22         221.194.47.224:56732    TIME_WAIT
tcp6       0      0 :::80                   :::*                    LISTEN
tcp6       0      0 :::30033                :::*                    LISTEN
tcp6       0      0 :::53                   :::*                    LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 ::1:953                 :::*                    LISTEN
tcp6       0      0 :::10011                :::*                    LISTEN
udp        0      0 xxx.xx.xx.xx:36538      194.97.114.3:2010       ESTABLISHED
udp        0      0 0.0.0.0:9987            0.0.0.0:*
udp        0      0 xxx.xx.xx.xx:2011       194.97.114.3:2010       ESTABLISHED
udp        0      0 xxx.xx.xx.xx:53         0.0.0.0:*
udp        0      0 127.0.0.1:53            0.0.0.0:*
udp6       0      0 :::9987                 :::*
udp6       0      0 0.0.0.0:30120           :::*
udp6       0      0 :::53                   :::*

I also have this port opened in iptables
Chain ufw-user-input (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http /* 'dapp_Apache' */
ACCEPT     tcp  --  anywhere             anywhere             multiport dports http,https /* 'dapp_Apache%20Full' */
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     udp  --  anywhere             anywhere             udp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:9987
ACCEPT     udp  --  anywhere             anywhere             udp dpt:9987
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:10011
ACCEPT     udp  --  anywhere             anywhere             udp dpt:10011
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:30033
ACCEPT     udp  --  anywhere             anywhere             udp dpt:30033
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:25565
ACCEPT     udp  --  anywhere             anywhere             udp dpt:25565
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ftp-data
ACCEPT     udp  --  anywhere             anywhere             udp dpt:20
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ftp
ACCEPT     udp  --  anywhere             anywhere             udp dpt:fsp
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:30110
ACCEPT     udp  --  anywhere             anywhere             udp dpt:30110
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:30120
ACCEPT     udp  --  anywhere             anywhere             udp dpt:30120
DROP       tcp  --  anywhere             anywhere             tcp dpt:mysql
DROP       udp  --  anywhere             anywhere             udp dpt:mysql

Does someone have any idea why this port is still closed?


text:
Q: django translation can't decode in django.po i have this .
msgid "%(message)s come from weixiang http:///www.iweix.cn "
msgstr "%(message)s 来自微X http:///www.iweix.cn"

and in view i have , (i have add # -- coding: utf-8 --) .
sina_weibo_post(self.user,_("%(message)s come from weixiang http:///www.iweix.cn ")%{"message":self.photo.desc},photo_adr)

i got the error:
sina_weibo_post(self.user,_("%(message)s come from weixiang http:///www.iweix.cn")%{"message":self.photo.desc},photo_adr)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 12: ordinal not in range(128)

how can i solve it ?thanks .

A: Please check that you have a header like this, in the po file:
msgid ""
msgstr ""
"Project-Id-Version: 1.0.0\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2013-10-04 13:06-0500\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: XXXXX\n"
"Language-Team: Es XXXX\n"
"Language: Es\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n != 1);\n"

This line is very important:
"Content-Type: text/plain; charset=UTF-8\n"

A: Another possible fix is using ugettext or ugettext_lazy instead of gettext or gettext_lazy if your're using Python 2 and Django <=1.11 as was suggested here: Django Translation UnicodeDecodeError


text:
Q: Jira REST API CALL ISSUE I want to call JIRA REST API in my server.
The first time it is called from my server, it works fine,
but the problem occurs from the second time.
this is issue message image

how to fix this issue ?


text:
Q: Pointers in CPP, confusion regarding an example program Working my way through accelerated c++. There's an example where there are multiple things that I do not understand.
double grade = 88;

static const double numbers[] = { 97,94,90,87,84,80,77,74,70,60,0 };

static const char* const letters[] = { "A+","A","A-","B+","B","B-","C+","C","C-","D","F" };

static const size_t ngrades = sizeof(numbers) / sizeof(*numbers);

for (size_t i = 0;i < ngrades;++i) {
    if (grade >= numbers[i]) {
        cout << letters[i];
        break;
    }
}

*

*I don't understand what's going on with static const char* const letters[] = (...). First of all, I always thought a char was a single character delimited by '. Single or more characters delimited by " are for me a string.

*The way I've understood pointers is that they're a value that represents the address of an object, although this would be initialized as int* p=&x;. They have the advantage of being able to be used like an iterator (kind of). But I really do not get what is going on here, we declare a pointer letters that gets assigned to it an array of values (not addresses), what does that mean? What would be a reason for doing this?

*I know what static is in java, is the meaning similar in CPP? The author writes it means that the compiler will initialize the static values only once. But isn't that done with every variable within a certain scope? I've noticed in debug that I seem to skip over the values after having executed it the first time. But that would imply that even after my program is finished running these static values are still saved? That doesn't seem logical to me.

A: Regarding your first question, a string literal (like e.g. "A+") is an (read-only) array of characters, and as all arrays they can decay to pointers to their first element, i.e. a pointer to char. The variable letters is an array of constant pointers (the pointer in the array can't be changed) to characters that are constant.
For the third questions, what static means is different depending on which scope you declare the variable in. It's a linkage specifier when used in the global scope, and means that the variable (or function) will not be exported from the translation unit. If use for a variable in local scope (i.e. inside a function) then variable will be shared between invocations of the function, i.e. all calls to the function will have the same variable with the the value of it being kept between calls. Declaring a class-member as static means that it's shared between all object instances of the class.

A: 1) Here
static const char* const letters[] = (...)

letters is actually array of const pointers to const characters. Hence the "".
2) Like said, above variable is array of pointers. So each
element in the array holds address to the string literal
defined in the array. So letters[0] holds address of memory
where "A+" is stored.
3) static has various uses in C++. In your case if its declared inside
function, its value is preserved between successive calls to that function.. More details.

A:
static const char* const letters[]

This is an array of pointers to characters. In this case the initializer list sets each pointer to the first character of each of the strings specified in the initializer list.

const ... const

The pointers and the characters the pointers point to are constants.

static

If declared inside a function, similar to a global, but with local scope.
Links:
http://msdn.microsoft.com/en-us/library/s1sb61xd.aspx
http://en.wikipedia.org/wiki/Static_(keyword)

A: *

*Those are not characters but strings, so your understanding is correct. Letters here are not stored as char but in the form of const char*.

*
we declare a pointer letters that gets assigned to it an array of values (not addresses)

those are not pointer letters but literal strings, "a" is a literal, its type is const char[], which decays to const char* - which means its a poitner.
3.

I know what static is in java, is the meaning similar in CPP

in general yes, but there are differences - like you cant use static inside functions in java while you can in c++, also you can have global static variables in c++.

The author writes it means that the compiler will initialize the static values only once. But isn't that done with every variable within a certain scope?

non static variables will be created on stack and default initialized (if no explicit initialization is done) on each function run. static variables on the other hand will be initialized on the first run only.

But that would imply that even after my program is finished running these static values are still saved?

thats not true, after program is done ,they are freed - your process is dead then


text:
Q: Keyword Arguments in Python So I am trying to read data from a Wikipedia page using urllib2/BeautifulSoup. I copied this code into terminal:
import urllib2

hdrs = { 'User-Agent': "Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11" }
req = urllib2.Request("http://en.wikipedia.org/wiki/List_of_United_States_mobile_phone_companies" , headers = hdrs)
fd = urllib2.urlopen(req)

It works fine. However, when I make this call (removing the keyword argument) instead:
req = urllib2.Request("http://en.wikipedia.org/wiki/List_of_United_States_mobile_phone_companies" , hdrs)

I get an error:
 TypeError: must be string or buffer, not dict

Why does this happen? I thought keyword arguments were optional in a function call. Thanks for the help!

A: The second parameter for urllib2.Request is data, not header.
class urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

To specify headers without specifying data, you should use keyword argument form.

A: From the documentation:
urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

You can do this:
req = urllib2.Request("<url>", None, hdrs)

A: Structure of urllib2's request function is :
urllib2.Request(url[, data][, headers][, origin_req_host][, unverifiable])

when you call your functions in python you need to either give the name of the arguments e.g. urllib2.request(headers = hdrs, url = my_url)
or you need to provide the arguments in the order they are given in the function definition.
So on your second function python assumes that you are giving hdrs as the value for data parameter, and thus the datatype mismatch.


text:
Q: Why do HtmlHelpers need an argument to this HtmlHelper helper? Why do HtmlHelpers need to be declared with an argument to an HtmlHelper helper?
i.e
public static string ScheduleEntries(this HtmlHelper helper, ...)

I've never noticed that syntax before in C#, what is it called?
Thanks
-Matt

A: That's an extension method.
The way it works for MVC is that Html in the view is a property of HtmlHelper type on the ViewPage class.


text:
Q: Rails running total column I currently am working on my first rails project after working through multiple tutorials.
I am trying to build a webpage to track my savings goal for the next 6 months.
essentially the site consists of a form input where I input the date I put money into savings and the amount. This site then updates a line graph to show the current savings vs. the goal line.
So far I have successfully built the form and database (using postgresql) and have created the chart which displays the goal and accepts input from the form.
The problem I have is that the input values are displaying as discrete numbers and not a cumulative sum up that month (i.e. week 4 should be the sum of savings from weeks 1 to 4).
I considered initially having a 3rd column in the db called amount_cum and put some lines in the page load method in the controller, that means the database would recalculate at each page load which may be slow...
Any advise would be appreciated, should I be looking to modify the model or the controller?
Lay on the wise words
class PagesController < ApplicationController
def home
 @pages = Pages.new
 @progress = Pages.order(:week)
 @goal = Goals.all
end

def create
 @pages = Pages.new(pages_params)
 weeks_year=Date.parse(params[:pages][:week]).strftime("%U")

 @pages = Pages.new(pages_params.merge(:week => weeks_year))

if @pages.save
  flash[:success]="Savings Uploaded Successfully"
   redirect_to root_path
else
   flash[:danger]=@pages.errors.full_messages.join(", ")
   redirect_to root_path
 end
 end
private
 def pages_params
 params.require(:pages).permit(:week, :amount)
end

end

And model file:
 class Pages < ActiveRecord::Base
  validates :week, presence: true
  validates :amount, presence: true
 end

my view file - I use chartkick gem to generate the chart:
  <%= line_chart [
  {name: "Amount Saved", data: @progress.group(:week).sum(:amount)},
  {name: "Goal Savings", data: @goal.group(:week).sum(:amount) }] %>

Screen shot of the application so you can see how the graph is to be displayed against the goal.
link

A: In that case, you could use inject in the view when generating the chart:
<% saved = [] %>
<% @progress.inject(0) do |sum, page| %>
<%   current = sum + page.amount
<%   saved << current %>
<%   current # the return value is passed in as `sum` in the next iteration %>
<% end %>
<%= line_chart [
      {name: "Amount Saved", data: saved},
      {name: "Goal Savings", data: @goal.group(:week).sum(:amount) }]
%>

Shorter but a little awkward:
<% saved = [] %>
<% @progress.inject(0) { |sum, page| (saved << sum + page.amount).last} %>
<%= line_chart [
      {name: "Amount Saved", data: saved},
      {name: "Goal Savings", data: @goal.group(:week).sum(:amount) }]
%>

You didn't post any info on the Goal model, but you could use a similar technique if you are also looking to plot the incremental increase in the goal each week.
EDIT:
If you need an array of arrays, you could try something like this (forgive me, I'm doing this on my phone)
<% @progress.inject(0) { |sum, page| (saved << [page.week, sum + page.amount]).last.last} %>

EDIT 2:
I don't think inject should modify the original @progress array (if that's what you're asking), but for the sake of argument (and diagnostics), try the following (we can certainly pretty this up if it works):
<% saved = [] %>
<% cum_sum = 0 %>

<% @progress.map do |page| %>
<%   cum_sum += page.amount %>
<%   saved << [page.week, cum_sum] %>
<% end %>
<%= line_chart [
      {name: "Amount Saved", data: saved},
      {name: "Goal Savings", data: @goal.group(:week).sum(:amount) }]
%>

A: There is a simpler way to calculate sums in Rails - you don't have to use inject, you can simply call sum on the array of records. In your case it would be something like:
@progress.sum(:amount)

However, the way I interpreted your question on the first read, I thought that, you were trying to create an array of partial sums from an array of actual sums. I don't know if that's of any use for you, but anyway, here's how I would do that using Ruby's each_with_object and with_index and Rails' sum:
amounts = [100, 200, 150, 300, 120]

partial_sums = amounts.each_with_object([]).with_index do |(_, obj), i|
  obj << amounts[0..i].sum
end                      # => [100, 300, 450, 750, 870]

# Examples:
partial_sums[0]  = 100  # 1st sum - just the first element
partial_sums[2]  = 450  # 3rd partial sum
partial_sums[-1] = 870  # the total of all the amounts from the array

Hope you find that useful.


text:
Q: Cannot find 'OSSignposter' in scope I am new to Instruments and I want to use the new struct OSSignposter.
To use it I updated macOS to 12.0.1. My Xcode Version is 13.0.
When I try to create an instance of OSSignposter I get the Error message "Cannot find 'OSSignposter' in scope".
The small Codesnippet is:
import os
let signpost = OSSignposter()

Can someone help me to fix that issue.
Thanks

A: For the people facing the same issue, the import is:
import os.signpost


text:
Q: How to combine multiple SQL queries CREATE, SELECT and UPDATE in one statement Step 1: I need to create a temporary table raw_data
CREATE TABLE #raw_data   ###create temporary table raw_data
AS
    SELECT table1.*, ba.col2, ''::text as newcol
    FROM table2 ba ##select column from table1 and table2 (alias ba) and add newcol to temporary table
    INNER JOIN table1 ON table2.id = table1.id;  ##inner join

Step 2: Update the raw_table first time
UPDATE raw_data c
SET newcol = 'fruit'
FROM table3.fruit f
WHERE f.ID = 1;

Step 3: Update the raw_table second time
UPDATE raw_data c
SET newcol = 'dryfruit'
FROM table4.dryfruit d
WHERE d.ID = 2;

Is there a way that the queries in step 1, 2 and 3 can be written in a single statement and SELECT * FROM ....  the final updated table?

A: You can use the SQL Merge statement https://learn.microsoft.com/en-us/sql/t-sql/statements/merge-transact-sql?view=sql-server-ver16
The syntax for it is easy but you can find examples and documentation about it.
Small sample:
MERGE tableToUpdate tu
USING newData nd ON tu.id = nd.id
WHEN MATCHED THEN
UPDATE SET tu.something = nd.something;


text:
Q: How to simplify a profile completion calculation that has multiple if statements? I am using a working code below to calculate profile completion percentage. Each field is assigned a weightage and if that field is passed, the weightage is added to the completion score. While this works, this can probably be done with shorter code?
export function profileProgress(user) {
  const name = 5;
  const dob = 15;
  const languages = 10;
  const profilePic = 15;
  const gender = 15;
  const educations = 5;
  const certifications = 10;
  ...
  ...
  let profileCompletion;
  if (user.name) {
    profileCompletion+=name;
  }
  if (user.dob) {
    profileCompletion+=dob;
  }
  if (user.languages) {
    profileCompletion+=languages;
  }
  ...
  ...
  return profileCompletion;
}

A: One approach would be to have an object indexed by user property, whose values are the associated weights for each property.
const weights = {
  name: 5,
  dob: 15,
  languages: 10,
  // ...
};
return Object.entries(weights)
  .reduce((a, [key, weight]) => a + (user[key] ? weight : 0), 0);

A: You can iterate the property names with for...in if you put them all in an object.
const weights = {
  name: 5,
  dob: 15,
  languages: 10,
  //...
};
let completion = 0;
for (let key in weights) {
  if (key in user) {
    completion += weights[key];
  }
}


text:
Q: ActiveMQ Configuration with KahaDB We are using ActiveMQ 5.6.0 with KahaDB. It has produced quite some log files, which is to be expected with our setup (DLQ and stuff), looking like this:
$ ll -h /opt/activemq/data/kahadb/
total 969M
drwxr-xr-x 2 root     root     4.0K Nov  3 12:47 ./
drwxr-xr-x 3 activemq activemq 4.0K Sep 24 12:12 ../
-rw-r--r-- 1 root     root      39M Oct 16 07:57 db-202.log
-rw-r--r-- 1 root     root      38M Oct 16 07:57 db-203.log
-rw-r--r-- 1 root     root      33M Oct 17 08:12 db-238.log
...

No more messages were processed, when we ran into the 1GB temp usage limit. Or that's what we are assuming, is that correct?
The configuration looks like this:
<systemUsage>
    <systemUsage>
        <memoryUsage>
            <memoryUsage limit="512mb"/>
        </memoryUsage>
        <storeUsage>
            <storeUsage limit="3 gb"/>
        </storeUsage>
        <tempUsage>
            <tempUsage limit="1 gb"/>
        </tempUsage>
    </systemUsage>
</systemUsage>

After cleaning up the log files and being way below the limits, still no messages were consumed by AMQ. Only when we manually purged a route, messages were starting to be delivered again.
So we need to ensure, that the KahaDB log size always stays below the temp usage, right? And that delivery was not picked up after fixing that is a bug or are there any other steps to be taken?

A: Yes, you should look for the storeUsage limit.
If you have undelivered messages in queues logs can't be removed.
The solutions are:

*

*raise the storeUsage limit;

*watch for your queues and purge messages from them;

*setup message expiration (http://activemq.apache.org/manage-durable-subscribers.html).


text:
Q: Why RESTful servics should be stateless? What's the benefit? I have heard enough about RESTful service should be stateless. All state info should be stored in client. And each request should contain all the necessary state info.
But why? What's the benefit of doing that? Only when I know its benefit/motivation can I use it properly.
What if my client have a huge amount of state? Suppose there's an online document editing application. Does client have to send the full text he/she is editing when calling server's RESTful API? Or is this scenario simply not suitable for RESTful approach?

A: When talking about REST (or well RESTful since not many people adhere 100% to the paper I will quote here) services I always think it's best to start with the source, meaning Fielding dissertation which mentions in 5.1.3 Stateless:

This constraint induces the properties of visibility, reliability, and scalability. Visibility
  is improved because a monitoring system does not have to look beyond a single request
  datum in order to determine the full nature of the request. Reliability is improved because
  it eases the task of recovering from partial failures [133]. Scalability is improved because
  not having to store state between requests allows the server component to quickly free
  resources, and further simplifies implementation because the server doesn't have to
  manage resource usage across requests.

It goes even further talking about its trade-offs:

Like most architectural choices, the stateless constraint reflects a design trade-off. The
  disadvantage is that it may decrease network performance by increasing the repetitive data
  (per-interaction overhead) sent in a series of requests, since that data cannot be left on the
  server in a shared context. In addition, placing the application state on the client-side
  reduces the server's control over consistent application behavior, since the application
  becomes dependent on the correct implementation of semantics across multiple client
  versions.

But Fielding doesn't stop even there, he talks about caching to overcome some of the problems.
I highly recommend you go through that PDF, since (from what I remember) that was the original paper that introduced REST.
The use case you provided is a tough one and as many said it depends on your exact scenario. RESTful services are called restFUL and not REST because people found the original paper too limiting and decided to loosen up a bit the rules (for instance the original paper doesn't say anything about batch operations).

A: The primary benefit is scalability -- by not needing to fetch additional context for each request, you minimize the amount of work done by the server, which may need to service many requests at the same time.
Additionally, it helps provide greater clarity to consumers of your API. By having the user send everything related to the operation being done, they can more clearly see what is actually being done, and the error messages they get can often be more direct as a result; an error can say what value is wrong and why, rather than trying to communicate that something the consumer can't see went wrong on the server.

A: From the same chapter of Fielding's dissertation:

Like most architectural choices, the stateless constraint reflects a
  design trade-off. The disadvantage is that it may decrease network
  performance by increasing the repetitive data (per-interaction
  overhead) sent in a series of requests, since that data cannot be left
  on the server in a shared context.

Advantages are explained as follows:

This constraint induces the properties of visibility, reliability, and
  scalability.
Visibility is improved because a monitoring system does
  not have to look beyond a single request datum in order to determine
  the full nature of the request.
Reliability is improved because it
  eases the task of recovering from partial failures [133].
Scalability is improved because not having to store state between requests allows
  the server component to quickly free resources, and further simplifies
  implementation because the server doesn't have to manage resource
  usage across requests.

Regarding your specific case, yes and no. This is how the Web works. When we edit something online, we send entire request to the server. Though it is a design choice how we implement partial updates.
Software can be designed to accomplish this goal by sending PUT/POST requests to sub-resources. For example:
PUT /book/chapter1 HTTP/1.1

PUT /book/chapter2 HTTP/1.1

PUT /book/chapter3 HTTP/1.1

instead of updating whole resource:
PUT /book HTTP/1.1
Content-Type: text/xyz
Content-Length: ...


text:
Q: How to parse HTML table data using angularjs There's a site called NPI registry lookup which will show the information about the doctor you're searching for. Here's the URL https://npiregistry.cms.hhs.gov/registry/search-results-table?number=1023070703. This will list the information in table form for the doctor whose NPI number is 1023070703, for example. What I want to do is build an angular site that will allow users to enter the NPI number, which I'd get the data using $http.get(url). I received the data but it's HTML instead of just the values. How can I parse the HTML table so that I can only pick the data I need? Or is there another better way of fetching the data?
It may sound silly to create another site when there already exists one, but it's for internal purpose only which we need to save a list of doctors that are not yet in our list.

A: Please read the sites API which is on top right.
For interactive demo:
https://npiregistry.cms.hhs.gov/api/demo
1023070703 becoming something like:
https://npiregistry.cms.hhs.gov/api/?number=1023070703


text:
Q: Repeat grok pattern I have a message like this "Something word word 20/07/2018 word word 25/04/2015".How can I use a grok pattern or a customer pattern to take all dates and add them into a new field which is an array?
I tried with a custom regex pattern but when I specify the global flag, ES doesn't recognize "/g" flag.The problem is that I don't know how many dates I will have in a document because are invoices or other type of docuemtns which have a lot of dates/numbers inside.

A: Since you have stated in the comment section that you are free in your implementation, I would solve this with logstashs ruby filter and with the help of this article:
https://zzamboni.org/post/capturing-multiple-matches-in-ruby/
(Sorry for not formatting the link but I'm on my mobile phone right now.)
The article describes how you match a string against a regex and store all found values in an array.
So the filter would look something like this (untested):
filter{
  ruby{
    code => '
      my_string = event.get("my_field")
      my_array = my_string.scan(/[0-9]+\/[0-9]+\/[0-9]+/)
      event.set("my_array_field_name", my_array)
    '
  }
}

By playing around with this skeleton you should be able to solve the issue. Also take a look at the documentations.


text:
Q: RecordingProxy::releaseRecordingFrame repeating in log every 25ms while recording on Android phone When I video record in my home made app I get these two lines repeating every 25ms or so (it then fills a log file in no time):
04-28 09:33:07.705: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:07.705: V/Camera(3161): releaseRecordingFrame

I don't think this is normal since I also get often an infamous "media server died" error or the movie just crash. This is on an 4.0.4 Samsung Discover device. I don't see these log lines on my LG optimus one devices.
You'd find these lines of logs in the code here each time a "// callback from camera service when timestamped frame is ready". Is it normal? I read that putting too much into log would eventualy slow down/ bug an app. More code following. Thanks!
Here is the log in video start:
04-28 09:33:05.635: V/Camera-JNI(3161): unlock
04-28 09:33:05.635: V/Camera-JNI(3161): get_native_camera: context=0x1287378, camera=0x1473a88
04-28 09:33:05.635: V/Camera-JNI(3161): get_native_camera: context=0x1287378, camera=0x1473a88
04-28 09:33:05.635: V/Camera(3161): getProxy
04-28 09:33:05.645: V/MediaProfilesJNI(3161): native_get_camcorder_profile: 0 1
04-28 09:33:05.665: D/ASC(3161): mounted
04-28 09:33:05.685: V/VoirCam(3161): ts 1398691985695
04-28 09:33:05.925: V/Camera(3161): RecordingProxy::startRecording
04-28 09:33:05.925: V/Camera(3161): reconnect
04-28 09:33:05.925: V/Camera(3161): startRecording
04-28 09:33:06.305: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:06.305: V/Camera(3161): releaseRecordingFrame
04-28 09:33:06.325: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:06.325: V/Camera(3161): releaseRecordingFrame
04-28 09:33:06.325: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:06.325: V/Camera(3161): releaseRecordingFrame
04-28 09:33:06.345: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:06.345: V/Camera(3161): releaseRecordingFrame
04-28 09:33:06.375: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:33:06.375: V/Camera(3161): releaseRecordingFrame

and on stop:
04-28 09:29:38.555: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:29:38.555: V/Camera(3161): releaseRecordingFrame
04-28 09:29:38.695: V/Camera(3161): RecordingProxy::releaseRecordingFrame
04-28 09:29:38.695: V/Camera(3161): releaseRecordingFrame
04-28 09:29:38.705: V/Camera(3161): RecordingProxy::stopRecording
04-28 09:29:38.705: V/Camera(3161): stopRecording
04-28 09:29:39.065: V/Camera-JNI(3161): lock
04-28 09:29:39.065: V/Camera-JNI(3161): get_native_camera: context=0x1287378, camera=0x1473a88
04-28 09:29:39.065: V/Camera-JNI(3161): lock
04-28 09:29:39.065: V/Camera-JNI(3161): get_native_camera: context=0x1287378, camera=0x1473a88

Recording starts like this:
    if (prepareVideoRecorder()) {
        mMediaRecorder.start();
   }

My prepareVideoRecorder function is:
private boolean prepareVideoRecorder(){
mMediaRecorder = new MediaRecorder();
// Step 1: Unlock and set camera to MediaRecorder
mCamera.unlock();
mMediaRecorder.setCamera(mCamera);
// Step 2: Set sources
mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    CamcorderProfile camcorderProfile = CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH);

    camcorderProfile.videoCodec = MediaRecorder.VideoEncoder.H264;
  camcorderProfile.audioCodec = MediaRecorder.AudioEncoder.AAC;
    camcorderProfile.fileFormat = MediaRecorder.OutputFormat.MPEG_4;

// Step 3: Set a CamcorderProfile (requires API Level 8 or higher)

mMediaRecorder.setProfile(camcorderProfile);
// Step 4: Set output file

mMediaRecorder.setOutputFile(getOutputMediaFile(MEDIA_TYPE_VIDEO).toString());

mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

// Step 6: Prepare configured MediaRecorder
try {
    mMediaRecorder.prepare();
} catch (IllegalStateException e) {
    Log.d(TAG, "IllegalStateException preparing MediaRecorder: " + e.getMessage());
    releaseMediaRecorder();
    return false;
} catch (IOException e) {
    Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
    releaseMediaRecorder();
    return false;
}
return true;

}

A: That message is not expected to appear, but perhaps not for the reason you'd expect.
In the Android sources, verbose-level logging (ALOGV) is compiled out by default.  To enable it, you define the symbol LOG_NDEBUG to be zero before including the Log.h header.  Looking at the source file that came up in your androidcodesearch.com link, you can see this #define -- commented out -- on line 18.  If you were debugging the Camera implementation, you'd start by uncommenting that line.
It appears that whoever built the system you're using (Samsung?) enabled verbose logging for this file and left it on, so messages that were only intended to be visible during debugging are always on.
I haven't looked at this code before, but I'd guess that function might normally run once per frame.  So what you're seeing is probably "normal".


text:
Q: Spring 3 MVC Nesting RequestMapping From Spring Official Document, Spring 3 MVC look to be support nesting Request Mapping.
http://static.springsource.org/spring/docs/3.0.0.RELEASE/spring-framework-reference/pdf/spring-framework-reference.pdf
In page 448, they mentioned:
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {
//...
    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }
//...
}

(I have eliminated some code for readability)
In such case, they claimed that a request to /appoinments/new will invoke the getNewForm method.
However, it doesn't work with my local Google App Engine server (though GAE server works just fine with mapping that are not nested).
I create an example controller like below:
@Controller
@RequestMapping("/basic.do")
public class HelloWorldController {
    @RequestMapping(value="/hello", method=RequestMethod.GET)
    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("basic/helloWorld");
        mav.addObject("message", "Hello World From Phuong!");
        return mav;
    }
}

but a request to /basic.do/hello always results in 404 error.
Wonder if anything wrong there?
I'm using annotation-driven mode with *.do request handled by spring DispatchServlet.

A: try this
@Controller
@RequestMapping("/basic")
public class HelloWorldController {
    @RequestMapping(value="/hello.do", method=RequestMethod.GET)
    public ModelAndView helloWorld() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("basic/helloWorld");
        mav.addObject("message", "Hello World From Phuong!");
        return mav;
    }
}

and try with the basic/hello.do url
The reason is that /basic.do/hello is not going to be handled by your dispatcher servlet as it is not an URL that ends in .do
BTW, .html extensions are nicer than .do, IMHO


text:
Q: PowerQuery - Dynamic Parameter in ODBC SQL Where Clause I'm trying a different approach to a similar question I've asked previously; I have managed to create a dynamic parameter in my PowerQuery Editor which displays a date value entered in an Excel table. The Advanced Editor for the Date Parameter looks like this:
(
let
Source = Excel.CurrentWorkbook(){[Name="DATE_RANGE"]}[Content],
#"Changed Type" = Table.TransformColumnTypes(Source,{{"START_DATE", type date}, {"END_DATE",
type date}}),
START_DATE = #"Changed Type"{0}[START_DATE]
in
START_DATE
)
meta [IsParameterQuery=true, Type="Any", IsParameterQueryRequired=true]

The parameter name is "StartDateValue".
Now, trying to use this parameter value in my OBDC WHERE clause I have tried the following:
WHERE A."CREATED_DTM" = :StartDateValue

Which leaves me with a "ORA-01008: not all variables bound" error code. How would I get this parameter value to work in my clause and what am I missing?


text:
Q: Method not found: 'Microsoft.Extensions.DependencyInjection.ServiceProvider' I have developed a simple console application in .NET6 with target Platform x86 which contains 1 project only with the following packages:

*

*Microsoft.AspNetCore.SignalR.Client (6.0.5)
Microsoft.AspNetCore.SignalR.Common(6.0.5)
Microsoft.AspNetCore.SignalR.Core(1.1.0)
System.IO.Ports (6.0.0)
Also it contains an API to communicate with a Dispenser.
This console application send and recieve data with main software throught SignalR and send and recieve data with Dispenser throught API.
I don't use any dependency injection and the Dispenser response when I try to initialize it is the next one:
Método no encontrado: 'Microsoft.Extensions.DependencyInjection.ServiceProvider Microsoft.Extensions.DependencyInjection.ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(Microsoft.Extensions.DependencyInjection.IServiceCollection)'.

Any idea why the response is that?

A: Microsoft.AspNetCore.SignalR.Core seems to be a legacy package (last updated in 2018) and was build against Microsoft.Extensions.DependencyInjection.Abstractions (>= 2.2.0), while Microsoft.AspNetCore.SignalR.Client is transitively using Microsoft.Extensions.DependencyInjection.Abstractions (>= 6.0.0) so the later version should be resolved during build. And it definitely has some breaking changes (like removal or signature changes of ServiceCollectionContainerBuilderExtensions.BuildServiceProvider(IServiceCollection) method)
Try removing Microsoft.AspNetCore.SignalR.Core package, Microsoft.AspNetCore.SignalR.Client should be sufficient enough to connect to the SingnalR server.


text:
Q: "push notifications at least one user should be subscribed for APNS" Quickblox Hi I have an issue here with regards to sending Push Notifications from my app. I can send them from the admin panel and they are received by the device but not from device to device. I have re-uploaded both development and production certificates on a couple of occasions now. Also push notifications can only be sent from the admin panel in the sandbox environment (no errors) and not the production environment (No recipients. At least one user should be subscribed for APNS (Apple Push) (through SDK or REST API). Can someone help please?
//
    NSString *message = @"Testing APNS!";
    NSMutableDictionary *payload = [NSMutableDictionary dictionary];
    NSMutableDictionary *aps = [NSMutableDictionary dictionary];
    [aps setObject:@"default" forKey:QBMPushMessageSoundKey];
    [aps setObject:message forKey:QBMPushMessageAlertKey];
    [payload setObject:aps forKey:QBMPushMessageApsKey];

    QBMPushMessage *pushMessage = [[QBMPushMessage alloc] initWithPayload:payload];

    // Send push to user
    [QBMessages TSendPush:pushMessage toUsers:self.opponent.login delegate:self];

//

A:  [QBMessages TSendPush:pushMessage toUsers:self.opponent.login delegate:self];

You can's send push notification to user's login, you have to use user's ID
For example:
 [QBMessages TSendPush:pushMessage toUsers:@"22,33,77" delegate:self];


text:
Q: clear example of using PHPSpec with Laravel I've scoured the net and cannot find a clear example of using PHPSpec with Laravel for specifying the behaviour of Models. I've watched the Jeffrey Way video on Laracasts, which shows how to test other classes within a Laravel project but not Models.
Examples I've found seem to differ slightly. I guess as this is still fairly new territory its not well documented. I've used Codeception for functional testing but wish to start a new project with solid unit tests.

A: As a beginner, you should use phpunit rather that phpspec. phpspec is quite superior, but is quite a new tool with very little documentation. Work with PHPUnit for unit testing and then move in when you feel comfortable with TDD,


text:
Q: Current method to set Firefox address bar search URL? I've done a bit of reading on this, but still can't figure out a nice way to do it. It might be worth mentioning that I'm using Vimperator with Firefox.
I want to set the default Firefox address-bar search URL. I will be using a DuckDuckGo URL with some of my preferences in it (so I don't have to store a cookie).
I can make a bookmarklet and assign a keyword to it, but I cannot choose this bookmarklet as a search engine (in the search engine dropdown, or in preferences dialog.)
What I want is to be able to 't %searchterm% ENTER' to make firefox search for %searchterm% in a newtab, rather than 't %KEYWORD FOR DUCKDUCKGO% %searchterm% ENTER'
Previous methods like setting Keyword.URL are depecrated, so what do I do?

A: The search engine that is currently set to default in Firefox's Search bar will also be the one used when searching in the Address bar.
There's an older SuperUser question about the same topic available here.

A: Do you need to change the search engine for Firefox' navigation bar or for :open, :tabopen and related commands in Vimperator / Pentadactyl? They are independent from each other; the latter is set by 'defsearch' option.
Given duckduckgo as the alias for DDG (see :dialog searchengines), you have to:
:set defsearch=duckduckgo


text:
Q: WebView OutOfMemoryException I'm loading long pages into a WebView using loadData(), unfortunately after around 5 or 10 page links it gives an OutOfMemoryException. This is likely caused by the history holding the full data: url of every page.
I have a memory & cpu monitor in the status bar, and it always shows hardly any memory usage, so the app isn't using up all memory. Is there a way to allow my app to use more memory, similar to Java's command-line switches? Is there a way to make the webview more efficient, perhaps by making a cache on the sd card, to prevent this crash?
06-27 12:02:44.746: WARN/System.err(6692): java.lang.OutOfMemoryError
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:157)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.StringBuilder.append(StringBuilder.java:217)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.startLoadingResource(BrowserFrame.java:710)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.nativeLoadUrl(Native Method)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:248)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1564)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore.access$1400(WebViewCore.java:52)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:950)
06-27 12:02:44.746: WARN/System.err(6692):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 12:02:44.746: WARN/System.err(6692):     at android.os.Looper.loop(Looper.java:123)
06-27 12:02:44.746: WARN/System.err(6692):     at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:623)
06-27 12:02:44.746: WARN/System.err(6692):     at java.lang.Thread.run(Thread.java:1096)
06-27 12:02:44.746: WARN/dalvikvm(6692): threadid=8: thread exiting with uncaught exception (group=0x40020ac0)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692): FATAL EXCEPTION: WebViewCoreThread
06-27 12:02:44.756: ERROR/AndroidRuntime(6692): java.lang.OutOfMemoryError
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:97)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:157)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.StringBuilder.append(StringBuilder.java:217)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.startLoadingResource(BrowserFrame.java:710)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.nativeLoadUrl(Native Method)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.BrowserFrame.loadUrl(BrowserFrame.java:248)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore.loadUrl(WebViewCore.java:1564)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore.access$1400(WebViewCore.java:52)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore$EventHub$1.handleMessage(WebViewCore.java:950)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.os.Handler.dispatchMessage(Handler.java:99)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.os.Looper.loop(Looper.java:123)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at android.webkit.WebViewCore$WebCoreThread.run(WebViewCore.java:623)
06-27 12:02:44.756: ERROR/AndroidRuntime(6692):     at java.lang.Thread.run(Thread.java:1096)

The strange thing is, DDMS Heap view shows it had plenty of "Free" memory, but it still may give an error such as:
ERROR/dalvikvm-heap(10612): Out of memory on a 1153232-byte allocation.

I don't know if it's at all related, but sometimes it gives this warning when opening a page, before out-of-memory:
ERROR/Web Console(18033): SECURITY_ERR: DOM Exception 18: An attempt was made to break through the security policy of the user agent. at ...

A: Have you considered implementing onLowMemory() and using freeMemory on the WebView?  You could also use clearCache.  Another consideration would be to change the cache mode.

A: I switched to loadDataWithBaseURL, which doesn't require URLEncoder encoding the url, and doesn't keep huge data urls in the history. This seems to have fixed the high cpu use and memory leak, and the SECURITY_ERR:
WebView.loadDataWithBaseURL(url,data,"text/html","UTF-8",url);


text:
Q: Appending multiple items to a default parameter with argparse I'm using argparse with Python 2.7.x and am having some trouble appending to a default parameter list. The pertinent code is shown below:
parser = ArgumentParser(...)

parser.add_argument('--project-list', action='append', dest='project_list',
                    nargs='*', default=['AAA', 'BBB'])

# ...

args = parser.parse_args()
print args.project_list

Which prints the following when called:
$ python program.py --project-list CCC # --> project_list=['AAA', 'BBB', ['CCC']]

$ python program.py --project-list CCC DDD # --> project_list=['AAA', 'BBB', ['CCC', 'DDD']]

However, what I would like the program to do is illustrated below:
$ python program.py --project-list CCC  # --> project_list=['AAA', 'BBB', 'CCC']

$ python program.py --project-list CCC DDD  # --> project_list=['AAA', 'BBB', 'CCC', 'DDD']

From what I've found so far it seems the nargs parameter forces a list to be made, which is then appended (not sure why?).
A few other solutions such as passing type=str, or type=construct_project_list (which is a function that returns a 'valid' list) haven't worked either...
Thanks in advance for any help you can provide!


text:
Q: Error: Could not find or load main class when trying to run jar file I'm trying to create a JAR file of my Java code. There are four classes - A.java, B.java, C.java, and D.java. A.java has the main method. These are in a folder called src, and my manifest file is outside of src, and all of my .class files are in bin which is inside src. I created a MANIFEST.MF with the following contents:
Manifest-Version: 1.0
Main-Class: src/A

I then use the command jar cmf MANIFEST.MF A.jar src/bin/*.class src/GraphFile.txt src/ProblemA.txt src/ProblemB.txt (there are a few text files I need to include as well in my JAR file). Then, when I run java -jar A.jar ProblemA.txt GraphFile.txt (note that ProblemA.txt and GraphFile.txt are input files that my program accepts and uses), I get the following error:
Error: Could not find or load main class src.A
Caused by: java.lang.ClassNotFoundException: src.A

Can anyone explain what I am doing wrong or any steps I am missing? Unfortunately, I cannot post the actual code because this is for a class project, but I just need to get it compiled into a JAR file for submission! Thanks for any help.


text:
Q: Verify user on server after using MSAL2 for login I am creating an application where a user logs in using the Microsoft Azure credentials, this login works perfectly on the client side.
However, after logging in, the backend should need to be able to verify that this user is actually able to access the application's content, as not every employee has access to every feature that comes with the app. So in order to validate that, I would like to have my server verify the token the client received to avoid the chances of the user being spoofed.
I have been breaking my head over this for over a week now. I was originally using the microsoft teams library to do the authentication, which worked fine, it allowed the server to do an extra step where it gets the token, but the applications needs to be accessible outside of teams too, and I can't recreate the functionality with MSAL.
EDIT: I seem to have been able to use the token received from the MSAL2 login to grab another access token via the server side, this way I can verify the login. I have no clue how I fixed my issue, but I did

A: As mentioned you can get user details from OpenID scope in your app authentication. If you have access to source code of your application then you can add some code to create logs to check user is actually able to access the application's content and then update it to server. You can also get sign in and activity logs information in azure.


text:
Q: Sum time across different continuous time events across date and time combinations in R I am having trouble figuring out how to account for and sum continuous time observations across multiple dates and time events in my dataset. A similar question is found here, but it only accounts for one instance of a continuous time event. I have a dataset with multiple date and time combinations. Here is an example from that dataset, which I am manipulating in R:
date.1 <- c("2021-07-21", "2021-07-21", "2021-07-21", "2021-07-29", "2021-07-29", "2021-07-30", "2021-08-01","2021-08-01","2021-08-01")
time.1 <- c("15:57:59", "15:58:00", "15:58:01", "15:46:10", "15:46:13", "18:12:10", "18:12:10","18:12:11","18:12:13")
df <- data.frame(date.1, time.1)
df
       date.1   time.1
1 2021-07-21 15:57:59
2 2021-07-21 15:58:00
3 2021-07-21 15:58:01
4 2021-07-29 15:46:10
5 2021-07-29 15:46:13
6 2021-07-30 18:12:10
7 2021-08-01 18:12:10
8 2021-08-01 18:12:11
9 2021-08-01 18:12:13

I tried following the following script from the link I present:
df$missingflag <-  c(1, diff(as.POSIXct(df$time.1, format="%H:%M:%S", tz="UTC"))) > 1
df
   date.1   time.1 missingflag
1 2021-07-21 15:57:59       FALSE
2 2021-07-21 15:58:00        TRUE
3 2021-07-21 15:58:01       FALSE
4 2021-07-29 15:46:10       FALSE
5 2021-07-29 15:46:13        TRUE
6 2021-07-30 18:12:10        TRUE
7 2021-08-01 18:12:10       FALSE
8 2021-08-01 18:12:11       FALSE
9 2021-08-01 18:12:13        TRUE

But it did not working as anticipated and did not get closer to my answer. It would have been an intermediate goal and probably wouldn't answer my questions.
The GOAL of my dilemma would be account to for all the continuous time observations and put into a new table like this:
   date.1   time.1      secs
1 2021-07-21 15:57:59       3
4 2021-07-29 15:46:10       1
5 2021-07-29 15:46:13       1
6 2021-07-30 18:12:10       1
7 2021-08-01 18:12:10       2
9 2021-08-01 18:12:13       1

You will see that the start time of each of the continuous time observations are recorded and the total number of seconds (secs) observed since the start of the continuous observation are being recorded. The script would account for date.1 as there are multiple dates in the dataset.
Thank you in advance.

A: You can create a datetime object combining date and time columns, get the difference of consecutive values and create groups where all the time 1s apart are part of the same group. For each group count the number of rows and their first datetime value.
library(dplyr)
library(tidyr)

df %>%
  unite(datetime, date.1, time.1, sep = ' ') %>%
  mutate(datetime = lubridate::ymd_hms(datetime)) %>%
  group_by(grp = cumsum(difftime(datetime,
           lag(datetime, default = first(datetime)), units = 'secs') > 1)) %>%
  summarise(datetime = first(datetime),
            secs = n(), .groups = 'drop') %>%
  select(-grp)

#  datetime             secs
#  <dttm>              <int>
#1 2021-07-21 15:57:59     3
#2 2021-07-29 15:46:10     1
#3 2021-07-29 15:46:13     1
#4 2021-07-30 18:12:10     1
#5 2021-08-01 18:12:10     2
#6 2021-08-01 18:12:13     1

I have kept datetime as single combined column here but if needed you can separate them again as two different columns using
 %>% separate(datetime, c('date', 'time'), sep = ' ')


text:
Q: RSpec testing with followerships / friendships has many through users I inspired myself with the following link, http://railscasts.com/episodes/163-self-referential-association, but the rspec testing is not coming easy.
user model:
class User < ActiveRecord::Base

  # Associations
  has_many :followerships
  has_many :followers, :through => :followerships
  has_many :inverse_followerships, :class_name => "Followership", :foreign_key => "follower_id"
  has_many :inverse_followers, :through => :inverse_followerships, :source => :user
end

followership model:
class Followership < ActiveRecord::Base
  belongs_to :user
  belongs_to :follower, :class_name => "User"
end

followerhip factory:
FactoryGirl.define do
  factory :followership do
    user_id 1
    follower_id 1
  end
end

followerships controller:
class FollowershipsController < InheritedResources::Base
  def create
    @followership = current_user.followerships.build(:follower_id => params[:follower_id])
    if @followership.save
      flash[:notice] = "Following."
      redirect_to root_url
    else
      flash[:error] = "Unable to follow."
      redirect_to root_url
    end
  end

  def destroy
    @followership = current_user.followerships.find(params[:id])
    @followership.destroy
    flash[:notice] = "Removed followership."
    redirect_to current_user
  end
end

folowerships controller spec (this is all wrong):
require 'rails_helper'

describe FollowershipsController do
  let!(:followership) { create(:followership) }
  let!(:follower) { followership.follower }
  let!(:user) { create(:user) }

  before do
    sign_in :user, user
  end

  describe "#create" do
    it "saves the followership" do
      post :create, followership: { follower_id: follower }

      expect(response).to redirect_to(root_path)
      expect(assigns(:followership).followership.followers).to eq(user)
      expect(flash[:notice]).to eq("Following.")
    end

    it "fails to save followership" do
      expect(post :create, followership: { follower_id: follower }).to redirect_to(root_path)
      expect(flash[:notice]).to eq("Unable to follow.")
    end
  end

  describe "#destroy" do
    it "deletes the followership" do
      expect {
        delete :destroy, id: follower
      }.to change(Followership, :count).by(-1)

      expect(flash[:notice]).to eq("Removed followership.")
    end
  end

end

Error from followerships controller Rspec
FollowershipsController
  #destroy
    deletes the followership (FAILED - 1)
  #create
    saves the followership (FAILED - 2)
    fails to save followership (FAILED - 3)

Failures:

  1) FollowershipsController#destroy deletes the followership
     Failure/Error: delete :destroy, id: follower

     ActionController::UrlGenerationError:
       No route matches {:action=>"destroy", :controller=>"followerships", :id=>nil}

  2) FollowershipsController#create saves the followership
     Failure/Error: expect(assigns(:followership).followership.followers).to eq(user)

     NoMethodError:
       undefined method `followership' for #<Followership:0x00000109f69780>

  3) FollowershipsController#create fails to save followership
     Failure/Error: expect(flash[:notice]).to eq("Unable to follow.")

       expected: "Unable to follow."
            got: "Following."

       (compared using ==)

Thanks for the help :)

A: The let command uses lazy evaluation, so these records are not actually created until called. Use the let! syntax to ensure they're created before your tests run:
  let!(:followership) { create(:followership) }
  let!(:follower) { followership.follower }
  let!(:user) { create(:user) }

Make sure your validations also only allow creation of a following if it doesn't already exist for that pair of users:
class Followership < ActiveRecord::Base
   validates_uniqueness_of :user_id, scope: :follower_id

Also, it's not guaranteed that the follower/followership relationships will belong to user since user doesn't necessarily have an id of 1.
Finally, assigns is a method, so the syntax should be assigns(:followership) not assigns[:followership]


text:
Q: TableStyle is overwritten by document style Because the original project seems inactive I have to replicate my Issue here at StackOverflow.
It seems to me that the global document style does overwrite lower styles e.g. TableStyle. I assume I misunderstand the concept here.
See this code as an example
#!/usr/bin/env python3
import os
import docx

document = docx.Document()
document.styles['Normal'].font.name = 'Fira Mono'
document.styles['Normal'].font.size = docx.shared.Pt(8)

my_tab_style = document.styles.add_style('MyTab', docx.enum.style.WD_STYLE_TYPE.TABLE)
my_tab_style.font.name = 'Fira Sans'
my_tab_style.font.size = docx.shared.Pt(20)

p = document.add_paragraph('Should be Fira Mono 8pt')

tab = document.add_table(rows=1, cols=1, style='MyTab')
tab.rows[0].cells[0].text = 'Should be Fira Sans 20pt'

document.save('test.docx')
os.system('start test.docx')

I would expect the document text in "Fira Mono 8pt" and the table content in "Fira Sans 20pt". But it isn't.

When you outcomment the document style lines
# document.styles['Normal'].font.name = 'Fira Mono'
# document.styles['Normal'].font.size = docx.shared.Pt(8)

the table style is taken into account.


text:
Q: JFlex - Regex for "Arrow" So if I wanted to key in an Arrow character, -->, via JFlex's regex, I'd figure it would just be the string "-->". However, if I attempt this, I always get a Could not match Input error.
"-->"   {}

Doesn't work. Neither does a combination of escaping certain characters as far as I can tell. I know each of those characters is special in flex, and I know the /-->/ literal way that works in other languages wont in Java.
What am I missing?

A: If I understand correctly, you're trying to find a match for '-->'?  If so, the expression [\-\-\>]+ fill find that match.
Tested at http://www.regexplanet.com/advanced/java/index.html


text:
Q: Resizing image proportionally in ASP.NET C# by specifying either Height or Width I need a code that will allow me to resize images, but with the following functionality:
1) resize image upon upload
2) Resize image proportionally by specifying either height or width.
Note:

*

*Should be done in ASP.NET C#

For example: The function should get the a width OR a height, and resize the image proportionally for the give height OR Width. Let's say that the image is 400(w)x100(h). I want to tell the function to resize the image to a specific height, let's say 80px. The function should resize the image proportionally while setting the image height to 80px and the width accordingly. Another option is ti tell the function the width, let's say 200px, and the function should resize the image to 200px width and set the height accordingly.
3) save the image to a specific location (path).
4) Function can work with uploaded image or by specifying an image path.
5) I want to be able to choose the image quality
6) Only need this for JPEG
Can somebody please help me out with this. Thanks.

A: Although it seems like you should be able to copy and paste a snippet to do this, there are a ton of pitfalls you need to look out for if you're building your own image resizing system. It's better to use a proven, tested, and supported open-source library.
To resize to a file directly from HttpPostedFile, call
ImageBuilder.Current.Build(httpPostedFile, "img.jpg", new ResizeSettings("width=200&quality=90"));

To resize an existing file, call
ImageBuilder.Current.Build("orig.jpg", "img.jpg", new ResizeSettings("width=200&quality=90"));

The ImageResizing.Net library is free, and MIT-licensed (no worries about licensing problems).

A: Last day I found imageresizer and its great. and good API. Works Great.
Downloaded from Visual studio 2010 Extension Manager: http://nuget.org/.
Easy Steps to download API in VS-2010:
1). Install Extension http://nuget.org/.

3). Find and Install ImageResizing

4).Then Code: (I m using here cropping. you can use any) Documentation on imageresizing.net
string uploadFolder = Server.MapPath(Request.ApplicationPath + "images/");
FileUpload1.SaveAs(uploadFolder + FileUpload1.FileName);

//The resizing settings can specify any of 30 commands.. See http://imageresizing.net for details.
ResizeSettings resizeCropSettings = new ResizeSettings("width=200&height=200&format=jpg&crop=auto");

//Generate a filename (GUIDs are safest).
string fileName = Path.Combine(uploadFolder, System.Guid.NewGuid().ToString());

//Let the image builder add the correct extension based on the output file type (which may differ).
fileName = ImageBuilder.Current.Build(uploadFolder + FileUpload1.FileName, fileName, resizeCropSettings, false, true);
Try!!! its very awsumm and easy to use. thanks.

A: Taken from this Stackoverflow answer, I come up with:
public static Image Resize(this Image image, int maxWidth = 0, int maxHeight = 0)
    {
        if (maxWidth == 0)
            maxWidth = image.Width;
        if (maxHeight == 0)
            maxHeight = image.Height;

        var ratioX = (double)maxWidth / image.Width;
        var ratioY = (double)maxHeight / image.Height;
        var ratio = Math.Min(ratioX, ratioY);

        var newWidth = (int)(image.Width * ratio);
        var newHeight = (int)(image.Height * ratio);

        var newImage = new Bitmap(newWidth, newHeight);
        Graphics.FromImage(newImage).DrawImage(image, 0, 0, newWidth, newHeight);
        return newImage;
    }

To resize Image specifying its maxWidth:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(100);

To resize Image specifying its maxHeight:
var _image = Image.FromStream(Source);
var _thumbImage = _image.Resize(maxHeight: 100);

A: This is how is did in my project
On Button click while uploading file:
System.Drawing.Bitmap bmpPostedImage = new System.Drawing.Bitmap(File1.PostedFile.InputStream);
     System.Drawing.Image objImage = ScaleImage(bmpPostedImage, 81);
     objImage.Save(SaveLocation,ImageFormat.Png);
     lblmsg.Text = "The file has been uploaded.";

public static System.Drawing.Image ScaleImage(System.Drawing.Image image, int maxHeight)
        {
            var ratio = (double)maxHeight / image.Height;

            var newWidth = (int)(image.Width * ratio);
            var newHeight = (int)(image.Height * ratio);

            var newImage = new Bitmap(newWidth, newHeight);
            using (var g = Graphics.FromImage(newImage))
            {
                g.DrawImage(image, 0, 0, newWidth, newHeight);
            }
            return newImage;
        }


text:
Q: How to convert window coords into turtle coords (Python Turtle) I am trying to create a program to move the turtle to where the mouse is.
I am doing:
import turtle
t = turtle.Turtle()

canvas = turtle.getcanvas()

while True:
    mouseX, mouseY = canvas.winfo_pointerxy()
    t.goto(mouseX, mouseY)

but the turtle keeps moving off the screen.
I read from this question that canvas.winfo_pointerxy() returns 'window coordinates' (0, 0 at the top left of the window) and that I need to convert them to 'turtle coordinates' (0, 0 at the center of the window) but I don't know how to do that.

A: First, you need to find the size of the canvas. for this example, I used a set width and height, but for your purposes, you may find it easier to find the size instead of entering it.
    width = 500
    height = 300

    t = turtle.Turtle()
    canvas = turtle.getcanvas()
    turtle.screensize(canvwidth=width, canvheight=height)

you can use this code to find the width and height
    width = canvas.winfo_width()
    height = canvas.winfo_height()

When you measure the mouse's position, however, you'll need to do this calculation to get the right value.
    mouseX = canvas.winfo_pointerx() - width/2
    mouseY = (canvas.winfo_pointery()*-1) + height/2
    t.goto(mouseX, mouseY)

A: You have to use the dimensions of the window to calculate the center of the window. You just need to subtract the midpoint from the mouse coordinates (since the 0,0 for that is the top-left of the screen) to get it.
You need to add the following:
width = canvas.winfo_width()
height = canvas.winfo_height()

midpoint_x = width / 2
midpoint_y = height / 2

turtleX = mouseX - midpoint_x
turtleY = mouseY - midpoint_y

You end up with something like this:
import turtle

t = turtle.Turtle()
canvas = turtle.getcanvas()
width = canvas.winfo_width()
height = canvas.winfo_height()
midpoint_x = width / 2
midpoint_y = height / 2

while True:
    mouseX, mouseY = canvas.winfo_pointerxy()

    turtleX = mouseX - midpoint_x
    turtleY = mouseY - midpoint_y

    t.goto(turtleX, turtleY)


text:
Q: Facebook - get user Access Token via Cronjob is it possible to get an valid access token for an user via a cronjob?
i want to create an app that parse every night all posts from the user and check if there are some special chars.
with the app access key i have only access to the public posts from the user.. with the user access token i can access also private posts
but the user access token expires
is it possible to refresh the user token with an cronjob? that means the cronjob may have to refresh 100 user access tokens and i dont have the user du open the authorization dialog because its called on a server via cronjob
I'am using php for the facebook api

A: No, this is not possible, it even say that explicitly in the official Removal of offline_access Permission post:

The user must access your application before you're able to get a
  valid "authorization code" to be able to make the server-side OAuth
  call again. Apps will not be able to setup a background/cron job that
  tries to automatically extend the expiration time, because the
  "authorization code" is short-lived and will have expired.

With that said, when you get an access token from a Server-Side authentication flow, the token you get should last for a month, if you persist it then you can then use it for that month.
After that month is over, and if the user hasn't re-engaged your app then the access token will be expired and you'll have to pass on that user.

A: If you use the facebook jdk you can use: $token = $facebook->getAccessToken();
then, save $token into database for use by cronjob
    $args = array(
                 'access_token'  => $page_info['access_token'], //Offline Access Token From Database
                 'message'       => $_POST['description'],
                 'link'          =>$_POST['link'],
                 'picture'       =>$_POST['image'],
                 'name'          =>$_POST['title']
                 );
    $post_id = $facebook->api("/$page_id/feed","post",$args);

with $page_id is id of fanpage or
$post_id = $facebook->api("/me/feed","post",$args);