text:
Q: Let $G$ be a (probably infinite) group and $H \leq K \leq G$. $|G:H| < \infty \Rightarrow |G:H|=|G:K||K:H|$? Let $G$ be a (probably infinite) group and $H \leq K \leq G$. Is it true that if we have $|G:H| < \infty$ then $|G:H|=|G:K||K:H|$ ?
Thanks in advance.

A: Recall that $|G:H|$ is the number of left (or right) cosets of $H$ in $G$.  Let $|G:H|=n$, then there are $g_1,\dots,g_n\in G$ s.t. ${g_iH}$ are the distinct cosets of $H$ in $G$.
The first thing to prove is that $|G:K|$ and $|K:H|$ are finite.
First, we show that $|K:H|$ is finite.  Let $K$ be a subgroup of $G$ containing $H$.  Then, since $\cup_i g_iH=G$, some of the $g_iH$'s intersect with $K$.  Suppose $g_1,\dots,g_k$ correspond to the cosets of $H$ which intersect $K$.  Then $g_iH\cap K\not=\emptyset$.  Therefore, for some $h\in H$, $g_ih\in K$.  Let $g_ih=k$.  Since $H$ is a subgroup of $K$, $h^{-1}\in K$, so $g_i=kh^{-1}\in K$.  Therefore, $|K:H|$ is finite and the cosets of $H$ which intersect $K$ are the cosets of $H$ in $K$.
Second, we show that $|G:K|$ is finite.  Consider the set of cosets of $K$ of the form $g_iK$ where $1\leq i\leq n$.  Since $K$ contains $H$, $g_iK\supseteq g_iH$ and since the union of the $g_iH$ is all of $G$, the union of the $g_iK$'s is also all of $G$.  By considering a minimal set of these $g_iK$'s, you have a complete set of cosets.
Finally, since $|G:K|$ is finite, let $g'_1K,\dots,g'_mK$ be the (distinct) cosets of $K$ in $G$, and let $g_1,\cdots,g_k$ be the distinct cosets of $H$ in $K$.  Then the cosets of $H$ in $G$ are $g'_ig_jH$.  You can show that these are distinct and that the number of these is exactly $|G:K||K:H|$.

A: Yes. For reference, you can check out this. I'm assuming $H$ and $K$ are subgroups of $G$.


text:
Q: How to space some DIVs in columns without a  I'm trying to have two or more columns worth of DIVs for input elements in a form. It's a very complex form, and some elements will be hidden and shown depending on some answers.
The problem is I can't get the DIVs to space accordingly in IE6 while having an effective hide/show. This is what mostly works:
.first_column
{
  float:left;
  clear:both;
}
.second_column
{
  float:left;
}

And some HTML...

first row, column 1 <input type="text" id="asdf">

second row, column 1 <input type="text" id="asdf2">

second row, column 2 <input type="text" id="asdf3">

This works as expected. The problem is the show/hide. If I hide #question1, the line break remains. This isn't so bad for this small example, but if there are many questions depending on a show/hide, large gaps start to appear between rows of questions.
How can I achieve this without that line break?

A: Use margin-bottom on your divs instead of br

A: I suggest wrapping your complete rows in another div, and give it an id like row_1, row_2. This would include all questions plus the br. Then when you hide the row, the br hides too.

A: Use this pattern. Better semantics, simple code. Wrap these in DIVS for hide/show.
this.next('.question').toggle() - uses Prototype library. It finds the next element with the given class name and will hide/show that element.
open

First Name
<input .... />

...and this CSS
.label {
width:120px;
float:left;
margin-right:15px
}

.input {
float:left
}

.formClear {
clear:left;
height:15px;
}

A: For this problem, in my websites I use this:
In the CSS:
.spacer
{clear: both; visibility: hidden;}

In the HTML:

DIV is betther than BR (or HR) for this type of things because it do not move a pixel so you are free to apply margins to other content DIVs in order to have the perfect layout that you want. This work in all browsers, also in IE6.
This will fix also most of the floating problems. I do not find other solutions without this that are cross browser.

A: Unfortunately IE6 is unwavering in it's resolve to render HTML differently from every other browser. Unfortunately I wasn't able to come up with a simple enough solution with using the br's with clear. Oh well... time to fight with IE6 elsewhere.
Thanks for the suggestions.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to move a Form to the foreground when clicking a Window of another app parented to a Panel I use the code down below to start an application and move it into a Panel on my Form. In this example I use Notepad, only as an example. Later I will use a different application.
When another application is moved in front of my Form, I can only move my Form to the foreground by clicking the title bar. If I click on the MDI child area (so the Panel where Notepad is moved into), nothing happens.
Is there a way to enable that?
Imports System.Runtime.InteropServices
Public Class Form1
    Declare Auto Function SetParent Lib "user32.dll" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim proc As Process
        proc = Process.Start("notepad.exe")
        proc.WaitForInputIdle()
        SetParent(proc.MainWindowHandle, Me.Panel1.Handle)
        SendMessage(proc.MainWindowHandle, 274, 61488, 0)
    End Sub
End Class

A: The problem is that a hosted (re-parented) Window, when activated, doesn't cause the hosing Form to also activate, so it's brought to the foreground.
The hosted Window is not exactly a child Window and the hosting Form doesn't receive any message from it.
A possible method to bring to the foreground the Form that hosts a foreign Window, when this Window receives the focus (you click or otherwise activate it)
It uses SetWinEventHook to install a Hook that monitors changes in state of the placement of a Window (EVENT_SYSTEM_FOREGROUND).
You specify the handle of the Window of interests, (your proc.MainWindowHandle here), plus its ProcessId and ThreadId. Note that these are not the same as your app's, a call to GetWindowThreadProcessId() is required to get this information.
When you activate the foreign Window, the Hooks calls the specified callback delegate (here, ForegrundChangedEventDelegate), which in turn executes the method that it points to (ForegroundStateChangedCallback)
When this method is called, it checks whether the object that caused the notification is OBJID_WINDOW and that the event is actually EVENT_SYSTEM_FOREGROUND. If that's the case, it calls SetWindowPos to bring the hosting Form to the foreground, but without activating it, so the hosted Window doesn't lose focus
Notes:

*

*The SetWinEvetHook delegate is created in the Constructor (Sub New()) of the parent Form, along with a GC SafeHandle that is used to prevent the delegate from being garbage-collected at the wrong time.
It's released in the OnHandleDestroyed() override, where also the hook proc is un-hooked

*see the imports statement in the Form:
  Imports [Your App Namespace].NativeMethods

this means that you have to specify the namespace of your app for the import to work as intended. In VB.Net, usually the name of the app and its main NameSpace match; if your app is named, WinFormsApp1, then its Imports WinFormsApp1.NativeMethods

*

*To activate the Hook, as soon as you have changed the Parent of that Window, use its handle to call the SetForegroundStateChangedHook() method. That's all.
When the Form closes, the hook is released

I suggest using the code in Unhook Window into its original State to set the Parent (and, possibly, set it back to the original value before closing the hosting form). You can send WM_CLOSE to the Window if needed.

Imports [Your App Namespace].NativeMethods

Public Class SomeForm

    Private hForegrundChangedEventHook As IntPtr
    Private ReadOnly ForegrundChangedEventDelegate As WinEventDelegate
    Private Shared GCForegroundStateSafetyHandle As GCHandle

    Public Sub New()
        InitializeComponent()
        ForegrundChangedEventDelegate = New WinEventDelegate(AddressOf ForegroundStateChangedCallback)
        GCForegroundStateSafetyHandle = GCHandle.Alloc(ForegrundChangedEventDelegate)
    End Sub

    Protected Overrides Sub OnHandleDestroyed(e As EventArgs)
        GCForegroundStateSafetyHandle.Free()
        UnhookWinEvent(hForegrundChangedEventHook)
        MyBase.OnHandleDestroyed(e)
    End Sub

    Private Sub SetForegroundStateChangedHook(hWnd As IntPtr)
        Dim processId As UInteger
        Dim targetThreadId = GetWindowThread(hWnd, processId)
        hForegrundChangedEventHook = WinEventHookOne(SWEH_Events.EVENT_SYSTEM_FOREGROUND, ForegrundChangedEventDelegate, processId, targetThreadId)
    End Sub

    Friend Sub ForegroundStateChangedCallback(hWinEventHook As IntPtr, eventType As SWEH_Events, hWnd As IntPtr, idObject As SWEH_ObjectId, idChild As Long, dwEventThread As UInteger, dwmsEventTime As UInteger)
        If idObject = SWEH_ObjectId.OBJID_WINDOW AndAlso eventType = SWEH_Events.EVENT_SYSTEM_FOREGROUND Then
            Dim flags = SWP_Flags.SWP_ASYNCWINDOWPOS Or SWP_Flags.SWP_NOACTIVATE Or SWP_Flags.SWP_NOSIZE Or SWP_Flags.SWP_NOMOVE
            SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, flags)
        End If
    End Sub
End Class

NativeMethods class
Add this class to the Project and import in your Form as described
Imports System.Runtime.InteropServices

