Q: How do I use two different custom UITableViewCell subclasses in a single table? How to I properly display to different UITableViewCell subclasses within the same UITableView?
I am using the storyboard for this question. I am trying to use two different subclasses of UITableView cell in a single table. The idea that TTTextFieldCells know how to show a text box and TTPickerCells know how to present a UIPicker to the user. There the protocol TTTableViewCell specifies a single selector: [setCellDetails (NSDictionary*) cellDetails] Each UITableViewCell subclass knows what to do with the cellDetails Dictionary to setup the cell.
-(NSArray *)tableData {
     if (!_tableData) {
          _tableData =
          @[ // Sections
             @{ // Section Details
                  kSectionName:@"Scout Information"
                  ,kRows:@[ // Rows
                             @{// Cell Details
                                  kBoundProperty:self.scoutName
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Name"
                                  ,kPlaceholderValue:@"Scout's Name"
                                  }
                             ,@{
                                  kReuseIdentifier:@"TTPickerCell"
                                  ,kLabel:@"Type"
                                  ,kPlaceholderValue:@"Cadet, Junior, etc..."
                                  }
                             ,@{
                                  kBoundProperty:self.yearsScouting
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Years"
                                  ,kPlaceholderValue:@"Years of Experience"
                                  ,kKeyboardStyle:@(UIKeyboardTypeNumberPad)
                                  }
                             ]
                  }
             ,@{ // Section Details
                  kSectionName:@"Parent Information"
                  ,kRows:@[
                             @{
                                  kBoundProperty:self.parentName
                                  ,kReuseIdentifier:kTextFieldCell
                                  ,kLabel:@"Name"
                                  ,kPlaceholderValue:@"Parents's Name"
                                  }
                             ]
                  }
             ];
     }
     return _tableData;
}

- (void)viewDidLoad
{
     [super viewDidLoad];
    // Do any additional setup after loading the view.
    // Line A
     [self.tableView registerClass:[TTTextFieldCell class] forCellReuseIdentifier:@"TTTextFieldCell"];
    // Line B
     [self.tableView registerClass:[TTPickerCell class] forCellReuseIdentifier:@"TTPickerCell"];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];

     NSString* reuseIdentifier = cellDetails[kReuseIdentifier];

     // Line C
     UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];

     [cell setCellDetails:cellDetails];
     return cell;
}

Now, here is the question. If I comment out line A and B, then the TTTextFieldCells are displayed correctly. But Line C will fail because it is attempting to call the TTTextFieldCell init with a TTPickerCell object, and failing because the TTPickerCell object doesn't have the same properties. If I uncomment Line A and B then the cell styles default to UITableViewCellStyleDefault and they don't display the custom controls. Oddly, if I comment out Line A, and uncomment line B, then the TTTextFieldCells look great, but the TTPickerCells default to UITableViewCellStyleDefault.
It seems that if I do not register a class, dequeue will return an instance of the first prototype cell class. If I register the class then the cell defaults to UITableViewCellStyleDefault.
Also of note, the initWithStyle:reuseIdentifier: selectors only get called if the class is registered.
So, how to I properly display to different UITableViewCell subclasses within the same UITableView? Do I have to forgo using the storyboard to design the cell?
Thank you in advance.

A: You do not want to be calling tableView registerClass:... inside of cellForRowAtIndexPath. Instead, you should be registering your classes/nibs a single time. This is often done in the controller's viewDidLoad method. Your cellForRowAtIndexPath implementation can then look something like this:
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSDictionary* cellDetails = self.tableData[indexPath.section][kRows][indexPath.row];

    NSString *reuseIdentifier = (/*some condition*/ ? @"TTTextFieldCell" : @"TTPickerCell");
    UITableViewCell<TTTableViewCell> *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    [cell setCellDetails:cellDetails];
    return cell;
}

EDIT: I should mention dequeueReusableCellWithIdentifier always returns a cell from iOS 6 on. If you are targeting an earlier version of iOS you need to account for creating cells in the even this method returns nil.

A: Ok, this is what I found to be the answer.

*

*Do not register the class for the reuse identifier. Comment out lines A and B.

*Do not copy and paste prototype cells, unless you take great care to review the IBOutlets. The pasted prototype cell doesn't care what UITableViewCell subclass you assign it too, it doesn't validate the IBOutlets are present.

Fixed up #2 and all was well.
Doh!

A: I used 2 types of cells loaded from NIB and NSMutable array with my objects, objects have texts, titles and imagens that i want to use in cells. In method cellForRowAtIndexPath... u put content from objects to cell. U can init without nib.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
    {
        if (your condition){
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass1" owner:self options:nil];
        CellClass1  *cell =  (CellClass1 *)[topLevelObjects objectAtIndex:0];
        }else{
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"CellClass2" owner:self options:nil];
        CellClass2  *cell =  (CellClass2 *)[topLevelObjects objectAtIndex:0];}

        //get your content for cell at array or your own estructure
        Content *content = [contents objectAtIndex:indexPath.row];

        cell.description.text = content.description;

        return cell;
    }


Q: static interfaces in c# Sorry it's possibly a duplicate but in the other static interface they mention generics which I am not using.
I wanted a quick and simple logger for my app I though I could avoid a singleton using a static element.
I would have like to keep the interface so that later I could change to another logging package. The interface being for me (I may be wrong here) a way to implement a "facade" feature.
I have the feeling I am overlooking something.
A gentle push in the right direction would be greatly appreciated. (Hope it's a bit clearer)
public interface Ilogger
{
    void Log(string data, out DateTime datetime, out string uid);
}

public class Logger : Ilogger
{
    private static TraceSource AppTrace = new TraceSource("RD", SourceLevels.All);

    static Logger ()
    {
       AppTrace.Listeners.Clear();
       AppTrace.Listeners.Add(new DelimitedListTraceListener("RD.log"));
    }

    static void Log(string data, out DateTime datetime, out string uid)
    {
        datetime = DateTime.Now;
        uid = Guid.NewGuid().ToString();

        AppTrace.TraceInformation(datetime + ";" + uid + ";" + data);
    }
}

A: You want to combine a singleton with a facade. Sort of a service locator. i.e. create a singleton that got the same methods as your interface and then assign the interface to the facade as the singleton.
I've blogged about it.

A: C# does not support static inheritance or static interface implementation. static variables are just a form of a Singleton either way you look at it - just go with a Singleton or better use a DI container to inject the logger dependency.


Q: Eigen SparseLU factorize too slow In my code, SparseLU.factorize() takes 1'20" to execute. How to speed it up? Or, are there any inappropriate steps slowing it down in my code?
Here is the code:
Eigen::SparseMatrix<double> F(verticesNum, verticesNum);  // verticesNum is about 34918
// reserve space for non-zero elements in sparse matrix
F.reserve(Eigen::VectorXi::Constant(verticesNum, 20));
// build matrix operator
for (int i = 0; i < vertices->size(); i++)
{
    // ... some algorithm
}

// build solver for matrix
Eigen::SparseLU<Eigen::SparseMatrix<double>, Eigen::COLAMDOrdering<int>> solver;

// tailor solver to matrix
solver.analyzePattern(F);
solver.factorize(F);

Thank you!!


Q: How to proxy requests in docker swagger ui I'm using Swagger UI using its docker version. The Try it out button is not working as expected from the Web UI because there's a problem with cors. I'm running the UI from localhost and doing requests to another domain. I have read this other question How to avoid CORS errors ("Failed to fetch" or "Server not found or an error occurred") when making requests from Swagger Editor? but I cannot do any of the solutions it says.
I'm not sure if it's posible to setup a proxy on the docker container as SwaggerHub does, like, instead of the Try it out request be resolved on the browser, resolve it on the docker container.
Do you know if that is posible?


Q: Actionscript show button after amount of time Hi i'm loading a FLV into a blank video holder and would like to display a button when the video reaches a certain point. Is this at all possible?

A: You didn't specify the version of actionscript in use, so I'll assume you're using as3.
You could

*

*use cue points embedded in the flv (added when creating the flv)

*if you're using the FLVPlayer component, use cue points created with actionscript

*use a regular Timer
If you don't have access to the creating-the-flv-part, the simplest (and the most inaccurate, but I would assume that displaying a button doesn't need to be millisecond-level-accurate) solution would be number three. If the user has no control over the playback (i.e. pause, rewind) and the video isn't being streamed over network, just start/stop a timer with the playback. If the user can pause and rewind the video, you'll have to also stop and adjust the timer every time the user does so. If the video is being streamed over network, you'll have to take any buffering pauses into account, too.

A: You can add cuepoint and listen for them with:
_Player.AddEventListener(MetadataEvent.CUE_POINT, PlayerCuePoint);

function PlayerCuePoint(e:MetadataEvent):void
{
    _Button.visible = true;
}

Or you could check the progress like this:
const BUTTON_TIME:Number = 10; //Time in seconds

_Player.AddEventListener(VideoEvent.PLAYHEAD_UPDATE, PlayerPlayheadUpdate);

function PlayerPlayheadUpdate(e:VideoEvent):void
{
    if(_Player.playheadTime >= BUTTON_TIME)
        _Button.visible = true;
}


Q: Meaning of command ls -lt | wc -l My friend just passed me this command to count the number of files in a directory:
$ ls -lt | wc -l

Can someone please help me flush out the meaning of this command? I know that ls is to list all the files. But what does -lt mean?
Also, I get a different count if I use ls | wc -l with no -lt option. Why is that the case?

A: You'll want to get familiar with the "man (manual) pages":
$ man ls

In this case you'll see:
 -l      (The lowercase letter ``ell''.)  List in long format.  (See below.)  If
         the output is to a terminal, a total sum for all the file sizes is
         output on a line before the long listing.
 -t      Sort by time modified (most recently modified first) before sorting the
         operands by lexicographical order.

Another way you can see the effect of the options is to run ls without piping to the wc command. Compare
$ ls

with
$ ls -l

and
$ ls -lt