Public Class NativeMethods

    <DllImport("user32.dll", SetLastError:=True)>
    Friend Shared Function GetWindowThreadProcessId(hWnd As IntPtr, ByRef lpdwProcessId As UInteger) As UInteger
    End Function

    <DllImport("user32.dll", SetLastError:=True)>
    Friend Shared Function SetWindowPos(hWnd As IntPtr, hWndInsertAfter As IntPtr, x As Integer, y As Integer, cx As Integer, cy As Integer, uFlags As SWP_Flags) As Boolean
    End Function

    Friend Delegate Sub WinEventDelegate(
        hWinEventHook As IntPtr,
        eventType As SWEH_Events,
        hwnd As IntPtr, idObject As SWEH_ObjectId,
        idChild As Long,
        dwEventThread As UInteger,
        dwmsEventTime As UInteger)

    <DllImport("user32.dll", SetLastError:=False)>
    Friend Shared Function SetWinEventHook(
        eventMin As SWEH_Events,
        eventMax As SWEH_Events,
        hmodWinEventProc As IntPtr,
        lpfnWinEventProc As WinEventDelegate,
        idProcess As UInteger,
        idThread As UInteger,
        dwFlags As SWEH_dwFlags) As IntPtr
    End Function

    <DllImport("user32.dll", SetLastError:=False)>
    Friend Shared Function UnhookWinEvent(hWinEventHook As IntPtr) As Boolean
    End Function

    Friend Shared WinEventHookInternalFlags As SWEH_dwFlags =
        SWEH_dwFlags.WINEVENT_OUTOFCONTEXT Or SWEH_dwFlags.WINEVENT_SKIPOWNPROCESS

    Friend Shared Function WinEventHookOne(evt As SWEH_Events, weDelegate As WinEventDelegate, idProcess As UInteger, idThread As UInteger) As IntPtr
        Return SetWinEventHook(evt, evt, IntPtr.Zero, weDelegate, idProcess, idThread, WinEventHookInternalFlags)
    End Function

    Friend Shared Function GetWindowThread(hWnd As IntPtr, ByRef processID As UInteger) As UInteger
        processID = 0
        Return GetWindowThreadProcessId(hWnd, processID)
    End Function

    ' SetWinEventHook Events
    Friend Enum SWEH_Events As UInteger
        EVENT_MIN = &H1
        EVENT_MAX = &H7FFFFFFF
        EVENT_SYSTEM_SOUND = &H1
        EVENT_SYSTEM_ALERT = &H2
        EVENT_SYSTEM_FOREGROUND = &H3
        EVENT_SYSTEM_MENUSTART = &H4
        EVENT_SYSTEM_MENUEND = &H5
        EVENT_SYSTEM_MENUPOPUPSTART = &H6
        EVENT_SYSTEM_MENUPOPUPEND = &H7
        EVENT_SYSTEM_CAPTURESTART = &H8
        EVENT_SYSTEM_CAPTUREEND = &H9
        EVENT_SYSTEM_MOVESIZESTART = &HA
        EVENT_SYSTEM_MOVESIZEEND = &HB
        EVENT_SYSTEM_CONTEXTHELPSTART = &HC
        EVENT_SYSTEM_CONTEXTHELPEND = &HD
        EVENT_SYSTEM_DRAGDROPSTART = &HE
        EVENT_SYSTEM_DRAGDROPEND = &HF
        EVENT_SYSTEM_DIALOGSTART = &H10
        EVENT_SYSTEM_DIALOGEND = &H11
        EVENT_SYSTEM_SCROLLINGSTART = &H12
        EVENT_SYSTEM_SCROLLINGEND = &H13
        EVENT_SYSTEM_SWITCHSTART = &H14
        EVENT_SYSTEM_SWITCHEND = &H15
        EVENT_SYSTEM_MINIMIZESTART = &H16
        EVENT_SYSTEM_MINIMIZEEND = &H17
        EVENT_SYSTEM_DESKTOPSWITCH = &H20
        EVENT_SYSTEM_END = &HFF
        EVENT_OEM_DEFINED_START = &H101
        EVENT_OEM_DEFINED_END = &H1FF
        EVENT_UIA_EVENTID_START = &H4E00
        EVENT_UIA_EVENTID_END = &H4EFF
        EVENT_UIA_PROPID_START = &H7500
        EVENT_UIA_PROPID_END = &H75FF
        EVENT_CONSOLE_CARET = &H4001
        EVENT_CONSOLE_UPDATE_REGION = &H4002
        EVENT_CONSOLE_UPDATE_SIMPLE = &H4003
        EVENT_CONSOLE_UPDATE_SCROLL = &H4004
        EVENT_CONSOLE_LAYOUT = &H4005
        EVENT_CONSOLE_START_APPLICATION = &H4006
        EVENT_CONSOLE_END_APPLICATION = &H4007
        EVENT_CONSOLE_END = &H40FF
        EVENT_OBJECT_CREATE = &H8000
        EVENT_OBJECT_DESTROY = &H8001
        EVENT_OBJECT_SHOW = &H8002
        EVENT_OBJECT_HIDE = &H8003
        EVENT_OBJECT_REORDER = &H8004
        EVENT_OBJECT_FOCUS = &H8005
        EVENT_OBJECT_SELECTION = &H8006
        EVENT_OBJECT_SELECTIONADD = &H8007
        EVENT_OBJECT_SELECTIONREMOVE = &H8008
        EVENT_OBJECT_SELECTIONWITHIN = &H8009
        EVENT_OBJECT_STATECHANGE = &H800A
        EVENT_OBJECT_LOCATIONCHANGE = &H800B
        EVENT_OBJECT_NAMECHANGE = &H800C
        EVENT_OBJECT_DESCRIPTIONCHANGE = &H800D
        EVENT_OBJECT_VALUECHANGE = &H800E
        EVENT_OBJECT_PARENTCHANGE = &H800F
        EVENT_OBJECT_HELPCHANGE = &H8010
        EVENT_OBJECT_DEFACTIONCHANGE = &H8011
        EVENT_OBJECT_ACCELERATORCHANGE = &H8012
        EVENT_OBJECT_INVOKED = &H8013
        EVENT_OBJECT_TEXTSELECTIONCHANGED = &H8014
        EVENT_OBJECT_CONTENTSCROLLED = &H8015
        EVENT_SYSTEM_ARRANGMENTPREVIEW = &H8016
        EVENT_OBJECT_END = &H80FF
        EVENT_AIA_START = &HA000
        EVENT_AIA_END = &HAFFF
    End Enum

    ' SetWinEventHook Window Objects
    Friend Enum SWEH_ObjectId As Long
        OBJID_WINDOW = &H0
        OBJID_SYSMENU = &HFFFFFFFFUI
        OBJID_TITLEBAR = &HFFFFFFFEUI
        OBJID_MENU = &HFFFFFFFDUI
        OBJID_CLIENT = &HFFFFFFFCUI
        OBJID_VSCROLL = &HFFFFFFFBUI
        OBJID_HSCROLL = &HFFFFFFFAUI
        OBJID_SIZEGRIP = &HFFFFFFF9UI
        OBJID_CARET = &HFFFFFFF8UI
        OBJID_CURSOR = &HFFFFFFF7UI
        OBJID_ALERT = &HFFFFFFF6UI
        OBJID_SOUND = &HFFFFFFF5UI
        OBJID_QUERYCLASSNAMEIDX = &HFFFFFFF4UI
        OBJID_NATIVEOM = &HFFFFFFF0UI
    End Enum

    ' WinEventDelegate flags
    Friend Enum SWEH_dwFlags As UInteger
        WINEVENT_OUTOFCONTEXT = &H0     ' Events are ASYNC - No dll needed
        WINEVENT_SKIPOWNTHREAD = &H1    ' Don't call back for events on installer's thread
        WINEVENT_SKIPOWNPROCESS = &H2   ' Don't call back for events on installer's process
        WINEVENT_INCONTEXT = &H4        ' Events are SYNC, this causes your dll to be injected into every process
    End Enum

    ' SetWindowPos flags
    <Flags>
    Public Enum SWP_Flags As UInteger
        SWP_NOSIZE = &H1
        SWP_NOMOVE = &H2
        SWP_NOZORDER = &H4
        SWP_NOREDRAW = &H8
        SWP_NOACTIVATE = &H10
        SWP_DRAWFRAME = &H20
        SWP_FRAMECHANGED = &H20
        SWP_SHOWWINDOW = &H40
        SWP_HIDEWINDOW = &H80
        SWP_NOCOPYBITS = &H100
        SWP_NOOWNERZORDER = &H200
        SWP_NOREPOSITION = &H200
        SWP_NOSENDCHANGING = &H400
        SWP_NOCLIENTSIZE = &H800
        SWP_NOCLIENTMOVE = &H1000
        SWP_DEFERERASE = &H2000
        SWP_ASYNCWINDOWPOS = &H4000
    End Enum
End Class

A: Thanks to the great help of Jimi, I was able to get it work:
Add the NativeMethods class to the project, use the code from Jimi's answer above
Use the following code in the form:
Imports System.Runtime.InteropServices
Imports WindowsApp1.NativeMethods
Public Class Form1
    Private ReadOnly ForegrundChangedEventDelegate As WinEventDelegate
    Private Shared GCForegroundStateSafetyHandle As GCHandle
    Declare Auto Function SetParent Lib "user32.dll" (ByVal hWndChild As IntPtr, ByVal hWndNewParent As IntPtr) As Integer
    Declare Auto Function SendMessage Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal Msg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    Declare Auto Function GetWindowThreadProcessId Lib "user32.dll" (ByVal hwnd As IntPtr, ByRef lpdwProcessId As Integer) As Integer
    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim proc As Process
        Dim ProcId As Integer = 0
        proc = Process.Start("notepad.exe")
        proc.WaitForInputIdle()
        SetParent(proc.MainWindowHandle, Me.Panel1.Handle)
        SendMessage(proc.MainWindowHandle, 274, 61488, 0)
        GetWindowThreadProcessId(proc.MainWindowHandle, ProcId)
        SetForegroundStateChangedHook(proc.MainWindowHandle)
    End Sub
    Public Sub New()
        InitializeComponent()
        ForegrundChangedEventDelegate = New WinEventDelegate(AddressOf ForegroundStateChangedCallback)
        GCForegroundStateSafetyHandle = GCHandle.Alloc(ForegrundChangedEventDelegate)
    End Sub
    Protected Overrides Sub OnHandleDestroyed(e As EventArgs)
        GCForegroundStateSafetyHandle.Free()
        UnhookWinEvent(hForegrundChangedEventHook)
        MyBase.OnHandleDestroyed(e)
    End Sub
    Private Sub SetForegroundStateChangedHook(hWnd As IntPtr)
        Dim processId As UInteger
        Dim targetThreadId = GetWindowThread(hWnd, processId)
        hForegrundChangedEventHook = WinEventHookOne(SWEH_Events.EVENT_SYSTEM_FOREGROUND, ForegrundChangedEventDelegate, processId, targetThreadId)
    End Sub
    Friend Sub ForegroundStateChangedCallback(hWinEventHook As IntPtr, eventType As SWEH_Events, hWnd As IntPtr, idObject As SWEH_ObjectId, idChild As Long, dwEventThread As UInteger, dwmsEventTime As UInteger)
        If idObject = SWEH_ObjectId.OBJID_WINDOW AndAlso eventType = SWEH_Events.EVENT_SYSTEM_FOREGROUND Then
            Dim flags = SWP_Flags.SWP_ASYNCWINDOWPOS Or SWP_Flags.SWP_NOACTIVATE Or SWP_Flags.SWP_NOSIZE Or SWP_Flags.SWP_NOMOVE
            SetWindowPos(Handle, IntPtr.Zero, 0, 0, 0, 0, flags)
        End If
    End Sub
    End Class


text:
Q: How to Loop Through Swift Image and Test Pixel RGB Value? I have just started trying to learn Swift this past week. I am trying to write code to loop through an image in Swift and compare each pixel value to see if it matches a range of colors (a range of RGB values).
The image I would want to use would be one displayed in a UI image that the user has selected from the photo library (I have this part of the code done). I found this code on stackoverflow for looking at a pixel and getting its R, G, and B value:
extension UIImage {
    func getPixelColor(pos: CGPoint) -> UIColor {

        let pixelData = CGDataProviderCopyData(CGImageGetDataProvider(self.CGImage))
        let data: UnsafePointer<UInt8> = CFDataGetBytePtr(pixelData)

        let pixelInfo: Int = ((Int(self.size.width) * Int(pos.y)) + Int(pos.x)) * 4

        let r = CGFloat(data[pixelInfo]) / CGFloat(255.0)
        let g = CGFloat(data[pixelInfo+1]) / CGFloat(255.0)
        let b = CGFloat(data[pixelInfo+2]) / CGFloat(255.0)
        let a = CGFloat(data[pixelInfo+3]) / CGFloat(255.0)

        return UIColor(red: r, green: g, blue: b, alpha: a)
    }
}

Could someone help me to write code that links this code to run on the photo the user selects and to loop through each pixel?


text:
Q: Best practice for monitoring and killing an activity from a background service? I'm trying to figure out the most efficient way of using ActivityManager to programmatically monitor when a package is running/executed, and then to programmatically kill it. I can do it on demand using manager.killBackgroundProcesses(processName) with 2.2, and my code works fine for that, but i'd like to register a background service monitor if possible.. Or some sort of an intent launching monitor for the specific package name?
What would be the most efficient and dependable way to do this?
Note: This isn't for any sort of a behind-the-scenes, malicious kill... I am calling <uses-permission android:name="android.permission.KILL_BACKGROUND_PROCESSES" /> in my manifest, so users will know exactly what the app does.

A: I believe the best practice would be using the AlarmManager to schedule your polling. The downside is that the AlarmManager only polls on a preset number of intervals.  The smallest interval is 15 minutes.  For majority of circumstances, I think this is enough.

A:
i'd like to register a background service monitor if possible

There is no such concept in Android.

Or some sort of an intent launching monitor for the specific package name?

There is no such concept in Android.

I need it to be relatively instant.. or within seconds or so. I don't think constantly polling would be very efficient.

Then you will simply have to live with inefficiency, or don't write the app. Android is not set up to support apps like the one you are trying to write.


text:
Q: Specify a specific double precision literal in c# How can I specify a specific double precision literal or value in c#?
For example, I would like to use the constant of the largest double value less than one in a program. The largest double less than one is 1.11111111 11111111 11111111 11111111 11111111 11111111 1111 x 2^(-1) in binary. Expressing this as a big-endian double in hex would be 0x3fe f ffff ffff ffff
I can generate it with the following code:
var largestDoubleLessThanOneBytes = new byte[] {0x3f, 0xef, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff};
if (BitConverter.IsLittleEndian) largestDoubleLessThanOneBytes = largestDoubleLessThanOneBytes.Reverse().ToArray();
double largestDoubleLessThanOne = BitConverter.ToDouble(largestDoubleLessThanOneBytes, 0);

BitConverter can't be used in the declaration of a const, so this can't be used in place of a literal value.
Using this tool, I can come up with the literal 9.99999999999999888977697537484E-1, which ends up being exactly the same double. BitConverter.ToString(BitConverter.GetBytes(9.99999999999999888977697537484E-1)) == "FF-FF-FF-FF-FF-FF-EF-3F".
Is there any other way to get specific double values into c# code than to find a decimal literal whose closest double representation is the double you want?

A: This is probably overkill, but damn, why not?
unsafe
{
    var x = 0x3fefffffffffffff;
    var d = *(double*)&x;
    Console.WriteLine("{0:r}", d);
}

hello, reinterpret_cast<> in C#


text:
Q: Attaching a custom function to amp "on" attribute <select id="gtranslator" on="change:gtranslator.doGTranslate(this)">
  <option value="">Select Language</option>
  <option value="arabic">arabic>
  <option value="english">arabic>
</select>

What i want, is to be able to execute the doGTranslate(this) function on an amp page.
Am new to amp, so am trying it out with a project.
Thanks.


text:
Q: How appear VerticalScrollBar in resize window in ListView? <UserControl x:Class="PMS.UserControlUsersList"
//...
             xmlns:local="clr-namespace:PMS"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800">

    <UserControl.Resources>
        <Style x:Key="ListViewStyle" TargetType="{x:Type GridViewColumnHeader}">
            <Setter Property="HorizontalContentAlignment" Value="Left" />
        </Style>
    </UserControl.Resources>

    <Grid>
        <DockPanel>
                <Expander Grid.Row="0" Header="Filters" Margin="10" Background="White" DockPanel.Dock="Top">
                    <Grid>
                       //...
                    </Grid>
                </Expander>

            <ListView Margin="10" ItemsSource="{Binding FilteredUsers}">
                <ListView.View>
                    <GridView>
                        <GridViewColumn HeaderContainerStyle="{StaticResource ListViewStyle}" Header="First name" DisplayMemberBinding="{Binding FirstName}" Width="Auto"/>
                        <GridViewColumn HeaderContainerStyle="{StaticResource ListViewStyle}" Header="Last name"  DisplayMemberBinding="{Binding LastName}" Width="Auto"/>

//other GridViewColum

                    </GridView>
                </ListView.View>
            </ListView>

        </DockPanel>
    </Grid>

</UserControl>

Hello. When I resize window VerticalScrollBar in ListView doesn't appear.
HorizontalScrollBar works fine. How I can fix this?
When I set MaxHeight VerticalScrollBar is visible but this isn't good solution :P
UserControl is placing in StackPanel:
 <StackPanel x:Name="StackPanelMain" Grid.Row="1" Grid.Column="1" HorizontalAlignment="Stretch">
      <!-- my UserControl is here -->
 </StackPanel>

Edit:
Look how it looks with me. UserControl is displayed in the bottom right corner. On the left is a menu and a bar at the top. In the main window I use WindowStyle = "None".
Error
It's good
Here, I pasted the full Window and Usercontrol code: full code

A: You are placing your nested ListView inside a StackPanel, which prevents it from calculating its size properly. Instead, your control renders to invisible area thus not showing a vertical scrollbar.
Consider changing your container panel to Grid.
See also: WPF ListView no scrollbar if height set to auto