Q: building android project produces make error 2 I have recently purchased a book to assist in my development of C++ for Android which contained some code samples.  However, when I come to build some of the sample code, I receive the following error:
C:\ndk\android-ndk-r9\ndk-build.cmd all
"Compile++  : Chapter10 <= Chapter10.cpp
process_begin: CreateProcess(NULL, C:/ndk/android-ndk-r9/toolchains/arm-linux-androideabi-4.7/prebuilt/windows/bin/arm-linux-androideabi-g++ -MMD -MP -MF ./obj/local/armeabi/objs/Chapter10/Chapter10.o.d -fno-exceptions -fno-rtti -Ijni -IC:/ndk/android-ndk-r9/sources/android/native_app_glue -IC:/ndk/android-ndk-r9/sources/cxx-stl/stlport/stlport -IC:/ndk/android-ndk-r9/sources/cxx-stl//gabi++/include -Ijni -DANDROID -Wa,--noexecstack -Wformat -Werror=format-security -frtti -c jni/Chapter10.cpp -o ./obj/local/armeabi/objs/Chapter10/Chapter10.o, ...) failed.

make (e=2): The system cannot find the file specified.

make: *** [obj/local/armeabi/objs/Chapter10/Chapter10.o] Error 2

The make file is as shown below:
LOCAL_PATH:= $(call my-dir)

include $(CLEAR_VARS)

LOCAL_ARM_MODE          := arm
LOCAL_C_INCLUDES        := $(LOCAL_PATH)
LOCAL_MODULE            := Chapter10
LOCAL_SRC_FILES         := Chapter10.cpp \
                           (Other cpp Files . . . )
LOCAL_LDLIBS            := -llog -landroid -lEGL -lGLESv2 -lOpenSLES
LOCAL_STATIC_LIBRARIES  := android_native_app_glue

include $(BUILD_SHARED_LIBRARY)

$(call import-module,android/native_app_glue)

The Application.mk file is as below:
APP_PLATFORM    := android-9
APP_STL         := stlport_static
NDK_TOOLCHAIN_VERSION   := 4.7

This was compiled using ADT v22.2.1 and Android NDK r9 on a Windows 7 Machine.
The NDK was installed to 'C:\ndk\android-ndk-r9\'.

A: Android NDK r9 contains the following toolchains:

*

*arm-linux-androideabi-4.6

*arm-linux-androideabi-4.8

*arm-linux-androideabi-clang3.2

*arm-linux-androideabi-clang3.3

*llvm-3.2

*llvm-3.3

*mipsel-linux-android-4.6

*mipsel-linux-android-4.8

*mipsel-linux-android-clang3.2

*mipsel-linux-android-clang3.3

*x86-4.6

*x86-4.8

*x86-clang3.2

*x86-clang3.3

There is no toolchain for gcc 4.7. However, your Application.mk contains the line:
NDK_TOOLCHAIN_VERSION   := 4.7

Which tells the NDK to look for the 4.7 toolchain. And it fails.
So, the solution to your problem is changing the NDK_TOOLCHAIN_VERSION variable to 4.6, 4.8, clang3.2, clang3.3, or just clang (which will use the most recent version of Clang available in the NDK).

A: Check your project path if is contain spaces and non-english characters.
I moved my project into somewhere without spaces, re-build it and works.


Q: Error message converting pandas dataframe integers to datetime I was trying to convert dates into datetime since they were given to me in YYYYMMDD format on my HW. The date was already indexed for a previous problem so I wrote out:
df.reset_index()
df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')

This is the error message I ended up getting:
   KeyError                                  Traceback (most recent call last)
    ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in
    get_loc(self, key, method, tolerance)
       3079             try:
    -> 3080                 return self._engine.get_loc(casted_key)
       3081             except KeyError as err:

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

    pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()

    KeyError: 'DATE'

    The above exception was the direct cause of the following exception:

    KeyError                                  Traceback (most recent call last)
    <ipython-input-291-e5a2ae2efa46> in <module>
          1 df.reset_index()
    ----> 2 df['DATE'] = pd.to_datetime(df['DATE'], format='%Y%m%d')
          3 #df.set_index('DATE',inplace=True)
          4 #df.resample('A').apply(lambda x: x[x<0].count())

    ~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
       3022             if self.columns.nlevels > 1:
       3023                 return self._getitem_multilevel(key)
    -> 3024             indexer = self.columns.get_loc(key)
       3025             if is_integer(indexer):
       3026                 indexer = [indexer]

    ~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
       3080                 return self._engine.get_loc(casted_key)
       3081             except KeyError as err:
    -> 3082                 raise KeyError(key) from err
       3083
       3084         if tolerance is not None:

    KeyError: 'DATE'

Very confused since I pretty much literally used this datetime line for a different problem without any issue. Is there anything I can do to fix this? thanks!


Q: Simplest way of integrating Angular-created elements with D3 I'm playing around with different ways of integrating D3 and Angular, in the context of learning both of these frameworks, and am hoping for some input:
My client application receives a JSON array of nodes and an array of edges from my server.
The central component of the client is a graph visualization implemented as a D3 force-directed layout: For each node in the nodes array, a (SVG) circle element is added to this visualization, and lines between these circles are added for each edge in the edges array.
Of course, D3's selection.data( ) makes it trivial to add these elements and bind each to the data it represents, but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.
My primary goal is minimizing code complexity, and - although I've fallen in love with the simplicity and elegance of D3's data-binding functionality - I've arrived at the tentative conclusion that using it in one part of the application while using Angular to do the same in other parts is creating unnecessary complexity, and that the simplest approach would be to use Angular to handle the data-binding/element-creation
In other words, instead of using selection.data( ).enter( ).append( ) to create SVG elements, I'm thinking I should do so using a ng-repeat="node in nodes", perhaps creating each as a custom directive to allow for custom functionality. Having done so, I would then need to get these elements "into" D3, i.e. managed by its force-directed layout.
Is my reasoning here sound? In particular, I'm worried that I'm overlooking complications this will create with regard to object constancy, which is an important requirement as nodes will be entering, exiting and moving about the screen constantly and I need these transitions to be smooth. How would you recommend I go about integrating my angular-created elements into D3 (more precisely, getting them into my force.nodes{ } and force.links( ) arrays) to avoid any such complications?
Finally, I'm also considering a strategy that I'm hoping might give me the best of both worlds: I could use D3 to create my SVG elements and bind them to their respective datum, but rather than executing that code in the link function of visualization directive (as I've been doing, and as all the Angular/D3 tutorials I've found do), I could run it in the compile function, and do something like this:
d3.select('SVG')
  .selectAll('.node')
  .data('nodeDataArray')
  .enter( )
  .append('circle')
  .attr("class", "node-icon"); //...other attributes/styles etc

where node-icon is the normalized name of a directive with a restrict property that includes C. If this runs in the compile method, angular should then compile all of these directives as normal, adding any additional functionality / interfaces with other directives (etc.), the same way it does with any other type of element. Right?
This is the option I'm most attracted to intuitively - are there any pitfalls of it I might be overlooking, which might make the former strategy preferable?

A: I have been pondering pretty much the same problem for a while and come to the following conclusion.
The simplest way to integrate Angular created elements with d3 is to add the directives with .attr and then .call the compile service on the d3 generated elements. Like this:
mySvg.selectAll("circle")
                .data(scope.nodes)
                .enter()
                .append("circle")
                .attr("tooltip-append-to-body", true)
                .attr("tooltip", function(d){
                    return d.name;
                })
                .call(function(){
                    $compile(this[0].parentNode)(scope);
                });

Here is a Plunker.
I think the idea of generating elements with Angular ngRepeat rather than d3 is working against the frameworks. D3 does not expect to be handed a bunch of elements. It wants to be handed data - almost always an array. It then has a stack of excellent functions to convert that data into various SVG or HTML elements. Let it do that.
It seems from this quote...

D3 makes it trivial to add elements and bind each to the data it represents,  but the graph visualization is only part of a much larger application: I need to create different types of elements representing these same nodes and edges in different parts of the application (which D3 has nothing to do with), and I'd like to keep all of these elements bound to a single dataset.

... you are implying that generating elements with d3 somehow prevents you from binding the same data to different parts of the application. I can't see why. Just have d3 generate elements from a scope array (as is done in the linked Plunker). Then use the same dataset wherever you want in the usual Angular way. Other parts of the application can update the dataset and a $watch callback can re-render the d3 graphic.


Q: Cannot make child element the same height as parent element IE I am trying to make a child element of a table cell take on the table cell's height and width using CSS.  Here is the html:

Here is the CSS I'm using:

    table tbody tr td:nth-child(1){
        position: relative;
    }

    table tbody tr td div.yellowDiv{
        position: absolute;
        top: 0;
        bottom: 0;
        width: 100%;
        background: yellow;
    }

The above code renders properly in Chrome, but not in IE (only concerned with IE 9 and 10).  I have also tried setting display: table-cell; for the div element but to no avail.  I have also tried setting the height of the div element to be 100% but that has not worked either.

A: Absolutey-positioned elements are no longer part of the layout. They have their own layout context. Therefore they cannot know how big their parent element is.
You need to use JavaScript to solve this or consider why you need absolute positioning at all.
You can use:
.yellowDiv {
    background-color:#ffff00;
    height:100%;
}


Q: Android imageview over another imageview I want an icon (ImageView) over another ImageView. When I tried, the icon is hiding behind the white image. In my code below, first image view is for the white box and another image view is for the icon.
<RelativeLayout
            android:layout_width="54dp"
            android:layout_height="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp">

            <ImageView
                android:id="@+id/button_menu"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true"
                android:padding="5dp"
                android:src="@drawable/ic_menu"
                android:background="@drawable/button_white_rounded"
                android:elevation="4dp"
                android:scaleType="fitXY"
                android:adjustViewBounds="true"
                android:tint="@color/colorText"/>

            <ImageView
                android:id="@+id/warning_circle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:src="@drawable/ic_warning_circle"/>
        </RelativeLayout>

I want the orange icon in screenshot over the white box. How can I bring it on the white box image?

A: <RelativeLayout
            android:layout_width="54dp"
            android:layout_height="54dp"
            android:layout_alignParentTop="true"
            android:layout_alignParentStart="true"
            android:layout_marginStart="20dp"
            android:layout_marginTop="20dp">

             <ImageView
                android:id="@+id/warning_circle"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentBottom="true"
                android:layout_alignParentRight="true"
                android:src="@drawable/ic_warning_circle"/>

            <ImageView
                android:id="@+id/button_menu"
                android:layout_width="44dp"
                android:layout_height="44dp"
                android:layout_alignParentTop="true"
                android:layout_alignParentStart="true"
                android:padding="5dp"
                android:src="@drawable/ic_menu"
                android:background="@drawable/button_white_rounded"
                android:elevation="4dp"
                android:scaleType="fitXY"
                android:adjustViewBounds="true"
                android:tint="@color/colorText"/>

        </RelativeLayout>

A: The layout_align [Top|Bottom|Left|Right] attribute in RelativeLayout is used to align views based on their respective x and y values within the margin. The second ImageView will now be aligned to the top, bottom, left, and right of the first ImageView based on the margins. Padding is ignored in the alignment.
<RelativeLayout
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:background="@color/white" >

    <ImageView
        android:id="@+id/inside_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="5dip"
        android:layout_marginTop="5dip"
        android:src="@drawable/frame" />

      <ImageView
         android:id="@+id/outside_imageview"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:layout_alignTop="@id/inside_imageview"
         android:layout_alignBottom="@id/inside_imageview"
         android:layout_alignLeft="@id/inside_imageview"
         android:layout_alignRight="@id/inside_imageview"
         android:scaleType="fitXY" />
  </RelativeLayout>

A: Your code is perfect but either you have to remove android:elevation from button_menu or you have to add android:elevation in warning_circle.
I have updated my answer based on @MikeM. suggestion for use RelativeLayout instead of ConstraintLayout
Solution 1:
<RelativeLayout
    android:layout_width="54dp"
    android:layout_height="54dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:background="@drawable/button_white_rounded"
        android:padding="5dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_menu"
        android:tint="@color/colorText"
        tools:src="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:src="@drawable/ic_warning_circle"
        tools:src="@tools:sample/avatars" />
</RelativeLayout>

Solution 2:
<RelativeLayout
    android:layout_width="54dp"
    android:layout_height="54dp"
    android:layout_alignParentStart="true"
    android:layout_alignParentTop="true"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:adjustViewBounds="true"
        android:background="@drawable/button_white_rounded"
        android:elevation="4dp"
        android:padding="5dp"
        android:scaleType="fitXY"
        android:src="@drawable/ic_menu"
        android:tint="@color/colorText"
        tools:src="@tools:sample/avatars" />

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentBottom="true"
        android:elevation="4dp"
        android:src="@drawable/ic_warning_circle"
        tools:src="@tools:sample/avatars" />
</RelativeLayout>

A: You can use FrameLayout to achieve this.. here is an example, you can modify this according to your need. In warning icon image view add gravity as bottom|end and in menu icon image view add margin of 10dp when using FrameLayout.
<FrameLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="20dp"
    android:layout_marginTop="20dp">

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:layout_margin="10dp"
        android:padding="5dp"
        android:src="@drawable/ic_menu"
        android:background="@drawable/button_white_rounded"
        android:elevation="4dp"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"
        android:tint="@color/colorText"/>

    <ImageView
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:src="@drawable/ic_warning_circle"/>

</FrameLayout>

A: <RelativeLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_marginTop="20dp">

    <ImageView
        android:layout_centerInParent="true"
        android:id="@+id/warning_circle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="20dp"
        android:src="@drawable/ic_launcher_background"/>

    <ImageView
        android:id="@+id/button_menu"
        android:layout_width="44dp"
        android:layout_height="44dp"
        android:padding="5dp"
        android:layout_marginRight="-20dp"
        android:layout_marginBottom="-20dp"
        android:layout_alignRight="@+id/warning_circle"
        android:layout_alignBottom="@+id/warning_circle"
        android:src="@drawable/ic_menu_gallery"
        android:background="@color/colorAccent"
        android:elevation="4dp"
        android:scaleType="fitXY"
        android:adjustViewBounds="true"/>

</RelativeLayout>

Use this way!!
We have a concept of layers in relative layout!
Vertically down views are on the top most layer.

A: <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitXY"
        android:src="@drawable/download" />

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerInParent="true">

        <ImageView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:src="@drawable/download_img" />
    </RelativeLayout>

</RelativeLayout>

A: You could try to search any ready-to-use solutions for badges like ImageBadgeView.
Or try to play with BadgeDrawable from material lib.
I'd prefer to use ViewOverlay for such purposes and just add few rows of code:
button_menu.post {
    val drawable = ContextCompat.getDrawable(context, R.drawable.ic_warning_circle)
    drawable.setBounds(
        button_menu.width - drawable.intrinsicWidth,
        button_menu.height - drawable.intrinsicHeight,
        button_menu.width,
        button_menu.height
    )
    button_menu.overlay.add(drawable)
}

In this way you would reduce amount of containers in your xml layout and make it more readable.


Q: Sharepoint 2007 File Upload , Page cannot be Displayed Having a bit of strange Sharepoint 2007 issue , especially for a Monday.
Here's the scenario: Users within organisation cannot upload files to ANY doc Lib.
User is able to click upload, browse, select the file without any problems. As soon as he/she clicks OK, they immediately get a standard IE error : Page cannot be displayed.
The MOSS Server is setup in a DMZ where it is Internet accessible. When accessing it from the Internet (which I'm doing), the uploading works fine. It's only when users who are in the organisation try to upload anything, they get the error. Users within the organistaion also access the site using the Internet IP as no direct route exists between Internal Network and DMZ.
We have a LINUX Firewall involved (Yuck, I know), and clients also have Norton AV.
I suspect some kind of networking issue, or maybe the AV. Any ideas?

A: Ok. The issue was related to intermittant connectivity loss. All fixed now


Q: Issue constructing a has_many relation with scope using multiple join tables I have a tag system on multiple models that are linked together.
The system works like this:

*

*A Top has many Middles

*A Middle has many Lows

*Tops, Middles and Lows have many Tags

*A tag associated to Top level is supposed to qualify every Middle and Low associated to it.

*Same goes for a tag that would be associated to a Middle, every Low associated to it would 'inherit' from the tags.

This mechanic is not on a database level, in the end in what concerns the database, Tops, Middles and Lows all have their own tag collection, and i initially implemented instance methods on each model so that when you call, for example, low_instance.all_tags, it concatenates the tag collections of it's parent Middles, and the one of its Top.
Here is what the models look like:
#          ______________________________
#         /                              \
#      (1)                                (*)
#    [Top] (1) __ (*) [Middle] (*) __ (*) [Low]
#      (*)               (*)              (*)
#        \_______________ | ______________/
#                         |
#                         *
#                       [Tags]

class Low < ApplicationRecord
  has_many :low_tags, dependent: :destroy
  has_many :tags, through: :low_tags
  has_many :middle_foos, dependent: :destroy
  has_many :middles, through: :middle_foos
end

class Middle < ApplicationRecord
  belongs_to :top
  has_many :middle_tags, dependent: :destroy
  has_many :tags, through: :middle_tags

  has_many :middle_lows, dependent: :destroy
  has_many :lows, through: :middle_lows
end

class Top < ApplicationRecord
  has_many :middles, dependent: :destroy
  has_many :lows, dependent: :destroy
  has_many :top_tags, dependent: :destroy
  has_many :tags, through: :top_tags
end

### Join tables
class MiddleLow < ApplicationRecord
  belongs_to :middle
  belongs_to :low
end

class LowTag < ApplicationRecord
  belongs_to :low
  belongs_to :tag
end

class MiddleTag < ApplicationRecord
  belongs_to :middle
  belongs_to :tag
end

class TopTag < ApplicationRecord
  belongs_to :top
  belongs_to :tag
end

That actually works like a charm. The issue is that i want to be able to search my Lows with the awesome Ransack gem and using the full tag collection of a Low (its self tags, plus the ones inherited from the parent Middles and Top)
Problem: Ransack only works with ActiveRecord::Relations. So from Ransack's point of view, i can only search my Lows using their self-tags and not the full inherited collection as this does not exist on the database level.
The initial solution to this problem i wanted to implement is to add a "copy" full tag collection on the database level that updates with the rest and that i could use to search with Ransack.
But I'm sure i don't have to add anything to the database as all the info is already here in the join tables and i kind of don't want to duplicate that info which is not super cool i think and would make the code base less understandable.
I have seen potential solutions using has many with scopes like so:
has_many :all_tags, ->(low) {
  unscope(.........).
  left_joins(..........).
  where(.........)
  # Returs self tags (Low) + tags from associated Middles + tags from the Top
}

I'm pretty sure this would be the best solution, but I'm really not good when it comes to database querying especially with so much models and join tables. I get confused and can't seem to find what to put in that scope so that i get this full collection of tags.
So if anybody has a clue about that, any help would be greatly appreciated!
By the way, using Rails 6.1 and Ruby 2.7

A: So found the solution to the query I wanted to construct in the end.
The scope looks like following:
    has_many :full_tags, lambda { |low|
        where_clause = 'top_tags.top_id = ? or low_tags.low_id = ?'
        where_args = [low.top_id, low.id]
        if low.middles.any?
          where_clause += ' or middle_tags.zone_id IN ?'
          where_args << low.middle_ids
        end
        unscope(where: :low_id)
          .left_joins(:middle_tags, :top_tags, :low_tags)
          .where(where_clause, *where_args).distinct
      }, class_name: 'Tag'

Calling xxx.full_tags on any instance of low returns the whole collection of tags from every middle it belongs to , plus those from the top it belongs to, plus its own tags, and the distinct makes it a unique collection.
That being said, that didn't fully fixed my problem because the whole purpose was to pass this scoped has_many relation as an attribute used by the Ransack gem to filter out my Low models, out of their full inherited collection of tags.
Big disappointment it was when i discovered that Ransack performs eager loading when it comes to search on associations:
Rails does not support Eager Loading on scoped associations
So i ended up implementing a whole other solution for my tagging system. But hey, i learned a lot.


Q: EnterpriseLibrary Error I'm receiving reports of a rare and intermittent error in our live environment. I have been unsuccessful in my attempts to reproduce it, and the error itself is a slight mystery. Add to that, it seems to be something involving Enterprise Library tracing (we're using version 5.0) - all in all, a bit of a pain. This is happening on Windows Sever 2008, application is on .Net Framework 4.0 (WPF).
The error message and the stack trace follow:
ArgumentNullException: Value cannot be null. Parameter name: category

<StackTrace>
  Server stack trace:
  at Microsoft.Practices.EnterpriseLibrary.Logging.LogEntry.BuildCategoriesCollection(String category)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceMessage(String message, String entryTitle, TraceEventType eventType)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.WriteTraceEndMessage(String entryTitle)
  at Microsoft.Practices.EnterpriseLibrary.Logging.Tracer.Dispose()
  at TestApplication.ViewModelTest.<UpdateUsers>d__1a.MoveNext()

  Exception rethrown at [0]:
  at System.Runtime.CompilerServices.AsyncVoidMethodBuilder.<SetException>b__1(Object state)
  at System.Threading.QueueUserWorkItemCallback.WaitCallback_Context(Object state)
  at System.Threading.ExecutionContext.runTryCode(Object userData)
  at System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
  at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state)
  at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
  at System.Threading.QueueUserWorkItemCallback.System.Threading.IThreadPoolWorkItem.ExecuteWorkItem()
  at System.Threading.ThreadPoolWorkQueue.Dispatch()
  at System.Threading._ThreadPoolWaitCallback.PerformWaitCallback()
</StackTrace>

Can anyone shed any light on what might be causing this?
EDIT:
I'm not modifying LogEntry.BuildCategoriesCollection. The input to the method BuildCategoriesCollection(String category) is null.
The UpdateUsers method is as follows:
async void UpdateUsers()
{
    Processing = true;

    using (traceMgr.StartTrace("Trace"))
        using (var engine = new EngineClient())
        {
            Users = new List<UserMasterDataModel> { _blankUser };
            var users = await engine.GetPossibleTagsTask(SelectedOutcomeId, _queue.SystemCd, _queue.QueueCd);
            Users.AddRange(users);
        }

    if (SelectedUser != _blankUser)
    {
        // If null user selected then initialize to the case's tag, otherwise try to find the previously selected UserName
        var userNameToFind = SelectedUser == null ? _details.TagTo : SelectedUser.UserName;
        SelectedUser = Users.FirstOrDefault(user => user.UserName == userNameToFind) ?? _blankUser;

        OnPropertyChanged("SelectedUser");
    }
}

A: This problem seem to be a known bug for E-Lib in previous versions too.
Known as: Unhandled exception when using the logging AB from multiple threads.
"The underlying issue is that in .NET 2.0 RTM a parent thread's operation stack was shared with its children if such a stack existed by the time the children were created."
Read more here:
http://entlib.codeplex.com/workitem/9592
Hard to suggest a generic solution to this as it is very depends on the architecture of your app.