text:
Q: Can't ping specific IP via OpenVPN I have an OpenVPN server set up via my Asus DSL-AC68U router, and can connect to it remotely and access the internet through it without issues, using both my iOS device and Tunnelblick on OS X as clients.
However, when accessing via VPN, my client cannot access/ping a specific IP on the LAN - I can ping/access 4 devices on the network apart from just one. The specific computer I am trying to connect to is a JACE NiagaraAX, which is possibly linux-based, set to a static ip of 10.0.10.88
I have no problem connecting/pinging it from the same subnet as it on the LAN (10.0.10.0 subnet), but cannot, for the life of me, figure out how to access it via the VPN (10.8.0.0 subnet).
Is this a routing issue? I'm not sure, because when I do a traceroute via the VPN it seems to me to be trying to connect to it via the correct gateway (10.8.0.1 is my VPN server gateway):
#traceroute 10.0.10.88
traceroute to 10.0.10.88 (10.0.10.88), 64 hops max, 52 byte packets
1  10.8.0.1 (10.8.0.1)  25.904 ms  25.042 ms  24.276 ms
2  * * * *
3  * * * *`

Here is my configuration for OpenVPN (mostly the Asus AC68U defaults):

*

*Interface Type: TUN

*Protocol: UDP

*Server Port: 1194

*Firewall: Auto

*Authorization Mode: TLS

*Username/Password Auth. Only: No

*Extra HMAC authorization: Disable

*VPN Subnet / Netmask: 10.8.0.0 255.255.255.0

*Poll Interval: 0

*Push LAN to clients: Yes

*Direct clients to redirect traffic: No

*Respond to DNS: Yes

*Advertise DNS to clients: Yes

*Encryption cipher: Default

*Compression: Adaptive

*TLS Regeneration Time: -1

*Manage client specific options: No

A: It turned out that the gateway on the computer I was trying to connect to wasn't set correctly.
Once I set it to 10.0.10.1 I could immediately connect to it via the remote computers on the VPN (10.8.0.0 subnet).


text:
Q: Angluar2 Observable UI - Update Children in Object Array force Change? Let's say I have a simple array object like so:
validationMessages = {
    'name': [{
        'type': 'required',
        'message': 'Name is required.',
        'enabled': 1
    },
    {
        'type': 'maxlength',
        'message': 'Name cannot be more than 50 characters long.',
        'enabled': 0
        }],
    'description': [
        {
            'type': 'required',
            'message': 'Description is required.',
            'enabled': 0
        },
    ]
};

I'm then displaying on load in my UI like so:
        <div *ngFor="let err of validationMessages.name">

            <div *ngIf="err.enabled == 1"  class="alert alert-danger">

                {{err.message}}
            </div>
        </div>

Working fine.
However what I'd like to do is be able to update validationMessages.name array to update a given object to mark enabled 1 or 0. I'd want this then to update/re-run my UI.
I'm sure this can be done using observables, but what am I missing to do this?

A: If you don't modify the object within some event (button click, value change) or async call, you must tell Angular that you want the component to be refreshed.
controller(private changeDetectorRef: ChangeDetectorRef) {}
changeValidationMessages(): void {
   this.validationMessages...enabled = 0;
   this.changeDetectorRef.markForCheck();
}

There is no need to use Observables for that, but if you did, you would probably use the async pipe to display the messages. The pipe calls the ChangeDetectorRef itself.
The other way of making sure model changes get reflected in UI is using immutable objects (creating a new object copy whenever you want to modify an existing one), but it also adds some complexity.
Angular's change detection system is a topic worth knowing in more detail. You can check the following articles:

*

*https://blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection-explained.html

*https://blog.thoughtram.io/angular/2017/02/27/three-things-you-didnt-know-about-the-async-pipe.html


text:
Q: Jquery : Refresh/Reload the page on clicking a button I have a button which loads after a ajax call , on clicking  i want to reload the page (like i press f5)
I tried
$( ".delegate_update_success" ).click(function() {
    location.reload();
});

but it does a simple refresh, but my page does not makes a new request to get the contents.
It should happen just like I am entering URL to get that page.

A: Use document.location.reload(true) it will not load page from cache.

A: You can also use window.location.href=window.location.href;

A: Use this line simply inside your head with
       window.location.reload(true);

It will load your current page or view.

A: You should use the location.reload(true), which will release the cache for that specific page and force the page to load as a NEW page.
The true parameter forces the page to release it's cache.

A: If your button is loading from an AJAX call, you should use
$(document).on("click", ".delegate_update_success", function(){
    location.reload(true);
});

instead of
$( ".delegate_update_success" ).click(function() {
    location.reload();
});

Also note the true parameter for the location.reload function.

A: use window.location.href = url

A: simple way can be -
just href="javascript:location.reload(true);
your answer is
location.reload(true);

Thanks


text:
Q: Localized connected expansions Given a connected space, it is easy to tell if there is a connected expansion because maximal connected spaces (those admitting no finer connected topology) have the property that every dense subset is open.  If you can find a dense subset $D$ which is not open (typically this is very easy to find), then the topology generated by $\tau$ with $D$ is a connected expansion.
My question is a little more specific.
Let $X$ be infinite connected Hausdorff space with collection of open sets $\tau$.   Given a nowhere dense infinite set $S\subseteq X$, I would like to know when it is possible to find a subset of $S$ which can be added to $\tau$ to produce a topology that is still connected.  Are there conditions depending $\tau$ and $S$ which will guarantee this is possible?


text:
Q: PHP - printf with json arguments I tried to pass as arguments in printf encoded json array. However, due to the nature of the json array it creates an error with printf: printf(): Too few arguments
Is there a way to pass encoded json array in printf method like this:
$val   = 10;
$min   = 0;
$max   = 100;
$steps = array( 1, 0.1, 0.01 );
$units = array( 'px', 'em', '%' );

printf(
    '<input type="range" value="%d" min="%d" max="%d" step="0.01" data-steps="%s" data-units="%s">',
    floatval( $val ),
    floatval( $min ),
    floatval( $max ),
    json_encode( $steps ),
    json_encode( $units )
);

Thank you

A: Your code is fine but it generates this piece of HTML
<input type="range" value="10" min="0" max="100" step="0.01"
       data-steps="[1,0.1,0.01]" data-units="["px","em","%"]">

which is invalid because of the double quotes included in the JSON content.
Any dynamic content you use to generate HTML must be properly HTML-encoded. Use htmlspecialchars() to encode the values returned by json_encode() before passing them to printf() to generate valid HTML:
$val   = 10;
$min   = 0;
$max   = 100;
$steps = array( 1, 0.1, 0.01 );
$units = array( 'px', 'em', '%' );

printf(
    '<input type="range" value="%d" min="%d" max="%d" step="0.01" data-steps="%s" data-units="%s">',
    floatval( $val ),
    floatval( $min ),
    floatval( $max ),
    htmlspecialchars( json_encode( $steps ) ),
    htmlspecialchars( json_encode( $units ) )
);

The values returned by floatval() do not need this treatment because they do not contain HTML special characters.


text:
Q: Displaying error messages from Controller in View I have seen a lot of people say that using Viewdata or ViewBag is not a good practice for this matter(displaying messages from the controller) because of security reasons. Everyone seems to suggest ModelState
My question is what is wrong with using viewdata to display error messages? If we arent supposed to use ViewData then what should we use it for?

A: As @shenku answered before, ViewData and ModelState reference the exact same thing, if you look at the code for System.Web.Mvc.Controller class you will see the implementation for ModelState is:
   public ModelStateDictionary ModelState
    {
      get
      {
        return this.ViewData.ModelState;
      }
    }

and @JimmiTh said,
although the main use of ModelState from an "end developer"'s perspective is in the controller, ViewData is used as a container for all data that's communicated between the controller and the view. Which is why it also needs to include ModelState - because, although you'd rarely use it directly in the view, ModelState is where e.g. many of the HtmlHelper methods actually get the values from by default when rendering the view from a POST action - rather than Model.


text:
Q: Multiple user interaction using photon in MRTK application We are working on an app for Hololens2. In this app multiple users can join a room and can perform different hand movements. Here challenge is, we also need to show hands of the users along with their names.
Need your help in understanding resolution for this issue.

A: You need to use Photon's methods to instantiate the hand prefab and then use it as a copy for live sharing. You can find hand prefabs in Mixed Reality Toolkit Foundation->SDK->Features->UX->Prefabs->RiggedHandVisualizer. Then you need to map the current hand position, rotation to this copy. You can also try to map the hand joints, please refer to Hand tracking - MRTK 2 | Microsoft Learn to get joint data.
For the name, you can ask the user to enter a display name for Photon to use before he joins the room. Then you can create a UI for it and have it display with the hand.


text:
Q: How do you apply a function to a nested column using purrr::map, and output to a new column? I'm new to purrr and tidyr in general.  I am trying to map a function to a nested column of datasets, and output as a new column in the main (nested) tibble.
Original attempt does run, but doesn't seem to apply the correct dataset to the functions.  When I run the function on an individual dataset from the datasets column it gives the correct results.  The function when run with all variables via map (see below for syntax used) gives different (incorrect) results.  I'm guessing I have the syntax incorrect and it is applying the function to the wrong dataset - but cannot figure out what the correct syntax should be.
dat is the original dataframe with two nested columns data=original dataset, datatidy=tidy dataset.  I would like to run a function on the datatidy column and output the results as a new (nested column) in dat.
  glimpse(dat)
        >  Observations: 535
        >     Variables: 4
        >     $ SITE_NO  <chr> "BC08EF0001", "BC08EF0001", "BC08EF0001", "BC08EF0001", "BC08EF0001", "BC08EF0001", "BC08EF0001", "B...
        >     $ variable <fct> CHLORIDE, FLUORIDE, SULPHATE, ALUMINUM TOTAL, ARSENIC TOTAL, BORON TOTAL, CADMIUM TOTAL, CHROMIUM TO...
        >     $ data     <list> [<tbl_df[234 x 15]>, <tbl_df[235 x 15]>, <tbl_df[234 x 15]>, <tbl_df[235 x 15]>, <tbl_df[235 x 15]>...
        >     $ datatidy <list> [<tbl_df[116 x 17]>, <tbl_df[116 x 17]>, <tbl_df[116 x 17]>, <tbl_df[116 x 17]>, <tbl_df[116 x 17]>...
        >

> glimpse(dat$dataTidy[[1]])
 $ DecDate        <dbl> 2005.047, 2005.121, 2005.195, 2005.312, 2005.392,
 $ month          <dbl> 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4,
 $ season         <fct> Jan, Feb, Mar, Apr, May, Jun, Jul, Aug, Sep, Oct,
 $ Value          <dbl> 0.5, 0.7, 0.7, 0.3, 0.1, 0.1, 0.1, 0.2, 0.1, 0.4,
 $ Date           <date> 2005-01-18, 2005-02-14, 2005-03-13, 2005-04-25,
 $ Value_subDL    <dbl> 0.50, 0.70, 0.70, 0.30, 0.05, 0.05,
 $ logConcVal     <lgl> FALSE, FALSE, FALSE, FALSE, FALSE, FALSE,

    > results <- mutate(dat
    >         newcol = map(dataTidy, ~ EnvOut_fun(.x$Value_subDL,
    >                                                        time = as.numeric(.x$Date),
    >                                                        group = .x$season,
    >                                                        time.name="as.numeric(Date)",
    >                                                        group.name="season",
    >                                                        y.name="Value_subDL",
    >                                                        LOGY=.x$logConcVal)))

I tried the syntax in the following thread but cannot seem to get it to work.

  dat %>%
    mutate(newcolumn = map(dataTidy, ~ EnvOut_fun(.x[["Value_subDL"]],
                                                   time=as.numeric(.x[["Date"]], ...)))

Example of EnvOut_fun.
The function uses columns from dataTidy to run a seasonal kendall test, and saves the original (list results) as sk, and extracts some info into a dataframe.  A list containing sk and the EnvOut dataframe for each row in the main tibble should be saved to a new nested column.
EnvOut_fun <- function(y, time, group,
                       time.name=NULL, group.name=NULL, y.name="y",
                       LOGY=FALSE){

  y = if(LOGY==FALSE) {y}else{log(y)}
  y.name = if(LOGY==FALSE) { y.name}else{paste0("Log(", y.name,")")}

  sk <- EnvStats::kendallSeasonalTrendTest(y ~ group+time,
                                           year.name="time", season.name="season",
                                           data.name="y.name")

  EnvOut <- tibble(
     tau=sk$estimate[["tau"]],
     slope=sk$estimate[["slope"]],
     int = sk$estimate[["intercept"]],
     p_val_raw = sk$p.value["z (Trend)"],
     slope_p_val = p_val_raw,
     numSeas = length(sk$sample.size)-1  ,
     medOfData = median(y),
     medOfTime = median(time) ,
     time.nm = time.name,
     block.nm = group.name,
     data.nm = y.name,
     LogY = LOGY
  ) %>%
    mutate(int_from_data = medOfData- (slope* medOfTime))

    sk <- list(sk=sk, EnvOut=EnvOut)
 sk
}

EDIT
Both syntaxes above work for applying a user defined function to nested dataframe.


text:
Q: React navigation clearing out data when stored in AsyncStorage - How to view data? I'm using react navigation bottom tab and when I have data stored in my AsyncStorage, the data comes out to be empty when I go into this SavedData component. In the console, if I showAsyncStorageContentInDev(), it shows that I do indeed have the key @storage_key. But when I console log out the data, its always empty. Does it have to do with something with react navigation bottom tab that empty's out the data?
Or how do I view the data when user tabs into this component?
const SavedData = (props) => {
  const [getData, setData] = useState([]);

  const getKeyInfo = async () => {
    try {
      const storedData = await AsyncStorage.getItem('@storage_Key');
      setData(JSON.parse(storedData))
      console.log('saved',getData);
    } catch (e) {
      // saving error
    }
    console.log(getData);
  };

  useEffect(() => {
    console.log(getData);
    getKeyInfo();
  }, []);

  return (
    <View>
      <Text>
        {getData.map((i, index) => (
          <View key={i.id.toString()}>
            <Data uri={i.uri} />
          </View>
        ))}
        ;
      </Text>
    </View>
  );

};

export default SavedExercise;

A: Have you ever try pass getData into the second argument of useEffect to notify for Component re-render when state change:
useEffect(() => {
    console.log(getData);
    getKeyInfo();
}, [getData]); // Here


text:
Q: CGI Python проблема с кодировкой. Добрый день.
Подскажите идеи пожалуйста, есть такая задача - CGI-приложение из веб-формы получает данные, а потом по ним заводит пользователя в Zimbra (путем вызова зимбровского бинарника). Проблема в том, что в форме есть русские символы (unquote естественно делаю), и все бы хорошо. но вот в зимбру они передаются в виде ???????. (английские - как надо)
локаль системы

LANG=POSIX
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=en_US.UTF-8

Локаль sudo и пользователя zimbra - такие же. Питоновский скрипт
-*- coding: utf-8 -*-

В файлы пишет абсолютно прекрасно и читаемо, проблема именно в случае, когда я вызываю
cmd = 'sudo /opt/zimbra/bin/zmprov'
subprocess.Popen(cmd + " ca "+ string_param, shell = True)

Причем дело не в форме, если я укажу переменную внутри скрипта (на русском), то такая же проблема.
До этого пытался сделать скрипт на bash (не хватило функционала), но там эту проблему решил путем
export LANG=POSIX
export LC_CTYPE=en_US.UTF-8 (помоему зимбра тогда ru_RU использовала)

Видимо, дело упирается в этот самый LANG, но как это решить, я не могу понять. Подскажите пожалуйста, замучился уже.
A: subprocess.Popen(u"%s ca %s" % (cmd, string_param), shell = True)

Так пробывали надеюсь?


text:
Q: The table does not have a primary key defined error I have two tables that are basically link tables.
So one looks like this;
QueueId
TaskId

the two columns link to a Queues table and a Tasks table.
There is no primary key and i don't believe I need one.
I so try to import it into my .EDMX and I get the warning that

the table does not have a primary key defined but that it's been inferred as a read only table.

Also, the table doesn't show up in the Diagram and there is no model created for it.
I added a primary key and then got errors in my code.
I deleted all tables and did it all again and still the same thing happens with this one table.
The second table that is virtually identical has the same error but does appear in the diagram.
How do I get the first table to show in the diagram and not be read only because I need to delete the associations from time to time.
Thanks

A: Entity Framework doesn't need association table in the model to work with it.
There should be two navigation properties on either side of the relation - Task has ICollection<Queue> and Queue has ICollection<Task>. To remove association between specific task and queue you either find queue and remove that thask from it's collection, or do the reverse.


text:
Q: jQuery each #anchor do something Need to know how to target each #anchor link to change an image on hover. Currently I am targeting one by one, do I need to wrap this in a each loop function?
Thanks in advance.
var originalpath = $('#fulltraceswap img').attr('src');
var root = window.location.protocol + "//" + window.location.host + "/home/";
//1
$("#fulltracerow .edgtf-iwt-title a[href='#aftermarketimage']").hover(
function(){

    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);

//2
$("#fulltracerow .edgtf-iwt-title a[href='#productlifecycle']").hover(
 function(){

    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);

EDIT
I found out what I wanted by using the a[href^='#'] selecting all links which started with #.
Backstory - I am using a wordpress plugin called visual composer and in the link options it doesn't allow to add a data attribute...unless I hard coded it. So I wanted a quick workaround.
Thanks
 $("#fulltracerow .edgtf-iwt-title a[href^='#']").hover(

 function(){

    //we get our current filename and use it for the src
    var path = root+"wp-content/uploads/2018/06/";
    var linkIndex = $(this).attr("href");
    linkIndex = linkIndex.replace('#', '');

    $('#fulltraceswap img').attr('src', path+linkIndex+".jpg");
    $('#fulltraceswap img').attr('srcset', path+linkIndex+".jpg");
},
function(){

    $('#fulltraceswap img').attr('src', originalpath);
    $('#fulltraceswap img').attr('srcset', originalpath);
}
);

A: No. You don't need use loop because if you specify right selector, then it apply to all matched elements.
Only what you need is define any global selector with any css class (not id) but I recommend to you use html5 data attribute because it is more flexible than css class.
Advice:
1) add data-* eg. data-changeImage for example to all links which use this hover
action.
Test1

2) change a[href='#aftermarketimage'] to global selector with data attribute like data-changeImage for example and then it works.
$("#fulltracerow .edgtf-iwt-title a[data-changeImage]").hover(function() {
    $(this).css('color', 'red');
},
function() {
    $(this).css('color', 'green');
});

JSFIDDLE


text:
Q: Unable to run python script from shell but able to run it from eclipse(PyDev) Python version:2.7 OS: CentOS
I have a python project with multiple files spread across different directories. I am able to run this through Eclipse(PyDev). However I am unable to run it from linux shell.
The directory structure looks like this:
      Projectrepo
          |
          |
        __|__
    src       conf
     |          |
     |          |
 buildexec.py   |
                |
             script_variables, list_of_scripts

buildexec.py is my main script. script_variables and list_of_scripts are two modules which I am referencing from buildexec.py.
I have included from conf.script_variables import * in my main script and it is working fine when I run it on eclipse. But, when I try to run it on shell, I get an error
'Traceback (most recent call last):
  File "buildexec.py", line 6, in <module>
    from conf.script_variables import *
ImportError: No module named conf.script_variables'
I have added PYTHONPATH=/usr/bin/python2.7 and have exported it..
Also, in the main script, I have added
sys.path.append('/home/tejas/Projectrepo/conf') before importing the modules.

A: Was a simple solution! My pythonpath was pointing to the default directory /usr/bin/python2.7. I added the location of the user defined modules also in the python path using                                                            export PYTHONPATH=/usr/bin/python2.7:/home/tejas/Projectrepo/conf


text:
Q: Unable to add a date time value in Cassandra DB? Invalid syntax error? Problem:
I'm currently trying to insert a date time object into my Cassandra database using the following code:
dt_str = '2016-09-01 12:00:00.00000'
dt_thing = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S.%f')

def insert_record(session):
    session.execute(
        """
        INSERT INTO record_table (last_modified)
        VALUES(dt_thing)
        """
        )

However, I'm receiving the following error:
cassandra.protocol.SyntaxException: <Error from server: code=2000 [Syntax error in CQL query] message="line 3:17 no viable alternative at input ')' (...record_table (last_modified)        VALUES([dt_thing])...)">

Background Info
I'm relatively new to Cassandra and I'm not sure how to go about this. What I'm basically trying to do is add an existing date time value in my database since an earlier version of the code is looking for one but it does not exist yet (hence, why I'm manually adding one).
I'm using Python 2.7 and Cassandra 3.0.
Any input or how to go about this would be great!

A: I answered a similar question yesterday.  But the general idea, is that you'll want to define a prepared statement.  Then bind your dt_thing variable to it, like this:
dt_str = '2016-09-01 12:00:00.00000'
dt_thing = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S.%f')

def insert_record(session):
    preparedInsert = session.prepare(
        """
        INSERT INTO record_table (last_modified)
        VALUES (?)
        """
        )
    session.execute(preparedInsert,[dt_thing])

Also, I don't recommend using a timestamp as a lone PRIMARY KEY (which is the only model for which that INSERT would work).


text:
Q: Trying to mock Angular2 Token in Test So I'm trying to get a token since its needed in the api authentication to get a list. I start of with importing the angular2-token:
import { Angular2TokenService } from 'angular2-token';

Then I add the describe block:
describe('ListComponent Tests', () => {
  let token: Angular2TokenService;

  beforeAll(() => {
    token.init();
    token.signIn('test@email.com', 'foobar');
  }
}

But I'm getting the error:
TypeError: Cannot read property 'init' of undefined

Now I'm uncertain how to actually get a login token in test.

A: You haven't initialize the token to anything, hence the error. When you create a mock of a service for a component-under-test, often is it enough to just create a spy for the functions that are expected to be called. Then in the test you just want to check that the component actually calls the functions. You will also need to substitute the real service for the mock service, so you need to configure the mock as provider substitute. For example
@Component({
  ...
})
class TestComponent {
  constructor(private token: Angular2TokenService) {}

  ngOnInit() {
    token.init();
  }

  onLogin(email, password) {
    token.signIn(email, password);
  }
}

describe('..', () => {
  let tokenStub;
  let component;
  let fixture;

  beforeEach(() => {
    tokenStub = {
      init: jasmine.createSpy('init'),
      signIn: jasmine.createSpy('signIn')
    }

    TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      providers: [{ provide: Angular2TokenService, useValue: tokenStub }]
    })

    fixture = TestBed.createComponent(TestComponent);
    component = fixture.componentInstance;
  })

  it('should init the token when component created', () => {
    fixture.detectChanges();
    expect(tokenStub.init).toHaveBeenCalled();
  })

  it('should signin token when component login', () => {
    component.onLogin();
    expect(tokenStub.signIn).toHaveBeenCalledWith('test@email.com', 'foobar')
  })
})

You can see that you check that the functions are called by using the toHaveBeenCalledXxx methods, which can take arguments.
If you aren't using the TestBed configuration, then you can easily make it an isolated test by simply doing something like
let tokenStub: Angular2TokenService;
let component;

beforeEach(() => {
  tokenStub = {
    init: jasmine.createSpy('init'),
    signIn: jasmine.createSpy('signIn')
  } as Angular2TokenService;

  component = new TestComponent(tokenStub);
})

it('..', () => {
  component.ngOnInit();
  expect(tokenStub.init).toHaveBeenCalled();
})

Make sure to read the docs on spies that linked to above. You can do other stuff with spies like make them return specific things, and more.


text:
Q: setting div height to full display height this is all over the stackoverflow,but it doesn't work for me.
using twitter bootstrap 3, i need to set the jumbotron class div to full display height.
this is my test site:
http://test.ulkas.eu/
i read i shall include
html {
    height: 100%;
}
body {
    min-height: 100%;
    padding-top: 50px;
}

but it still doesn't work. maybe i got some syntax error somewhere?

A: The height of your html / body will always only be the height of your content - those tags behave slightly different to standard div / block tags. To get something to be truly 100% high your best bet is to remove it from the standard flow of the page using position: absolute / fixed, then set your div to be 100% high. Something like this:
.fullheight {
    position: absolute;
    top: 0px;
    left: 0px;
    height: 100%;
    width: 100%;
    z-index: 2;
}

I think it's always worth setting a z-index on anything I position outside the normal page flow, allows you to control which parts appear on top of others.

A: In order to apply 100% height property to inner divisions you need to mention the same property to all the parent divs. So add
body{height: 100%;min-height:100%;padding-top:50px;}

.jumbotron{height:100%;}

to your body as well as to jumbortron class


text:
Q: Issues with Resharper Search with Pattern/Structural Replacement functionality I am trying to use Resharper's Search with Pattern/Structural Replacement functionality to find (cs)html fragments like the following, with the end goal of replacing said code with an editor template:

@Html.LabelFor(model => model.FirstName)

@Html.TextBoxFor(model => model.FirstName, new { @class = "text" })
@Html.ValidationMessageFor(model => model.FirstName)

I am using the following pattern, but I receive an error saying that the search pattern could not be parsed:
@Html.LabelFor(model => model.$propertyName$)

@Html.LabelFor(model => model.$propertyName$)

@Html.TextBoxFor(model => model.$propertyName$, new { @class = "text" })
@Html.ValidationMessageFor(model => model.$propertyName$)

Can anyone tell me:

*

*If I am doing something wrong

*If Resharper's pattern functionality is capable of dealing with HTML

*If Resharper's pattern functionality is capable of dealing with multiline patterns

Thanks in advance
JP

A: ReSharper 6.0 doesn't support SSR in HTML, but 6.1 will.
But still, only plain HTML (in html, aspx, cshtml files), but not Razor constructions, like @Html.
So, your pattern will not work even in 6.1.
P.S. Yes, ReSharper is capable of handling multiline patterns.


text:
Q: Wordpress - Display "Custom Author Role Name" - WP Members Plugin Installed I tried to display the custom author name than I created with WP_Members Plugin. I used this function inside function.php of my theme.
function get_author_role_name(){
    $role = get_the_author_meta('roles')['0'];
    echo esc_html($role);
}

It works fine, but it displays the "slug" of the role. I would like to display the name!
Ex. Name: "My Custom Role", the function displays "my-custom-role".
So, I could replace "-" with a space " " and I could use ucwords() function, but, is there a function to get the real name directly? I can't find it!
Thanks
EDIT - SOLUTION HERE:
function get_author_role_name(){
    $get_role = get_the_author_meta('roles')['0'];
    global $wp_roles;
    $role = $wp_roles->roles[$get_role]['name'];
    echo esc_html($role);
}

A: Based on above link, I edited my function like so:
function get_author_role_name(){
    $get_role = get_the_author_meta('roles')['0'];
    global $wp_roles;
    $role = $wp_roles->roles[$get_role]['name'];
    echo esc_html($role);
}


text:
Q: .Net what new Regex(@"[ ]{2,}", options) means What's happening in this code snippet ?
    RegexOptions options = RegexOptions.None;
    Regex regex = new Regex(@"[ ]{2,}", options);
    string outStr = regex.Replace(inStr, @" ");

What I am looking for is to replace any sequences of "white" spaces ( including TAB, CR, LF )   with a single space.

A: Let's break it down:
[ ]          <-- matches a single space
{2,}         <-- previous token is repeated 2 or more times

So this would match 2 or more consecutive spaces.
Then the .Replace call, this would replace those sequences of 2 or more spaces with just one space.

A: [ ] denotes a character group (in this case only a single whitespace)
{2,} means "at least 2 times"
so, this code replaces multiple occurences of a space with a single one
which is much easier to write (and read) as: " +" (one or more spaces) and then replace them with a single one (shouldn't be slower after all)

A: This line:
Regex regex = new Regex(@"[ ]{2,}", options);

Creates a regular expression object, that will look for occurrences of 2 or more adjacent spaces. The [ ] creates a character group that contains a space - it could have been written as a , but would then be less readable is my guess. The {2,} means 2 or more (unbounded) of the previous character (or character group).
See this handy RegEx cheat sheet for .NET regex syntax.
This line finds all such occurrences and replaces them with one space:
string outStr = regex.Replace(inStr, @" ");

The replace function finds all matches of the regex in the first string parameter, and replaces them with the second string.
In both cases, there is no need for a verbatim string literal (starting with @).

A: @ - verbatim string literal; the characters are not interpreted till next quote
[ ] - in this brackets we specify whit characters are allowed or not. This([ ]) any whitespace it is possible that author wanted to use replace only space but for this should be used pattern \s
{2,} - At least two time
Probably this Regex had to remove double spaces


text:
Q: не могу наложить картинки одна на другую в общем,делал я верстку макета и нужно сделать слайдер, но для начала надо нажить картинки одну на другую(они примерно одинакового размера)

.fade-slider {
   width: 100%;
   height: 100%;
   display: block;
}

.fade-slider__item--style-one {
    background: url(./img/lol.jpg) center center / contain no-repeat;
    height: 100%;
    left: 0;
    top: 0;
}

.fade-slider__item--style-two {
    background: url(./img/kek.jpg) center center / contain no-repeat;
    height: 100%;
    left: 0;
    top: 0;
}

very

mesmerizing,

unexplored

space

So beautiful

universe

A: необходимо задать свойство смещаемым блокам:
    position: absolute;

.fade-slider {
   width: 100%;
   height: 100%;
   display: block;
}

.fade-slider__item--style-one {
    position: absolute;
    background: url(./img/lol.jpg) center center / contain no-repeat;
    height: 100%;
    left: 0;
    top: 0;
}

.fade-slider__item--style-two {
    position: absolute;
    background: url(./img/kek.jpg) center center / contain no-repeat;
    height: 100%;
    left: 0;
    top: 0;

    color: red;
}

very

mesmerizing,

unexplored

space

So beautiful

universe


text:
Q: UISegmentedControl switch views in uitableviewcontroller I have the following scenario:
UITabBarController
--tab1
--tab2
----UINavigationController (with a UITableViewController and 3 rows)
------pushedViewController
--tab3
--tab4
--tab5

Ok, so, when user clicks on an option in the UINavigationViewController it pushes "pushedViewController", and in that viewcontroller I want to have a segmented control like the one on the App Store http://i.stack.imgur.com/hrdxL.png
How can I do this?
I already checked
https://stackoverflow.com/questions/1559794/changing-views-from-uisegmentedcontrol
https://stackoverflow.com/questions/5280653/uisegmentedcontrol-to-switch-views-in-uitabbarcontroller
http://www.astroryan.com/?p=19
https://stackoverflow.com/questions/8723094/using-uisegmentedcontrol-to-switch-between-two-views

This could help me but I can't figure out how
Switch between UIViewControllers using UISegmentedControl
And this user asked the same but it doesn't have the full code
Recreating Segmented Control from iPhone App Store

A: The pushedViewController can contain a UIScrollView framed to fill the screen.  Set paging enabled, and give it three big subviews, like this:
CGFloat width = self.view.bounds.width;
CGFloat height = self.view.bounds.height;

// it's easier to do all this this in xib/storyboard, but to illustrate...

self.scrollView.frame = CGRectMake(0,0,width,height);
self.scrollView.contentSize = CGSizeMake(width*3.0, height);  // this must be done in code
self.scrollView.pagingEnabled = YES;

UIView *subviewA, *subviewB, subviewC;

subviewA.frame = CGRectMake(0.0, 0.0, width, height);
subviewB.frame = CGRectMake(0.0, width, width, height);
subviewB.frame = CGRectMake(0.0, 2.0*width, width, height);

[self.scrollView addSubview:subviewA];
[self.scrollView addSubview:subviewB];
[self.scrollView addSubview:subviewC];

// then when the segmented control changes ...

- (IBAction)segmentedControlChanged:(UISegmentedControl *)sender {

    NSInteger page = sender.selectedSegmentIndex;
    CGFloat contentOffsetX = page*self.view.bounds.width;
    [self.scrollView setContentOffset:CGPointMake(contentOffsetX, 0.0) animated:YES];
}


text:
Q: Wrong results from custom reference system I'm trying to define a custom CRS in QGIS using PROJ4 format.
Here's the string I used:
+proj=tmerc +ellps=GRS80 +datum = ETRS89 +lon_0 =11.86 +lat_0 = 0 +x_0 =40000 +y_0=-6013000 +units=m +towgs84=0,0,0,0,0,0,0 +to_meter +nodefs
here's the original geodetic infos:

WGS84 coordinates lat = 54.95 lon = 11.86 should give me something like x = 39763 y = 79272 instead I get y = 14296754 x = 757997.
Does anybody know what I'm missing/doing wrong?
Please be kind with this newbie

A: Check this
+proj=tmerc +lat_0=0 +lon_0=11.86667 +k=1 +x_0=40000 +y_0=-6013000 +ellps=GRS80  +towgs84=0,0,0,0,0,0,0 +units=m +no_defs


text:
Q: How to make Linear Gradient work in HTA in IE10 and IE11 without using  I have a CSS3 linear gradient in my HTA that won't display in IE10 or IE 11 unless I have the 'meta http-equiv="x-ua-compatible" content="IE=edge"' tag in my HTA. If I don't have this it just displays a white background. This is the CSS....
html {
       height: 100%;
}

body {
       background-image:
            linear-gradient(to bottom, #800000 0%, #DB7093 100%);
       filter:
            progid:DXImageTransform.Microsoft.Gradient(GradientType=0, StartColorStr='#800000', EndColorStr='#DB7093');

       height: 100%;
       margin: 0;
       background-repeat: no-repeat;
       background-attachment: fixed;
       font: 14 pt arial;
       color: white;
}

As long as I have the META tag it works fine, but my question is why doesn't it work without this tag?? Surely I don't have to be in Compatibility mode if I am using the latest version of IE with the latest syntax?
<html>
  <head>
     <meta http-equiv="x-ua-compatible" content="IE=edge" />
     <HTA:application id="main" applicationName="Test HTA" />

     <link rel="stylesheet" type="text/css" href="test.css" />

A: If you add a Windows Registry key for mshta.exe under FEATURE_BROWSER_EMULATION you can make your HTA default to IE10/IE11 mode without the need of a meta tag. This is documented http://msdn.microsoft.com/en-us/library/ee330730(v=vs.85).aspx but to save you time, the registry key is:
New DWORD (32-bit) Value
Name: mshta.exe
Value: 0x00002AF9 (11001)

On a 32-bit Windows machine, it's located under:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION

On a 64-bit Windows machine, it's located under:
HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Internet Explorer\MAIN\FeatureControl\FEATURE_BROWSER_EMULATION


text:
Q: IndexError: Cannot choose from an empty sequence Python I'm having an issue with an index error in a AI which can play wordle. The AI can run through a couple of attempts at words, getting them right, but will usually mess up on the 3rd simulation and throw an index error. I'm aiming to remove every word which contains a character which is greyed out in the first section, but this seems to reduce the word list to 0, causing the index error. The sections for green and yellow characters are working as intended too. Is there any better way I can write this?

*

*Guess counter is the amount of guesses the AI has made

*Letter_states is the state of each letter, -1 being yellow (in the word but not right location), 0 (not in the word) and 1 (in the right spot for the word).

*Letter_indexes refers to the indexing of the letter in the alphabet.
  if guess_counter == 0:
      self.dictionaryList = list(self.dictionary)
      return (random.choice(self.dictionaryList))
      #  If not first guess
  else:
      for index in range(self.word_length):

          if letter_states[index] == 0:  # 0 means grey
              wrongWords = []

              for word in self.dictionaryList:
                  if self.letters[letter_indexes[index]] in word:
                      wrongWords.append(word)
              for word in wrongWords:
                  self.dictionaryList.remove(word)

          elif letter_states[index] == 1:  # 1 means green
              wrongWords = []

              for word in self.dictionaryList:
                  if self.letters[letter_indexes[index]] not in word[index]:
                      wrongWords.append(word)

              for word in wrongWords:
                  self.dictionaryList.remove(word)

          elif letter_states[index] == -1:  # -1 means yellow
              wrongWords = []

              for word in self.dictionaryList:
                  if self.letters[letter_indexes[index]] not in word or self.letters[letter_indexes[index]] in word[index]:
                      wrongWords.append(word)

              for word in wrongWords:
                  self.dictionaryList.remove(word)

  return random.choice(self.dictionaryList)


text:
Q: Python 2.7 memory leak with scipy.minimze During a fit procedure, my RAM memory slowly but steadily (about 2.8 mb every couple of seconds) increases until I get a memory error or I terminate the program. This happens when I try to fit some 80 measurements by fitting a model to them. This fitting is done by using scipy.minimze to minimize Chi_squared.
So far I've tried:

*

*Playing with the Garbage collector to collect every time Chi_squared calls my model, didn't help.

*Looking at all variables using global() and then using pympler.asizeof to find the total amount of space my variables take up, this first increases but then stays constant.

*

*The pympler.tracker.SummaryTracker also didn't show any increase of variable size.

*I've also looked at the memory_profiler but didn't find anything relevant.

From these test, it seems that my RAM usage goes up while the total space my variables take up is constant. Where my memory goes I would really like to know.
The code below reproduces the problem for me:
import numpy as np
import scipy
import scipy.optimize as op
import scipy.stats
import scipy.integrate

def fit_model(model_pmt, x_list, y_list, PMT_parra, PMT_bounds=None, tolerance=10**-1, PMT_start_gues=None):
    result = op.minimize(chi_squared, PMT_start_gues, args=(x_list, y_list, model_pmt, PMT_parra[0], PMT_parra[1], PMT_parra[2]),
                     bounds=PMT_bounds, method='SLSQP', options={"ftol": tolerance})
    print result

def chi_squared(fit_parm, x, y_val, model, *non_fit_parm):
    parm = np.concatenate((fit_parm, non_fit_parm))
    y_mod = model(x, *parm)
    X2 = sum(pow(y_val - y_mod, 2))
    return X2

def basic_model(cb_list, max_intesity, sigma_e, noise, N, centre1, centre2, sigma_eb, min_dist=10**-5):
        """
        plateau function consisting of two gaussian CDF functions.
        """
        def get_distance(x, r):
            dist = abs(x - r)
            if dist < min_dist:
                dist = min_dist
            return dist

        def amount_of_material(x):
            A = scipy.stats.norm.cdf((x - centre1) / sigma_e)
            B = (1 - scipy.stats.norm.cdf((x - centre2) / sigma_e))
            cube =  A * B
            return cube

        def amount_of_field_INTEGRAL(x, cb):
        """Integral that is part of my sum"""
            result = scipy.integrate.quad(lambda r: scipy.stats.norm.pdf((r - cb) / sigma_b) / pow(get_distance(x, r), N),
                                          start, end, epsabs=10 ** -1)[0]
            return result

        # Set some constants, not important
        sigma_b = (sigma_eb**2-sigma_e**2)**0.5
        start, end = centre1 - 3 * sigma_e, centre2 + 3 * sigma_e
        integration_range = np.linspace(start, end, int(end - start) / 20)
        intensity_list = []

        # Doing a riemann sum, this is what takes the most time.
        for i, cb_point in enumerate(cb_list):
            intensity = sum([amount_of_material(x) * amount_of_field_INTEGRAL(x, cb_point) for x in integration_range])
            intensity *= (integration_range[1] - integration_range[0])
            intensity_list.append(intensity)

        model_values = np.array(intensity_list) / max(intensity_list)* max_intesity + noise
        return model_values

def get_dummy_data():
"""Can be ignored, produces something resembling my data with noise"""
    # X is just a range
    x_list = np.linspace(0, 300, 300)

    # Y is some sort of step function with noise
    A = scipy.stats.norm.cdf((x_list - 100) / 15.8)
    B = (1 - scipy.stats.norm.cdf((x_list - 200) / 15.8))
    y_list = A * B * .8 + .1 + np.random.normal(0, 0.05, 300)

    return x_list, y_list

if __name__=="__main__":
    # Set some variables
    start_pmt = [0.7, 8, 0.15, 0.6]
    pmt_bounds = [(.5, 1.3), (4, 15), (0.05, 0.3), (0.5, 3)]
    pmt_par = [110, 160, 15]
    x_list, y_list = get_dummy_data()

    fit_model(basic_model, x_list, y_list,  pmt_par, PMT_start_gues=start_pmt, PMT_bounds=pmt_bounds, tolerance=0.1)

Thanks for trying to help!

A: I narrowed down the problem by successively removing layer after layer of indirection. (@joris267 This is something you really should have done yourself before asking.) The minimal remaining code to reproduce the problem looks like this:
import scipy.integrate

if __name__=="__main__":
    while True:
        scipy.integrate.quad(lambda r: 0, 1, 100)

Conclusion:

*

*Yes, there is e memory leak.

*No, the leak is not in scipy.minimize but in scipy.quad.

However, this is a known issue with scipy 0.19.0. Upgrade to 0.19.1 should supposedly fix the problem, but I don't know for sure because I'm still with 0.19.0 myself :)
Update:
After upgrading scipy to 0.19.1 (and numpy to 1.13.3 for compatibility) the leak disapeared on my system.


text:
Q: Unable to cancel jQuery DataTable Ajax request I am trying to give the user the ability to cancel the jQuery DataTable(ver 1.10.8) ajax request  by pressing the button,
but all the solutions i have tried are not giving me the required results.
Here is what i have tried :

let table = $('#data-table').DataTable({
                destroy: true,
                responsive: true,
                serverSide: false,
                autoWidth: false,
                paging: true,
                filter: true,
                searching: true,
                stateSave: true,
                scrollX: true,
                lengthMenu: [5, 10, 25],
                language: {
                    "search": "Filtrer: "
                },
                ajax: {
                    url: '/User/GetUsersByDepartment',
                    type: 'POST',
                    data: {
                        QueryValue: departmentName,
                        Type: type
                    },
                    dataSrc: '',

                },
                columns: [
                    {
                        title: 'Display Name',
                        data: 'UserName',
                    },
                    {
                        title: 'Date Joined',
                        data: 'JoinedDate',
                    }
                  ],
                  initComplete: function (settings, json) {

                    HideSpinner();

                    //Do something with json data;

                  }
               }).order([[1, 'asc']]).draw(false);

 //..This function is called upon pressing cancel button
 function CancelSearch() {
        table.context[0].jqXHR.abort();
        HideSpinner();
 }


text:
Q: (Qt) Render SVG with custom color I want to render a SVG icon in a QPixmap by choosing the drawing color.
This is my code using PyQt:
def svg_to_pixmap(svg_filename: str, width: int, height: int, color: QColor) -> QPixmap:
    renderer = QSvgRenderer(svg_filename)
    pixmap = QPixmap(width, height)
    pixmap.fill(Qt.GlobalColor.transparent)
    painter = QPainter(pixmap)
    painter.setPen(QPen(color))
    renderer.render(painter)
    painter.end()
    return pixmap

And a test code to display the pixmap:
app = QApplication([])
pixmap = svg_to_pixmap("test.svg", 512, 512, Qt.GlobalColor.red)
label = QLabel()
label.setStyleSheet("background-color: yellow;")
label.setPixmap(pixmap)
label.show()
app.exec()

The issue is that painter.setPen has no effect as expected (the drawing remains black). The background is transparent as expected and we can see the label background color behind.
An example of SVG file to test here
My configuration: Ubuntu22.10, X11, PyQt6.3.1

A: The answer is not simple. But, as long as you are completely sure that you only want to use the shape (or mask) of the original SVG, then it is feasible.
The reason for which setting the pen doesn't change the result is that SVG is a vector image format: it usually explicitly tells the colors of anything it wants to draw, so, setting the painter pen is almost useless, unless the SVG content is so simple to not specify it, which is clearly not the case: icons normally define colors of their shapes, and for good reasons.
The problem comes when trying to understand compositing and the possible alternatives that QPainter provides.
To be honest, even after trying to put efforts in understanding the results and associating them with the QPainter.CompositionMode enums, I still need to testing and checking in order to understand the proper mode I need.
What you probably need is the CompositionMode_SourceIn, which is cryptically explained in the documentation:

The output is the source, where the alpha is reduced by that of the destination.

As far as I can understand, the source is what is going to be painted, while the destination is what was previously painted (consider the source as a brush painting, and the destination as the canvas on which you paint).
With that in mind, we need to use the original svg as the destination and fill the whole pixmap with the color we want. Since only the alpha of the destination will be used (the visible part of the svg), we will be practically doing some sort of "stencil".
def svg_to_pixmap(svg_filename: str, width: int, height: int, color: QColor) -> QPixmap:
    renderer = QSvgRenderer(svg_filename)
    pixmap = QPixmap(width, height)
    pixmap.fill(Qt.GlobalColor.transparent)
    painter = QPainter(pixmap)
    renderer.render(painter) # this is the destination, and only its alpha is used!
    painter.setCompositionMode(
        painter.CompositionMode.CompositionMode_SourceIn)
    painter.fillRect(pixmap.rect(), color)
    painter.end()
    return pixmap

Which seems to give the wanted result:


text:
Q: How do I implement a fixed task pane in Outlook Web edition How do I implement a fixed task pane in Outlook Web App?
Read the official documentation to see that the classic Outlook web App does not support a fixed task pane.
https://learn.microsoft.com/en-gb/office/dev/add-ins/outlook/pinnable-taskpane
But I wonder how I can upgrade to Modern Outlook on the Web?
Our Server is installed with Exchange Server 2016 CU16


text:
Q: frida calls the wrong constructor I'm trying to hook the following constructor of java.net.URL:
URL(URL context, String spec, URLStreamHandler handler)
My code is as follows:
import argparse
import frida
import sys

jscode = """
Java.perform(function () {
    Java.use('java.net.URL').$init.overload('java.net.URL', 'java.lang.String', 'java.net.URLStreamHandler').implementation = function(arg0,arg1,arg2) {
          return this.$init(arg0,arg1,arg2);
      };
});
"""

parser = argparse.ArgumentParser()
parser.add_argument("target")
args = parser.parse_args()
process = frida.get_usb_device().attach(args.target)
script = process.create_script(jscode)
script.load()
sys.stdin.read()

This causes the application (and sometimes frida-server) to crash. Inspecting the logcat shows:
03-25 16:09:03.347 23490 23563 E AndroidRuntime: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String java.lang.String.toLowerCase()' on a null object reference
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(URL.java:391)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(URL.java:316)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(URL.java:339)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(Native Method)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(URL.java:498)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at java.net.URL.<init>(URL.java:447)
03-25 16:09:03.347 23490 23563 E AndroidRuntime:        at okhttp3.HttpUrl.url(HttpUrl.kt:1)
...

This means that the init I tried to call is the wrong init function, as the URL.java:339 maps to the URL(String protocol, String host, String file) constructor. I suspect this might be because both arg0 and arg2 are null in this call chain.
Is there a way to call to a specific overload?

A: I got an answer on the frida github.
The solution is:
Java.perform(function () {
  var URL = Java.use('java.net.URL');

  var ctor = URL.$init.overload('java.net.URL', 'java.lang.String', 'java.net.URLStreamHandler');
  ctor.implementation = function (arg0, arg1, arg2) {
    return ctor.call(this, arg0, arg1, arg2);
  };
});


text:
Q: Finding $n^{th}$ derivative of $x^2\log x$ I need to find the nth derivative of $x^2 \log x$ and to do that I tried just differentiating the function with the hope of finding a pattern. So I did the following:
$f'(x) = 2x\log x + x$
$f''(x) = 2\log x + 3$
$f'''(x) = 2/x$
$f''''(x) = -2/x^2$
and, unfortunately, I could not spot any pattern. I also thought of applying Leibniz's theorem:

but I am not sure how I could simplify the expression when subbing $\log x$ as $u$ and $x^2$ as $v$.
Could anyone advise if there is another method of solving this problem?
Thank you!

A: I think the OP's question may really have been how to incorporate all the $f^{(n)}\text{'s}$ into a single formula, since $f, f',$ and $f''$ don't seem to follow the same pattern as the later ones.
Usually the answer would simply be written in cases, like
$$f^{(n)}(x)=\begin{cases}x^2 \log x,&\text{if }n=0,
\\2x \log x+x, &\text{if }n=1,
\\2\log x +3, &\text{if }n=2,
\\2(-1)^{n+1}(n-3)!x^{2-n},&\text{if }n\ge 3,
\end{cases}$$
without trying to come up with some artificial formula that covers $n=0, 1,$ and $2$ also.

If you really want to try to merge these, the best way would be to write
$$f^{(n)}(x)=\begin{cases}
\frac{x^{2-n}}{(2-n)!}(2 \log x - 2 H_{2-n}+3),&\text{if }n\le 2,
\\2(-1)^{n+1}(n-3)!x^{2-n},&\text{if }n\ge 3,
\end{cases}$$
where $\,H_n=\sum_{k=1}^n \frac1{k}\,$ is the $\,n^{\text{th}}$ harmonic number, because then the formula even works for negative integer values of $n,$ with $\,f^{(-n)}(x)\,$ being an $n^{\text{th}}$ antiderivative of $\,f(x).$  (This still has two cases though, and I don't see a natural way to merge them into one.)
But if this was a homework problem, as I assume it was, this complicated formula isn't what was intended. And if you really only need the derivatives, it's overkill!

A: Though @MitchellSpector gave the solution, here is how it (laboriously) works with Leibnitz:
$$(uv)^{(n)}=\sum_{k=0}^n\binom nku^{(n-k)}v^{(k)}.$$
Then
$$u=\ln x,u'=x^{-1},u''=-x^{-2},u'''=2!x^{-3},\cdots u^{(n)}=(-1)^{n-1}(n-1)!x^{-n},$$
$$v=x^2,v'=2x,v''=2,v'''=0,\cdots v^{(n)}=0,$$
and for $n\ge3$, the sum reduces to three terms
$$\binom n0u^{(n)}v+\binom n1u^{(n-1)}v'+\binom n2u^{(n-2)}v''\\
=(-1)^{n-1}(n-1)!x^{-n}\cdot x^2+n(-1)^{n-2}(n-2)!x^{1-n}\cdot 2x+\frac{n(n-1)}2(-1)^{n-3}(n-3)!x^{2-n}\cdot2\\
=((n-1)(n-2)-2n(n-2)+n(n-1)))(-1)^{n-3}(n-3)!x^{2-n}\\
=2(-1)^{n-3}(n-3)!x^{2-n}.$$

Note that the formula doesn't work for $n=2$ even though the Leibnitz development has the three terms. The reason is that
$$u^{(n-2)}=(-1)^{n-3}(n-3)!x^{2-n}$$ doesn't hold for $n=2$.

A: we have $$f^{(iv)}(x)=2\cdot 2x^{-3}$$ and $$f^{(v)}=-2\cdot 2\cdot3x^{-4}$$
can you proceed?


text:
Q: Xpath conditioning in datamapper using rule If the below XML is evaluated using datamapper to map only even numbered id's to output then the condition using xpath(Rule) is : ?
 <employees>
        <employee>
            <id>1</id>
            <name>aaa</name>
        </employee>
        <employee>
            <id>2</id>
            <name>bbb</name>
        </employee>
        <employee>
            <id>3</id>
            <name>ccc</name>
        </employee>
        <employee>
            <id>4</id>
            <name>ddd</name>
        </employee>
    </employees>

I tried using /employee[id mod 2 = 0]/id. It maps if the input has only one even number and fails if it has more than one even numbered id in the input.xml.
    The error is

Result of xpath filling field 'id' contains two or more values!

A: Rules are independent to each Element Mapping configured in DM. Rules are to be created in the element mapping configuration it is intended to be used in.
For the sample xml provided, this rule should be created in Foreach 'employee' -> 'employee' element mapping.
Try this for the rule configuration

    Name : {Rule Name}
    Type : Boolean
    Context : /employees/employee
    Xpath : /matches(string(id mod 2), '0')

This creates a rule returning true if id is even and false if id is odd.
Use an if block in DM script view and check for the rule's value. if rule value is true, only then map the id.

A: It also worked in this way
    Name : {Rule Name}
    Type : String
    Context : /employees/employee
    Xpath : /id mod 2 = 0
and used the if condition as below :
if(input.Ruleid.equals("true")){
    output.id = input.id;
    output.name = input.name;
}

Is there any other way to do this without using if condition.


text:
Q: Load Image from packs or assets/images folder into a template.html file I've tried all the possible means of loading images into a template.html in a rails/angular application but none of my methods are working.
I imported my template file - import template from "./template.html";
Here's what my angular component looks like
import { Component } from '@angular/core';
import template from "./template.html";
import logo from "../packs/img/logo.png";

@Component({
  selector: 'ms-nav',
  template: template
})
export class NavComponent {}

Here is the list of variants I've tried. Where logo.png is saved in /assets/images/logo.png i also saved the same logo in packs/img/logo.png just to see which one would eventually work.
 got this error in console GET http://localhost:5000/assets/images/logo.png 404 (Not Found)
<img src="<%= asset_pack_path 'logo.png' %>" alt="" /> got this error in console GET http://localhost:5000/%3C%=%20asset_pack_path%20'logo.png'%20%%3E 404 (Not Found)
<img src="<%= asset_pack_path '/img/logo.png' %>" alt="" /> - GET http://localhost:5000/%3C%=%20asset_pack_path%20'img/logo.png'%20%%3E 404 (Not Found)
<img src="<%= image_tag('logo.png') %>" alt="" /> - GET http://localhost:5000/%3C%=%20image_tag('logo.png')%20%%3E 404 (Not Found)
I even tried importing logo as well but got this error - template.html?6163:1 Uncaught Error: Cannot find module "./logo"
I'm not sure if this is wrong, but I think this might be happening because of
// app/javascript/hello_angular/html.d.ts

declare module "*.html" {
  const content: string
  export default content
}

As per the documentation, this is supposed to tell typescript not to do anything with an html file whenever it comes across it. So since typescript is treating all content in this file as a string, how are we suppose to load images through an external template file?
I basically ran out of variants on the possible methods to load image through a template.html file.


text:
Q: get holder of solana nft using python I want to get the current holder (and also all past holders list) of a specific Solana NFT, using python.
Currently, I'm using get_confirmed_signature_for_address2 to get the token signatures, then I get the transaction of the newest signature, and then I extract the owner using: transaction["result"]["meta"]["postTokenBalances"][0]["owner"]
But it seems like a really long way to get the holder and I wonder if there is a better way to get it.

A: I found the solution at: https://solanacookbook.com/references/nfts.html#get-the-owner-of-an-nft
First, need to get the largest token account, it can retrieve using getTokenLargestAccounts.
Then need to take it and parse it using getParsedAccountInfo, it'll give the owner address from the associate address.
The code is in TS, but the same logic goes in python.


text:
Q: Android @DatabaseView cannot find my View I created a complex database view to fetch some data from my tables:
@DatabaseView(viewName = "VIEW_SEDINTE_SPECIALE",
        value = "SELECT descriere AS description, UPPER(titlu) AS upperTitle," +
                "(CASE " +
                "WHEN puncte_premiu * 2 > 100 THEN 100 " +
                "ELSE puncte_premiu * 2 " +
                "END) AS doubledRewards " +
                "FROM sarcini")
public class SpecialTask {
    public String upperTitle;

    public String description;

    public Long doubledRewards;

    public SpecialTask(String upperTitle, String description, Long doubledRewards) {
        this.upperTitle = upperTitle;
        this.description = description;
        this.doubledRewards = doubledRewards;
    }
}

I specified the view to the database, according to the documentation:
@Database(
        entities = {
                Role.class, Task.class, TaskHistory.class, User.class,
                Feedback.class, Location.class, Material.class,
                SessionMaterial.class, SessionTask.class,
                Problem.class, Session.class
        },
        views = {
                SpecialTask.class
        },
        version = 1
)
@TypeConverters(DateConverter.class)
public abstract class PersonalDevelopmentDatabase extends RoomDatabase { ... }

And in my QueriesDao I want to select everything from the View:
@Dao
public interface QueriesDao {
    @Query("SELECT * FROM VIEW_SEDINTE_SPECIALE")
    LiveData<List<SpecialTask>> getSpecialTasks();
}

And I am stuck with the following error:
There is a problem with the query: [SQLITE_ERROR] SQL error or missing database (no such table: VIEW_SEDINTE_SPECIALE)

I went through many posts and no solution helped me out. How should I solve this ?

A: If you add a new view or table you have to increment the version of your database. So try and update PersonalDevelopmentDatabase to version 2.


text:
Q: Reverse (parse the output) of Arrays.toString(int[]) Is there in the JDK or Jakarta Commons (or anywhere else) a method that can parse the output of Arrays.toString, at least for integer arrays?
int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} );

A: Pretty easy to just do it yourself:
public class Test {
  public static void main(String args[]){
    int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} ));
  }

  private static int[] fromString(String string) {
    String[] strings = string.replace("[", "").replace("]", "").split(", ");
    int result[] = new int[strings.length];
    for (int i = 0; i < result.length; i++) {
      result[i] = Integer.parseInt(strings[i]);
    }
    return result;
  }
}

A: A sample with fastjson, a JSON library:
    String s = Arrays.toString(new int[] { 1, 2, 3 });
    Integer[] result = ((JSONArray) JSONArray.parse(s)).toArray(new Integer[] {});

Another sample with guava:
    String s = Arrays.toString(new int[] { 1, 2, 3 });
    Iterable<String> i = Splitter.on(",")
        .trimResults(CharMatcher.WHITESPACE.or(CharMatcher.anyOf("[]"))).split(s);
    Integer[] result = FluentIterable.from(i).transform(Ints.stringConverter())
        .toArray(Integer.class);

A: You can also use split/join from Apache Commons' StringUtils