Q: android jni from static to non static methods I am trying to refactor some android jni code. It was initially setup to use static variables in JNI and static calls on the android side. I would like to change that to improve compatibility with other code.
current method signatures
static jclass main_activity;

static jmethodID on_init;
static jmethodID on_update;
static jmethodID on_render;
static jmethodID on_exit;
static jmethodID on_get_input;

these bindings were setup in the beginning of the code like this:
main_activity = (jclass)((*mEnv)->NewGlobalRef(mEnv, cls));

on_init = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_init","()V");
on_update = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_update","()V");
on_render = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_render","()V");
on_exit = (*mEnv)->GetStaticMethodID(mEnv, main_activity,
                            "on_native_exit", "()V");

Then later in the code they would be used like this:
void Android_JNI_SwapEGLwindow(void)
{
    JNIEnv *a_env = get_android_jni_env();
    (*mEnv)->CallStaticVoidMethod(a_env, main_activity, on_update);
}

Since this project is currently setup to store the main activity and the function addresses as a static reference with only the call to get_android_jni_env(); allowing me access to get the current android jni environment.
How can I restructure this code to be able to get an instance instead of holding on to a static reference?

A: Just add one static method as "getInstance()" to retreive the object of class main_activity, then you can use the object to call non-static methods.
jmethodID midGetInstance = (*env)->GetStaticMethodID(env, main_activity_class, "getInstance", "()Lcom/package/yourapp/MainActivity;");
jobject main_activity_obj = (*env)->CallStaticObjectMethod(env, main_activity_class, midGetInstance);
...NewGlobalRef(main_activity_obj);

where main_activity_class is the same of your original jclass main_activity.
On Java side, you need
onCreate(...) {mInstance = this;...}
public static MainActivity getInstance() {return mInstance;}

Then you can use main_acitivty_obj to access the non-static methods.


Q: Send form data to Firebase The problem is that when I run this my real-time database is not updating and there are no errors coming or showing.

function writeData() {
    firebase.database().ref("user").set( {
            Email: document.getElementById("help").value,
            Price: document.getElementById("price1").value,
            Desc: document.getElementById("Pdesc").value,
        }

    );
}
<form>

        Enter Product name
        <input type="text" class="form-control" id="help" aria-describedby="emailHelp">

        Product Price
        <input type="number" class="form-control" id="price1">

        Product description
        <input type="text" class="form-control" id="Pdesc">

    <button type="submit" onclick="writeData()" class="btn btn-lg btn-success">Upload</button>
</form>

A: First, check your realtime firebase, sometimes if you use free, your realtime firebase has expired (for 1 month).
You can print it by inputting a simple value, for example:
If nothing happens, then check your project's API, library, or expiration date.
Solution:
Create a new project.


Q: $uibModal not loading correct content on first click I'm working in ServiceNow and am trying to use $uibModal to open up a modal window that holds an embedded widget.  The modal opens fine on the first click, but every click after that requires two clicks for the modal to load the correct content.  I've read on a few sites that it's because of the template cache doesn't clear and some people suggested not using the script tags, but I'm not sure how to get uibModal to work without the script tags in ServiceNow.  Has anyone run into this?  Would love to get some suggestions on how to fix this.
Here's my client script:
c.onWidget2 = function(template, task) {
    c.taskName = task.short_description;
    c.modalInstance = $uibModal.open({
        templateUrl: template,
        scope: $scope,
        size: 'lg'
    });
    spUtil.get('hrj_task_activity_scoped', {
        sys_id: task.sys_id,
        table: 'sn_hr_core_task',
        recordInfo: task.taskInfo
    }).then(function(response) {
        c.newTask2 = response;
    });
};

//closeModal for the "x"
c.closeModal = function() {
    c.modalInstance.close();
};

And here's my HTML:

A: problem here is "directive in modal", like in this thread:
Integrating directive in Angular UI Modal
The solution would be to load the directive after the modal is rendered:
c.onWidget2 = function(template, task) {
    c.taskName = task.short_description;

    var initWidget =  spUtil.get('hrj_task_activity_scoped', {
        sys_id: task.sys_id,
        table: 'sn_hr_core_task',
        recordInfo: task.taskInfo
    }).then(function(response) {
        c.newTask2 = response;
    });

    c.modalInstance = $uibModal.open({
        templateUrl: template,
        scope: $scope,
        size: 'lg'
    }).rendered.then(initWidget);
};

//closeModal for the "x"
c.closeModal = function() {
    c.modalInstance.close();
};


Q: Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php I’m in the middle of E10-4 from 'Learning PHP, MySQL & JavaScript' by Robin Nixon.  I have enjoyed the book until two days ago when I got to exercise 10-4 where I was asked to run the following php program:
<?php
require_once 'login.php';
  $conn = new mysqli($hn, $un, $pw, $db);
  if ($conn->connect_error) die($conn->connect_error);

  $query  = "SELECT * FROM classics";
  $result = $conn->query($query);
  if (!$result) die($conn->error);

  $rows = $result->num_rows;

  for ($j = 0 ; $j < $rows ; ++$j)
  {
    $result->data_seek($j);
    echo 'Author: '   . $result->fetch_assoc()['author']   . '
';
    $result->data_seek($j);
    echo 'Title: '    . $result->fetch_assoc()['title']    . '
';
    $result->data_seek($j);
    echo 'Category: ' . $result->fetch_assoc()['category'] . '
';
    $result->data_seek($j);
    echo 'Year: '     . $result->fetch_assoc()['year']     . '
';
    $result->data_seek($j);
    echo 'ISBN: '     . $result->fetch_assoc()['isbn']     . '

';
  }

  $result->close();
  $conn->close();
?>

I get the two following error messages:

*

*Fatal error: Class ‘mysqli’ not found in
C:\xampp\htdocs\code\query.php

*PHP Fatal error: Class ‘mysqli’ not found in C:\xampp\htdocs\code\query.php

I’m running the following systems:

*

*Windows 7 Home Premium

*PHP 5.6.8

*XAMPP Control Panel v3.2.1

*Apache 2.4.12

*Database client version: libmysql - mysqlnd 5.0.11-dev -

*PHP extension: mysqli

I have searched stackoverflow and found a few posts about similar problems but could not pull any information out to solve the problem.  I’m new to programming but the responses where over my head.  I really have enjoyed this book but this Fatal error is keeping me from doing some great stuff with php and I'm not sure what I can do if I don't get past this issue.  I'm sure it is simple to fix.  Thanks for your help.


Q: Why is this labeled javaScript continue not working? I am using this code to weather some circles are overlapping:
iCantThinkOfAGoodLabelName:
x = genX(radius);
y = genY(radius);
for(i in circles) {
  var thisCircle = circles[i];
  if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
    continue;
  } else { //Overlap
    continue iCantThinkOfAGoodLabelName; //<- Line 256
  }
  thisCircle = [];
}

But when the continue statement is reached, chrome's developer console gives me this: client.html:256 Uncaught SyntaxError: Undefined label 'iCantThinkOfAGoodLabelName'

A: Because iCantThinkOfAGoodLabelName: needs to be right before the loop.
iCantThinkOfAGoodLabelName:
for (blah; blah; blah)
    ..

I think what you want is a function..
function iCantThinkOfAGoodFunctionName() {
    var x = genX(radius),
        y = genY(radius);

    for (i in circles) {
        var thisCircle = circles[i];
        if(Math.abs(x-thisCircle["x"])+Math.abs(y-thisCircle["y"])>radius*2) { //No overlap
            continue;
        } else { //Overlap
            iCantThinkOfAGoodFunctionName();
        }
        thisCircle = [];
    }
}

A: There should not be any statement between a label name and associated loop.
x = genX(radius);
y = genY(radius);
iCantThinkOfAGoodLabelName:
    for(i in circles) {

fixes it.

A: The label should come immediately before the loop
x = genX(radius);
y = genY(radius);

iCantThinkOfAGoodLabelName:
for(i in circles) {

A: I recently had this issue and I resolved it by using all lowercase in the loop's label in version v0.8.x of Node.js.
Using labelname: vs. iCantThinkOfAGoodLabelName: might help you.
Others have correctly corrected you on the location of the label. It should be immediately before the for loop.
The Mozilla Developer Network on labels advises to avoid using labels, and instead prefer calling functions or throwing an error. You might rethink your strategy on using them, if possible.
Example of calling a function depending on result:
var i, j;

for (i = 0; i < 3; i++) {
   for (j = 0; j < 3; j++) {
      if (i == 1 && j == 1) {
         // we want to ignore and continue
      } else {
         // do work with these variables from inside the doWork function
         // (scoped to whatever scope `this` for loop is in)
         doWork.call(this, i, j);
      }
   }
}


Q: error using result returned from angular service (undefined) So I have two variables in my Typescript class:
private myServiceSubscription: Subscription;
myVar: myDto[] = [];

In the ctor:
this.myServiceSubscription = this.deliveryPointService
        .getPostalAddresses()
        .subscribe(result => console.log(result));

I can see the expected result returned from the service in the console log (a list with two items)
However, if I use another subscribe instead:
.subscribe(result => this.myVar);

and (outside the subscribe):
    console.log(this.myVar[0]);
then I notice this.myVar is undefined.
Why does console.log(result) show the right result, but this.myVar does not?
This is in angular 4.

A: Right now, you don't do anything with the result of your service method. You have to assign the returned item to your variable:
.subscribe(result => {
   this.myVar = result;
   console.log(this.myVar);
});


Q: How to prompt message box in remote computer where application is running as service? I have an C++ MFC application running in master machine that installs update from a server in remote computers through an agent service. This service takes care of authorization in remote machines before update. Now, I need to prompt the currently active user in remote machines for confirmation. AfxMessagebox or MessageBox in the service context doesn't show up any window in remote machines. Is there a way to achieve this?

A: Look at WTSSendMessage():

Displays a message box on the client desktop of a specified Remote Desktop Services session.


Q: Push Data from a WCF Service to Website I have the following scenario, and I would like to know if there is a solution to achieve such thing:
I have a WCF service that is running in a backend server, and it does bulk data processing, like inserting records into DB, and I would like to have this service send a message or notification once a record has done processing to a webpage (ASP.NET Page), where this page should be listening to these messages and display a progress with the finished tasks at real-time.
Note: The WCF service is separate from the webpage; This means that the WCF service process starts when another WCF service calls it in the backend server, so the web-page should only 'listen' to the updates that comes from WCF service.
Through my research, I have come up with SignalR, can this technology help me build a solution for such a scenario, or maybe there is some other way to achieve it?


Q: How to collect activity information from network-attached storage (NAS) devices? My goal is to be able to generate a report about the users that have accessed a particular folder on any file share. This includes Windows file servers, Unix/Linux file servers, and NAS devices (CIFS/SMB/NFS).

*

*For Windows, this isn't too complicated because it has built-in functionality that supports this (see: http://blogs.splunk.com/2013/07/08/audit-file-access-and-change-in-windows).

*I'm assuming that there is similar built-in functionality for unix/linux shares.

*So this leaves the question of whether something like this is possible for NAS devices (CIFS/SMB/NFS).

I'm thinking that something like this is possible because of some tools that I see are available, such as what is available at http://www.imperva.com/products/fsc_file-activity-monitoring.html.
So my question is the following: Is it possible to collect file share activity information from NAS devices? If so, how do I collect this information? For example, if there were APIs to support this, it would be most useful.

A: Is your NAS running SAMBA?  If so will the Samba log files or smbstatus command solve your need?  See https://askubuntu.com/questions/89288/how-can-i-monitor-my-samba-traffic


Q: Wordpress - How to extract the first video embed from post content and place it in different area? I am trying to build a wordpress theme which extracts the first embedded video out of the content of the post and features it on top of the page.
So for example, I am trying to go from this:

Post content

Post content

To this:

Post content

Post content

So the important things I am trying to accomplish are:
1) Finding the first embedded video within the post content.
2) Placing that first video in the above featured area.
3) Filtering that first video out of the content (so that it doesn't appear twice on the page).
So far I am simply using the get_post_custom() function to get the first embed code within the post and copy it into the featured area. I am having problems with number 3 though (filtering out the first video from the post content). I could just hide the first embedded video with CSS, but it doesn't feel right to me. I feel like I need to filter the video out of the content completely. Am I right or wrong about this?
I have also had ideas about using the oembed filters in wordpress but I can't seem to get my head round how to implement them.
Let me know what you think is the best way of doing this is.


Q: using JSON to get data from MYSQL to Java i'm trying for days to get this working.. but i still fail.
<?php
$province = $_POST['test'];
$dbhost = 'localhost';
$dbname = 'news';
$dblogin = 'root';
$dbpass = '';

function dbConnect() {
   global $dbhost;
   global $dbname;
   global $dblogin;
   global $dbpw;

   $db = mysql_connect($dbhost, $dblogin, $dbpw) or die("could not
connect to database: ".mysql_error());
   mysql_select_db($dbname) or die("could not select database");
   return $db;
}
function dbClose($db) {
   mysql_close($db);
}

// basis code ^^

$db = dbConnect();

$query = "SELECT title FROM news_google_us";

$result = mysql_query($query) or die(mysql_error());

while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{

echo json_encode($row);

 ;}

?>

i get this as response:
{"title":"Obama and GOP in Deal on Tax Cuts - New York Times"}{"title":"WikiLeaks Founder Warns About More Dispatches - New York Times"}{"title":"S. Korea to make islands near N. Korea fortresses - Jerusalem Post"}{"title":"9th Circuit judges explore narrow routes to reinstate gay marriage - Los Angeles Times"}{"title":"Killing of Iranian Scientist Overshadows 6-Nation Nuclear Talks - BusinessWeek"}{"title":"Schwarzenegger proposal rebuffed - San Jose Mercury News"}{"title":"WikiLeaks list of 'critical' sites: Is it a 'menu for terrorists'? - Christian Science Monitor"}{"title":"Big moments in the Concorde's history - BusinessWeek"}{"title":"Citigroup Stake Is Sold for About $10.5 Billion as US Unwinds Investment - Bloomberg"}{"title":"Jets Vs. Patriots: New England In Full-On Kobra Kai Mode...No Mercy - SB Nation"}{"title":"Obama, GOP cut deal to extend tax cuts - USA Today"}

I use Jquery to get the data:
 $.ajaxSetup({"error":function(XMLHttpRequest,textStatus, errorThrown) {
      alert(textStatus);
      alert(errorThrown);
      alert(XMLHttpRequest.responseText);
  }});

 $.getJSON('mysql-query.php', function(data) {
    alert(data);
 });

I've tried a stripped version
<?

$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['descrtiption'])) {
 $stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
 //   $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['descrtiption']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "
";
print_r(phpinfo());
echo "
";
}

echo json_encode($rows);
?>

tried this one
I've tried a stripped version
<?

$dsn = "mysql:host=localhost;dbname=news";
$username = "root";
$password = "";

$pdo = new PDO($dsn, $username, $password);

$rows = array();
if(isset($_GET['descrtiption'])) {
 $stmt = $pdo->prepare("SELECT description FROM news_BBC_sport WHERE name = ? ORDER BY description");
 //   $stmt = $pdo->prepare("SELECT variety FROM fruit WHERE name = ? ORDER BY variety");
    $stmt->execute(array($_GET['descrtiption']));
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo "
";
print_r(phpinfo());
echo "
";
}

echo json_encode($rows);
?>

tried this one
http://www.phpclasses.org/package/4369-PHP-Generate-JSON-representation-from-MySQL-queries.html
I'm using firebug to check what's wrong. I get this:
parse error

syntax error JSON parse

(shows json data)

I've tried like everything, but i still get this error. I'm using a XAMPP server on OSX.

A: You first attempt is almost right, just don't echo each row, collect the result then echo:
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $rows[] = $row;
}
echo json_encode($rows);


Q: While installing yolov3 using conda on window10 getting error Solving environment: failed When I am trying to install yolov3 on windows10 using Conda, getting following error:
(base) D:\aaa\yolo>conda env create -f yolo.yml
Collecting package metadata (repodata.json): done
Solving environment: failed  ResolvePackageNotFound:
vc==14.1=h0510ff6_3
vs2015_runtime==15.5.2=3

How do I solve this issue?


Q: Create a Spring bean that cannot be autowired I have a class A that extends B, which implements C. Currently, A takes B has an input argument and is the only defined bean that is an implementation of C, so it gets autowired whenever C is needed.
Without changing the ALL of the places where C is needed or the class structure of A/B/C, I need make B a defined bean so the same instance can be re-used. The problem is then I have 2 implementations of C (A and B). Is there a way to mark B so that it cannot be autowired?
Current:
  <bean id="A" class="A">
    <constructor-arg>
      <bean class="B">
    </constructor-arg>
  </bean>

Wanted (so same instance of B can be used elsewhere):
  <!-- TODO: Somehow mark B so it cannot be autowired -->
  <bean id="B" class="B"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

A: If you want to eliminate a bean from autowiring, then you can set autowire-candidate attribute of that bean tag to false.
For example consider your case(Here I am setting B bean's autowire-candidate attribute to false)
 <bean id="B" class="B" autowire-candidate="false"/>

  <bean id="A" class="A">
    <constructor-arg ref="B">
  </bean>

  <bean id="Foo" class="Foo">
    <constructor-arg ref="B">
  </bean>

A: You could use qualifiers attached to @Autowired.
E.g., if you want to wire the bean with id B, you can do the following:
@Autowired
@Qualifier("B")
private C c;


Q: Using NSTrackingArea in an NSView that is unattached to a window? Basically, I want an "invisible" NSView covering my entire screen. I will add an NSTrackingArea to that, so that I get global mouse events as my cursor moves about the screen.
-(void)setTrackingArea
{
    view = [[NSView alloc] initWithFrame:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame];

    NSTrackingArea *area = [[NSTrackingArea alloc] initWithRect:[NSScreen currentScreenForPoint:[NSEvent mouseLocation]].frame options:NSTrackingMouseEnteredAndExited | NSTrackingActiveAlways owner:view userInfo:nil];

    [view addTrackingArea:area];

    [area release];

    //[[window contentView] addSubview:view];

    //I don't want to add the view to a window, as all tutorials say.
}

- (void)mouseExited:(NSEvent *)theEvent
{
    NSLog(@"Exit"); //Never firing
}

Is this possible? Using NSViews and NSTracking Areas without a window?

A: Using an invisible view is definitely not something you want to do.  Look into the addGlobalMonitorForEventsMatchingMask:: class method on NSEvent.
For example, here's how you would add a monitor for a movement of the mouse:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSMouseMovedMask handler:^(NSEvent *mouseMovedEvent) {
    //do something with that event
}];


Q: Implementing File Uploads From Angular to Flask I am trying to implement file uploading for my Web tool. The front end is developed using angular and the back end is using flask. Following tutorials on the flask website I have set up the following flask app:
from flask import Flask, request
from werkzeug import secure_filename
import os

UPLOAD_FOLDER = '/home/openstack/Documents/Confmrg/bcknd/uploads'

app = Flask(__name__)
app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER

@app.route('/uploader' , methods = ['GET' , 'POST'])
def upload_file():
    if request.method == 'POST':
        f = request.files['file']
        filename = secure_filename(f.filename)
        f.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
    return 'File Uploaded'

if __name__ == '__main__':
    app.run(debug = True)

I run this and the web server is hosted on http://localhost:5000
So on my angular component html I place the following:
<form action="http://localhost:5000/uploader" method="POST" enctype = "multipart/form-data">
<input type="file" name="file" />
<input type="submit" />
</form>

However when I run the angular web page, and test it by uploading a file and clicking submit, nothing happens. There is no error, and nothing is output in the console. I must be missing something, could someone point me in the right direction?

A: Form onSubmit handler
To answer your immediate question, what's happening is input type submit in Angular calls the onSubmit method of the form (instead of submitting the form like in plain HTML). And because you don't have a handler for onSubmit in your class, nothing is happening.
For a quick test, follow this link to create a simple onSubmit handler method to test that your submit button works.
Here's a Stackblitz example which logs to console when you click the submit button: https://stackblitz.com/edit/angular-uy481f
File upload
To make file upload work, you would need to make a few things. This touches the component class, creating a new service and injecting it, and updating your form to bind it to the class.

*

*Create a proper Angular form. Here's an example.

*Create a method that will handle the onSubmit() of the form.

*Create a service that will handle Http calls to upload files.

*Inject the service into your class, and call the file upload method of that class.

As you can see, there's a lot involved in making this work unlike having a simple post form in the template. As such, it will be too much for a single answer.
But hopefully, the initial paragraph answered your question and the rest of the answer pointed you in the right direction.


Q: How to bypass code if criteria don't match? The code works when the criteria exists. I get an error when the criteria doesn't exist.
' Define constants.
Const srcName As String = "wfm_rawdata"
Const srcFirst As String = "D2" ' Location for Group
Const dstName As String = "bond_insurance"
Const dstFirst As String = "A2"  ' do not change the 'A' (entire row).

'This function will transfer rows from one worksheet to another worksheet
'  if the value = specified critiera
' Define workbook.
Dim wb As Workbook: Set wb = ActiveWorkbook ' Workbook containing this code.

' Define Source Range
Dim LastRow As Long
Dim srg As Range

' Define worksheet and column am working on and
'  getting the range of last used cell using(LastRow)
With wb.Worksheets(srcName).Range(srcFirst)
    LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row
    Set srg = .Resize(LastRow - .Row + 1, 10)
End With

'Combine' critical cells into a range.
Dim brg As Range ' Built Range --> Range in the new sheet
Dim cel As Range ' Current Cell Range --> Range in the current sheet(rawdata)

'for every cell in group within wfm_rawdata sheet if the value = GO
For Each cel In srg.Cells
    If cel.Value = "BOND INSURANCE" Then
        ' If the range in the new sheet have nothing then
        '  add specific criteria from the group in wfm_rawdata
        If brg Is Nothing Then
            Set brg = cel
         ' if there is range in there combine the new and
         '  old range together  using -> Union function
        Else
            Set brg = Union(brg, cel)
        End If
    End If
Next cel

Application.ScreenUpdating = False

' Copy and delete critical rows of Source Range.
With wb.Worksheets(dstName).Range(dstFirst)
    .Resize(.Worksheet.Rows.Count - .Row + 1, _
        .Worksheet.Columns.Count).clear
    Set brg = brg.EntireRow ' 'Convert' cells into rows.
    brg.Copy .Offset ' Copy. 'Offset' because range is in 'With'.
    brg.Delete ' Delete.
End With

How can I use a Boolean or other function to bypass the above code if the criteria doesn't exist?
For example if criteria "dog" exists then run the code and if it doesn't exist bypass the code.
I use this code to run three modules with code similar to the top code.
Sub master()
Call report1
Call report2
Call report3
End Sub

A: One you've assigned srg you can use Match() to check whether it contains any instances of the term you're interested in:
'...
'...
' Define worksheet and column am working on and getting the range of last used cell using(LastRow)
With wb.Worksheets(srcName).Range(srcFirst)
    LastRow = .Offset(.Worksheet.Rows.Count - .Row).End(xlUp).Row
    Set srg = .Resize(LastRow - .Row + 1, 10)
End With

'Exit if "BOND INSURANCE" is not found in `srg`
If IsError(Application.Match("BOND INSURANCE", srg, 0)) Then Exit Sub
'...
'...


Q: Keep client connected to WebSocket in react native and express server I have a react native application where i have two users using the app (customer and restaurant)
So on checkout I connect the customer to websocket on the express server and once the order is placed i send a message to the restaurant which is supposed to be connected to websocket all time.
However,  sometimes the restaurant is disconnected somehow, so I am trying to keep the restaurant connected, and if disconnected then reconnect again automatically.
In react native restaurant side implementation i have the following code :
this is useWebSocketLite hook to handle connection, send, receive messages and retry connection to server when closed:
function useWebSocketLite({ socketUrl, retry: defaultRetry = 3, retryInterval = 1000 }) {
    const [data, setData] = useState();
    const [send, setSend] = useState(() => () => undefined);
    const [retry, setRetry] = useState(defaultRetry);
    const [readyState, setReadyState] = useState(false);

    useEffect(() => {
        const ws = new WebSocket(socketUrl);
        ws.onopen = () => {
            setReadyState(true);
            setSend(() => {
                return (data) => {
                    try {
                        const d = JSON.stringify(data);
                        ws.send(d);
                        return true;
                    } catch (err) {
                        return false;
                    }
                };
            });

            ws.onmessage = (event) => {
                const msg = formatMessage(event.data);
                setData({ message: msg, timestamp: getTimestamp() });
            };
        };

        ws.onclose = () => {
            setReadyState(false);
            if (retry > 0) {
                setTimeout(() => {
                    setRetry((retry) => retry - 1);
                }, retryInterval);
            }
        };
        return () => {
            ws.close();
        };
    }, [retry]);

    return { send, data, readyState };
}

So based on this, every-time the connection is closed, the connection will retry again.
Besides, when a restaurant launches the app the following code will be implemented:
const ws = useWebSocketLite({
    socketUrl: `wss://${url}/id=${user.user_id}&role=restaurant`
});

This useEffect to establish the connection:
useEffect(() => {
        if (ws.readyState === true) {
            setConnectionOpen(true);
        }
    }, [ws.readyState]);

and this useEffect to handle incoming messages
useEffect(() => {
    if (ws.data) {
        const message = ws.data;
        //dispatch...
    }
}, [ws.data]);

Express server implementation:
This is the code where i handle socket connections and messages in express server:
var webSockets = {}
function setupWebSocket(server) {
    server.on('connection', (socket, req) => {

        if (req) {

            var clientId = req.url
            let regexReplace = /[\[\]/]/g
            let regex = /([^=#&]+)=([^?&#]*)/g,
                params = {},
                match;
            while ((match = regex.exec(clientId))) {
                params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
            }
            if (params.role === 'restaurant') {
                webSockets[params.id] = socket
            }
        }
        socket.on('message', data => {

            let sData = JSON.parse(JSON.parse(data))
            let {id, data} = sData.data
            sendToClient(id, 'order', data)

        })

        socket.on('error', (err) => {
            console.log(err)
        })
        socket.on('close', (code, req) => {
            var clientId = req.url
            let regexReplace = /[\[\]/]/g
            let regex = /([^=#&]+)=([^?&#]*)/g,
                params = {},
                match;
            while ((match = regex.exec(clientId))) {
                params[decodeURIComponent(match[1]).replace(regexReplace, '')] = decodeURIComponent(match[2])
            }

            if (params.role === 'restaurant') {
                delete webSockets[clientId]
                console.log(`${webSockets[clientId]} disconnected with code ${code} !`);
            }

        });
    });

    // sends a message to a specific client
    const sendToClient = (clientId, type, data = {}) => {
        const payload = { type, data }
        const messageToSend = JSON.stringify({ error: false, message: payload })

        if (webSockets[clientId]) {
            webSockets[clientId].send(messageToSend)
            console.log(`${clientId} client notified with this order`)

        } else {
            console.log(`${clientId} websocket client is not connected.`)

        }
    }

}

So most of the time I get 13 websocket client is not connected. which means the restaurant has already been deleted from the webSockets object and its connection already closed.
Apologise for long question and hope someone can help me regarding this.

A: First of all, you should know that this is not a good practice of websockets, where you are forcing the client (the restaurant) to be connected.
Whatever, at the current state of your code, there is an illogical behavior: at the end of the useEffect of your “useWebSocketLite” function, you are closing the socket connection:
return () => {
        ws.close();
    };

Knowing that the useEffect hook is called twice: after the first render of the component, and then after every change of the dependencies (the “retry” state in your case); Your code can be ridden like so: everytime the “retry” state changes, we will close the socket! So for me that is why you got the client disconnected.


Q: Can't generate a new migration in Rails I am trying to generate a new migration to add an Index to a table field with the following :

$ rails generate migration AddIndexToUserEmail

Though, unexpectedly I get the following message

C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-core-3.0.2/lib/rspec/core/formatters/b
  ase_formatter.rb:1:in <top (required)>': uninitialized constant
  RSpec::Support (NameError)
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
  ib/rspec/legacy_formatters.rb:24:inrequire'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
  ib/rspec/legacy_formatters.rb:24:in block in <top (required)>'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
  ib/rspec/legacy_formatters.rb:13:ineach'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/rspec-legacy_formatters-1.0.0/l
  ib/rspec/legacy_formatters.rb:13:in <top (required)>'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
  me.rb:81:inrequire'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
  me.rb:81:in rescue in block in require'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
  me.rb:66:inblock in require'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
  me.rb:59:in each'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler/runti
  me.rb:59:inrequire'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/bundler-1.3.5/lib/bundler.rb:13
  2:in require'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.1/lib/rails/comman
  ds.rb:43:inrequire'
          from C:/Ruby193/lib/ruby/gems/1.9.1/gems/railties-4.0.1/lib/rails/comman
  ds.rb:43:in <top (required)>'
          from bin/rails:4:inrequire'
          from bin/rails:4:in `'

I am not sure what has to be understood here as I had same Constant Unitinialized error when trying to do tests with RSPEC (before I found the right setup).
Though this is a different context here

A: Seems the problem was coming from the following gem:
gem "rspec-legacy_formatters", :group => [:development, :test]
Not sure why I added it to the gem file. I removed it and did a
$ bundle install

which solved the problem


Q: Regex Expression that matches a pattern except for specific matches I'm trying to extract Names from a HTML Response using a RegEx. So far I'm able to do so except I'm getting more than I need, I want to NOT match specific strings such as "Date" or "Today".
Here is my regex:

([^:()]{1,20})<\/li>

And here is a portion of the HTML response against which I'm running the pattern:

...Default Inspector (if any)

Andy Schene

gilberto hubner

Jim Tinner

Kenneth Donovan

RENTAL REG INSPECTORS

Rob Barker

Robert Costello

Ryan BalFour

Sean Angeley

Krissy King

            <input id="ctl07_ddInspector_ClientState" name="ctl07_ddInspector_ClientState" type="hidden" />

        Set Default

                        <input name="ctl07$ddSetDefault" type="text" class="rcbInput radPreventDecorate" id="ctl07_ddSetDefault_Input" value="Next Day (Default)" style="display: block;" readonly="readonly" />

                        select

Next Day (Default)

Today

Specified Date

Next Available (Insp Cap)

No Specified Date

I'm aware of negative lookaheads and this other post: Regex that matches a pattern and doesn't match specific words. But I can't make that work for me. The following still brings back the unwanted matches:

((?!Date$)[^:()]{1,20})<\/li>

A: *

*You don't want Date$ because the $ means "This is the very end of the string."

*Since your examples show that the unwanted strings containing "Date" have it appearing right before
, you want to put your negative lookaround right there, not earlier.

*Now, since you want to be looking backward to find Date, you want a lookbehind, not a lookahead. (add < in the middle of your ?!)

This ends up looking like:

([^:()]{1,20})(?<!Date)<\/li>

If you're also trying to remove "Today" entries, then make it Today|Date:

([^:()]{1,20})(?<!Today|Date)<\/li>

P.S.: Do you really need to check for all that whitespace at the beginning?

A: As the location of 'Date' or 'Today' is not fixed,
so here is my suggestion:
string[] filter = {"date","today"};
var result = Regex.Matches(yourhtml,"(?i)
([^:()]{1,20})<\/li>")
.Cast<Match>()
.Where(m=>!filter.Any(f=>m.Groups[1].Value.ToLower().Contains(f)));

A: You cannot use the $ because it indicates the end of the entire string.
Try this one:

((?!(.)*(Date|Today))[^:()]{1,20})<\/li>


Q: Can a stack allocated Rust buffer be accessed through C++? In order to avoid head allocations, and since I know the maximum MTU of an ethernet packet, I created a small buffer: [u8, MAX_BYTES_TRANSPORT] in Rust, that C++ should fill for me:
pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> std::result::Result<(), &str> {
    let mut buffer: [u8; MAX_BYTES_TRANSPORT] = [0; MAX_BYTES_TRANSPORT];
    //number of bytes written in buffer in the C++ side
    let written_size: *mut size_t = std::ptr::null_mut::<size_t>();
    let r = unsafe{openvpn_client_receive_just(
        buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client)};

So, the function openvpn_client_receive_just, which is a C++ function with C interface, should write to this buffer. Is this safe? I couldn't find information about a stack allocated Rust buffer being used in C++
This is the function:
uint8_t openvpn_client_receive_just(
    uint8_t *buffer, size_t buffer_size, size_t *written_size, OpenVPNSocket *client)

A:
Can a stack allocated buffer be accessed through C++?

Yes.
From the type-system perspective there is no difference between statically allocated, stack allocated, or heap allocated: the C signature only takes pointer and size, and cares little where that pointer points to.

Is this safe?

Most likely.
As long as the C function is correctly written and respects the bounds of the buffer, this will be safe. If it doesn't, well, that's a bug.
One could argue that it's better to have a heap-allocated buffer, but honestly once one starts writing out of bounds, overwriting arbitrary stack bytes or overwriting arbitrary heap bytes are both bad, and have undefined behavior.
For extra security, you could use a heap allocated nested between 2 guard pages. Using OS specific facilities, you could allocate 3 contiguous OS pages (typically 4KB each on x86), then mark the first and last as read-only and put your buffer in the middle one. Then any (close) write before or after the buffer would be caught by the OS. Larger jumps, though, wouldn't... so it's a lot of effort for a mitigation.

Is your code safe?

You most likely need to know how many bytes were written, so using a null pointer is strange.
I'd expect to see:
let mut written: size_t = 0;
let written_size = &mut written as *mut _;

And yes, that's once again a pointer to a stack variable, just like you would in C.

A note on style. Your Rust code is unusual in that you use fully typed variables and full paths, a more idiomatic style would be:
// Result is implicitly in scope.

pub fn receive(&mut self, f: &dyn Fn(&[u8])) -> Result<(), &str) {
    let mut buffer = [0u8; MAX_BYTES_TRANSPORT];

    let mut written: size_t = 0;
    let written_size = &mut written as *mut _;

    //  Safety:
    //  <enumerate preconditions to safely call the function here, and why they are met>
    let result = unsafe {
        openvpn_client_receive_just(
            buffer.as_mut_ptr(), buffer.len(), written_size, self.openvpn_client)
    };

    translate_openvpn_error(result)?;

    let buffer = &buffer[0..written];
    f(buffer);

    Ok(())
}

I did annotate the type for written, to help along inference, but strictly speaking it should not be necessary.
Also, I like to preface every unsafe call I make with the list of pre-conditions that make it safe, and for each why they are met. It helps me audit my unsafe code later on.


Q: Compare count of characters with a constant value, then execute next statement I have a PowerShell script where I get the count of certain string from a file, then go to next step or execute next step only if the string count is 30.
I do have the code for getting the count of the string, as well the code for executing the next step. The only thing missing is to incorporate if statement.

To get the count of string, I am using the following:
$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches

To do the next step, I am using following;
"d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%

How to include if condition in between above two codes, so that last command will follow, only if the count of the string is more than 30?

A: First off, don't use $Matches for anything user-defined - it's an automatic variable.
With that out of the way: since Select-String may return multiple lines, you should sort them by length and test the length of the longest one:
$FileContent = Get-Content "YourFile.txt"
$LongestMatch = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches |Sort-Object {$_.Line.Length} |Select-Object -Last 1

if($LongestMatch.Line.Length -gt 30){
    # We found a match in a string longer than 30 chars!
    # run plink here!
}

A: This may be too simplistic. I feel like there is something I must have missed in the question.
$FileContent = Get-Content "YourFile.txt"
$Matches = Select-String -InputObject $FileContent -Pattern "/export" -AllMatches

if ($Matches -eq 30) {
    & "d:/scripts/plink.exe" -ssh %1 -l hpov -pw NDIA123 -m %com%|find "host" >>%lnm%
}


Q: Better way to combine tables than multiple joins? I have two dfs, df1 and df2. I need to combine the dfs in a way that might require multiple left joins, but I have a feeling there's a better way to do this.
df1 is a table of locations and people (id numbers) associated with them, it looks like this.
location person1 person2 person3 ... personn
1        12      450     2       ... 90
2        23      218     4       ... 3
3        1000    274     937     ... 318
....     ...     ...     ...     ... ...
1350     1       41      10      ... 101

df2 contains information about the people. It looks like this:
person year action
1      2020 a
2      2020 a
3      2020 b
4      2020 c
1000   2020 a
1      2019 c
2      2019 b
3      2019 a
4      2019 c
...    ...  ...
1000   2019 b

Ideally, I'd like the combined dataset to look like this:
location year action_a_count action_b_count action_c_count ... action_n_count
1        2020 1              0              0              ... ...
2        2020 0              1              1              ... ...
3        2020 1              0              0              ... ...
1350     2020 1              0              0              ... ...
1        2019 0              1              0              ... ...
2        2019 0              1              1              ... ...
3        2019 0              1              0              ... ...
1350     2019 0              0              1              ... ...
...      ...  ...            ...            ...            ... ...

Right now my instinct is to do a series of left joins to get the actions for each person into df1, then figure out a way to count them.

A: You could restructure df1 to have 2 columns, location and person. That would simplify the subsequent operations.
df1_new = df1.melt(id_vars='location',
                   value_vars=df1.columns[1:],
                   value_name='person')

df1_new = df1_new.drop('variable', axis=1)

Now you can join df2 and df1_new
combined = df2.join(df1_new.set_index('person'), on='person', how='left')

Then create a pivot table
combined.pivot_table(index=['location', 'year'], columns='action',  aggfunc='count')

After the pivot table is created, you can rename the columns however you'd like.


Q: Where should logic go for deciding which SQL query to execute I have a DAO with a method CommitmentListDAO.getListByOwnerBadge that returns an arraylist of commitment items against a supervisor badge (database field OWNED_BY)
    String SQL_VIEW_LIST_BY_SUPERVISOR = SELECT_QUERY +
    " WHERE c.OWNED_BY = ? " +
    " ORDER BY p.PROGRAM_NAME";

Now, I want to add a pull down on my web form to allow the user to choose between Owned By or Tasked To
I'll need to add a WHERE c.TASKED_TO = ? clause in the DAO.
Do I perform the logic for which field to search on within the DAO - say a passed in parameter of the pulldown (Never the request object) and rename the method to getListByBadge(String whichField, String badge) or should my CommitmentListForm class have this logic and then make the appropriate call to either getListByOwnerBadge or getListByTaskeToBadge

A: I would go with a DAO on it with two different methods to clearly differentiate what the call does.
The point of a DAO is to hide the SQL implementation details. You should always consider a question like this from the standpoint of, "What if I switched to a different persistence mechanism, like HBase?" The HBase implementation may not store this in a way that simply differentiates by a field name. The DAO should make it possible to hide that detail, thus the different methods.
Just my opinion, of course. :)

A: I would determine the logic in your controller and separate the two SQL queries into getListByOwnerBadge or getListByTaskeToBadge. That way you avoid having a method that "does it all" and could quickly get out of hand. Furthermore, other developers who choose to use the "does it all" method will have to inspect the method's internals to see what valid Strings can be passed in, whereas an explicit method call makes it obvious as to what the method is accomplishing.

A: I think that the second solution is better. Keep DAO as simple as it is possible. No logic, no flags. Create 2 simple methods and make decision in form which one to call. Or even create yet another layer between form and DAO that decides which DAO method to call.

A: To summarize:
From @McStretch - The logic for which to call goes in your controller.
From @rfreak - The query methods themselves go in the DAO
Here's an example:
//Controller
CommitmentListAction {

updateForm(...){
  List<CommitmentItem> commitmentItems;
  if (formUsesOwnedBy){
    commitmentItems = CommitmentItemDAO.getListByOwnerBadge(...);
  } else {
    commitmentItems = CommitmentItemDAO.getListByTaskeToBadge(...);
  }
  // Do stuff with commitmentItems.
}
// DAO

getListByOwnerBadge(...){
 String SQL_VIEW_LIST_BY_SUPERVISOR = SELECT_QUERY +
    " WHERE c.OWNED_BY = ? " +
    " ORDER BY p.PROGRAM_NAME"
  return doQuery(SQL_VIEW_LIST_BY_SUPERVISOR); // Performs the actual query
}

getListByTaskeToBadge(...){
String SQL_VIEW_LIST_BY_TASKED_TO = SELECT_QUERY +
    " WHERE c.TASKED_TO = ? " +
    " ORDER BY p.PROGRAM_NAME"
  return doQuery(SQL_VIEW_LIST_BY_TASKED_TO); // Performs the actual query
}

If you're going to have many different views of the CommitmetItems or many different criteria, consider passing in the criteria to the DAO. But only do this at the time when it appears there is an excessive number of getListBy[blah] methods polluting the DAO.


Q: Gitlab CI Runner slow to complete job I've been using the GitLab CI runner on Windows for a couple of years now, and am wondering why it takes a long time between when the compile has actually completed before GitLab deems that the job has completed.
Here's a few screen grabs to show what I'm talking about. This one shows that the compilation is complete:

MSBuild is complete, so the build stage is complete. The 31 second time is the time it took MSBuild to finish, but there was another minute or so of getting packages from NuGet and Bower and NPM before that. Here's a picture of the current job running time:

But then GitLab sits with the 3 dots for another two minutes or so before it decides the job has actually succeeded:

I turned on CI_DEBUG_TRACE but it didn't show much that seemed useful to me. I've also played around with caching and artifacts but turned them off because the artifacts were too big and it didn't significantly change the build time. Here's the .gitlab-ci.yml file:
stages:
 - build
 - test

before_script:
  - '.nuget\\nuget.exe restore <name>.sln'
  - 'call bower install'
  - 'call npm install'
  - 'call gulp'

cache:

build:
 stage: build
 dependencies: []
 script:
  - '"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe" <name>.sln /t:ReBuild /p:Configuration=Release'
 retry: 2

test:
 stage: test
 dependencies: []
 script:
  - '"C:\\Program Files (x86)\\MSBuild\\14.0\\Bin\\MSBuild.exe" <name>.sln /t:ReBuild /p:Configuration=Release'
  - ".\\packages\\xunit.runner.console.2.3.1\\tools\\net452\\xunit.console.exe UnitTest\\bin\\Release\\UnitTest.dll"
 retry: 2

A couple of minutes doesn't seem too bad except it's happening with each stage in the pipeline, so it adds up quickly.
In the past that 2-minute delay didn't happen, but I don't know what might have changed or what I might have done to cause it. The runner is the latest version.
Any ideas or suggestions?


Q: Access: Combining multiple rows into one, but show text I am trying to form a single row from multiple rows by using GROUP BY in my SQL statement.
Problem is, the raw data I am working with contains data that I do not need, and all the fields are populated with text strings.
For example,
ID COURSE
01 Baking 101
01 Driving 102
01 Writing 101
02 Baking 102
02 Writing 101

I don't need 'Writing', only 'Baking' and 'Driving'. So I'd like my data to turn up like this:
ID Baking     Driving
01 Baking 101 Driving 102
02 Baking 102 -

I am selecting records by seeing if they contain the relevant keywords, because my raw data source contains the course history of all courses, not just the ones that I am concerned with. And the spelling of the courses can vary for the same course.
As of now, I am using a IIf statement to return a 1 if the keyword is present and a 0 if the keyword isn't. I then Sum it and GROUP BY my ID (Personal identifier). So my table turns out a bit like this.
ID Course1 Course2 Course3 Course4 Course5
01    1       0       0       1       0
02    0       1       1       0       0

What I would like is for my query to display the record IF the record contains a certain keyword, while still grouping and truncating all related records into a single row.
A GROUP BY function can't do that (afaik) because it doesn't know how to handle text strings (i.e. it doesn't know which record to display), which is why I am using an IIf to generate a number then Sum to allow GROUP BY. Is there a way for me to perhaps convert the number back into the text (i.e. the text that satisfies my IIf statement)
I apologise for not being able to provide an actual sample of the data, but it's corporate data that I can't share unfortunately.
Edit:
What I mean when I say the spelling varies is something like this:
1.Baking 101 Cse
2.Baking 101 Course
3.Baking-101 Cse

So as of now, my SELECT statement is something like this
SELECT Courses.CourseName,
Sumiif((Courses.CourseName Like "*Baking*",1,0) AS BAKING
FROM Courses
GROUP BY Courses.PersID

This is quite a bit simplified, because I have more than 1 course to handle.
So the problem I am facing is that I want to display the actual data in the field, and not the result of my IIf function. i.e. instead of a 1, I want to see the name of the course. However, I also need to group by my primary key, which requires that I use an aggregate function. I am not aware of an aggregate function that can do this with strings.

A: Consider a table or query like:
+----------+------------+---------------+
| CourseID | CourseName | CourseSection |
+----------+------------+---------------+
|       01 | Baking     |           101 |
|       01 | Driving    |           102 |
|       01 | Writing    |           101 |
|       02 | Baking     |           102 |
|       02 | Writing    |           101 |
+----------+------------+---------------+

And query:
TRANSFORM First(Courses.CourseSection) AS FirstOfCourseSection
SELECT Courses.CourseID
FROM Courses
WHERE (((Courses.CourseName)<>"Writing"))
GROUP BY Courses.CourseID
PIVOT Courses.CourseName;

Output:
+----------+--------+---------+
| CourseID | Baking | Driving |
+----------+--------+---------+
|       01 |    101 |     102 |
|       02 |    102 |         |
+----------+--------+---------+

If your course names are less consistent for spelling and the name and section are actually in one field but the section suffix is consistent, then emulate a crosstab like:
SELECT Courses.CourseID, Max(IIf(InStr([CourseName],"Baking")>0,Right([CourseName],3),Null)) AS Baking,
Max(IIf(InStr([CourseName],"Driving")>0,Right([CourseName],3),Null)) AS Driving
FROM Courses
GROUP BY Courses.CourseID;


Q: How to download a file from the server using a POST request or a more secure method without using a GET request for iOS application. I do not want to use asihttp methods so is there a way to download a file from the server without having to use a get request? How to use a post request to download the file from the server?

A: Since the OP wants the answer regardless, I will use PHP for this.
iOS client side:
NSString *phpURLString = [NSString stringWithFormat:@"%@/getFile.php", serverAddress];
NSURL *phpURL = [NSURL URLWithString:phpURLString];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:phpURL];

NSString *post = [NSString stringWithFormat:@"filePath=%@", filePath];
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding];
NSString *postLength = [NSString stringWithFormat:@"%d", [post length]];

[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setHTTPBody:postData];

NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil]:

For the PHP side:
<?php

$filePath = htmlspecialchars($_POST['filePath']);

$fileData = file_get_contents($filePath);

echo $fileData;

?>

This is very basic. Also for the iOS side you would want to wrap that entire request in a code block that is run asynchronously in the background. You could use GCD for that. Once you have the file as responseData in iOS you can save the file to the local container and then do many things with it.


Q: Populating Tabs WinForms Goes Undetected without User View This might just be a small quirk. But I've built a small windows form application with multiple tabs.
I have a feature that allows users to "load" the entries in each of the tabs by opening a json file. This lets them avoid manually inserting the data. At the same time, I have a "check" to make sure that all required fields have been populated.
What I've found is that even if the load process is successfully populating all the right fields, the user still needs to select each tab (even though they are already filled), in order to avoid hitting the flag.
Hopefully, this makes sense. Right now, my work around is to have the program flip through each tab automatically upon "load", but it seems strange that winforms can't detect a text box has been filled unless the tab is viewed.
Any advice?

A: Some events only fire when the control is visible. This sounds like what you should do is decouple the text entries from the control and store them in another object which fires off the filled events then do data binding to those entries.
This has the nice benefit of decoupling the UI from the data storage (always a nice thing) as well as freeing you from the vagaries of the .net UI system (both winforms and wpf have 'interesting' quirks like the above which assume specific behavior preferences).