text:
Q: Powerpoint VBA/Macro: Deactivate (Grey out) Button on Ribbon, if no shape is selected I have a macro in Powerpoint that gives me Information of a Shape. To bypass the error if no shape is selected I insert an errormask. However, this is very annoying.
Is it therefore possible to grey out the button if e.g. no Shape is selected. That way the user would npot even have a chance to click it.
Custom UI XML:
http://pastebin.com/T6NQ8WF8

A: Assuming you are using a 2007+ version of PowerPoint, the only way to manipulate the ribbon controls, buttons, etc., is through ribbon extensibility.  It is possible to do this at run-time, with a vba hook, but it is much more difficult than in previous versions of PowerPoint where you could just use VBA to manipulate the controls' .Enabled or .Visible properties.
Here is an example of using ribbon extensibility to customize the ribbon at run-time.  As you can see, it is not easy.  I will show this in Option 2, below.
In this case, you have an error condition that you can easily identify using the .Type property of the Selection.ShapeRange.  I think that attempting to conditionally disable this button at run-time (Option 2, below) is probably more trouble than it is worth.
Update

Is there a setting that greys your all buttons that don't have an effect.

No. The macros are the "effect", even if the result of the macro is that no action is performed.  What you are asking is whether there is a setting which can compile and interpret your macros, determine whether that macro performs "an action" (e.g., manipulates a shape, changes a property assignment, etc.) and then disable buttons based on this determination.  There is no such setting.
OPTION 1 -- Simply Do Not Display the MsgBox; Perform No Action if Invalid Selection
I will make some edits to clean up your code and use a better method of avoiding that error:
Sub Infos()

   Dim n as String
   Dim w as String
   Dim h as String
   Dim l as String
   Dim T as String

   With ActiveWindow.Selection.ShapeRange
   Select Case .Type
        Case 0
            'MsgBox ("No shape selected.")
            Exit Sub
        Case Else
            n = .Name
            w = .Width
            h = .Height
            l = .Left
            T = .Top

            MsgBox "Name: " & n & Chr$(CharCode:=13) & "Länge: " & w & _
                   Chr$(CharCode:=13) & "Höhe: " & h & Chr$(CharCode:=13) & _
                   "Linkeposition: " & l & Chr$(CharCode:=13) & "Höhenposition: " & T
    End Select
End Sub

OPTION 2 -- Use an Application Event Handler and Manipulate Ribbon at Run-Time
I mentioned that this is not easy.  I uploaded an example file to Google Docs Presentation1.pptm.  This should get you started. You can see now how much difficult this method is.  If you are creating a PPAM/Add-In file, there are further considerations and complexities you may encounter. Good luck!
There are several errors in your code.
1. Your XML is not valid when I check in Custom UI Editor. I edited it here:
http://pastebin.com/SpG0Rtqq
2. Your Infos macro contains errors. You omit the End With statement, also, your n assignment will fail (and the rest of them will produce strange result) if the selection is multiple shapes. You can fix that by:
n = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Name)
w = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Width)
h = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Height)
l = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Left)
T = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Top)

Once you have fixed those components...
Add a module called mod_EventHandler, which includes this code. This will create an application event-handler class object, cEventClass:
Option Explicit
Public cPPTObject As New cEventClass
Public TrapFlag As Boolean

Sub TrapEvents()
'Creates an instance of the application event handler
If TrapFlag = True Then
   MsgBox "Relax, my friend, the EventHandler is already active.", vbInformation + vbOKOnly, "PowerPoint Event Handler Example"
   Exit Sub
End If
   Set cPPTObject.PPTEvent = Application
   TrapFlag = True
End Sub

Sub ReleaseTrap()
If TrapFlag = True Then
   Set cPPTObject.PPTEvent = Nothing
   Set cPPTObject = Nothing
   TrapFlag = False
End If
End Sub

Since we need this class object, add a class module to your PowerPoint file, named cEventClass.  In this module, put this code below.  This code forces a refresh of the ribbon. This procedure implicitly calls the EnabledBtInfo subroutine, which then tests if the current selection is Shape(s).
Option Explicit
Public WithEvents PPTEvent As Application
Private Sub PPTEvent_WindowSelectionChange(ByVal Sel As Selection)
    'Force refresh of the "btInfo" button:
    RefreshRibbon "btInfo"
End Sub

And finally, another standard code module with this code to control the Button's visibility/enabled. Note that EnabledBtInfo is the VBA Hook for this button, and it tests whether Selection is shapes, before refreshing the ribbon:
Option Explicit
Public Rib As IRibbonUI
Public xmlID As String

'Callback for customUI.onLoad
Sub RibbonOnLoad(ribbon As IRibbonUI)
    TrapEvents  'instantiate the event handler
    Set Rib = ribbon
End Sub

Sub EnabledBtInfo(control As IRibbonControl, ByRef returnedVal)
    'Check the ActiveWindow.Selection.ShapeRange
    returnedVal = (ActiveWindow.Selection.Type = ppSelectionShapes)
    Call RefreshRibbon(control.Id)
End Sub

Sub RefreshRibbon(Id As String)
    xmlID = Id
    If Rib Is Nothing Then
        MsgBox "Error, Save/Restart your Presentation"
    Else
        Rib.Invalidate
    End If
End Sub

When a shape(s) is selected, the magnifying glass icon is enabled:

When shape(s) is not selected, button is disabled:

And finally, when multiple shapes are selected:


text:
Q: How do I add custom snippets to zen-coding? I'm trying to get how to add custom snippets to Zen Coding (ZC) plugin for Notepad++. I found the file where ZC stores its snippets

C:\Program Files\Notepad++\plugins\NppScripting\includes\Zen Coding.js

But I have some questions:

*

*What the difference between "snippets" and "abbreviations" ?

*ZC expands typed abbreviations differently in different contexts. For example Z followed by Ctrl+E sometimes expands as z-index:|; and sometimes as <z></z>. How does ZC recognize the context?

A: Actually, Zen Coding is now renamed as Emmet, which is also available to Notepad++ and it have some docs on customization.
It seems that you need to read on it's snippets.json format.
I can't see the difference between the snippets and abbreviations there, so it would be best to try both ways.
Zen Coding (and Emmet) recognize context based on the editors, for example in ST2 it is based on the current Syntax and Scope, I think there should be something similar to Notepad++

A: This is an example of an abbreviation:
ul.myClass0$>li*5>a

This is an example of a snippet:

A: I have not worked with Zen Coding but I prefer to run a macro to store most of my snippets.  I find them easy and customizable and you can set whatever shortcut key combo you would prefer.
If you go to Macro > "Start Recording" and then enter in whatever snippet you would like then press "Stop Recording" and then "Save Current Recorded Macro" it will prompt you for what shortcut key you would like.  There might be a more elegant way to accomplish this, but I find quick and easy is always good.
Hope this helps.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cassandra json2sstable Null Pointer Exception I'm using Cassandra 0.7.4. I have been breaking my head for most of today to make a simple import with json2sstable util. I'm in Test Cluster.
I create a simple keyspace KS1.
I create a simple CF mycf.
I insert a row with only one column like set mycf[key1][col1]='col1value'

I export the above with sstable2json util to a file called out. But when I try the reverse (import) it always gives NPE.
C:\>json2sstable -K KS1 -c mycf C:/out C:/var/lib/cassandra/data/kS1/mycf-f-2-Data.db
java.lang.NullPointerException
        at org.apache.cassandra.db.ColumnFamily.create(ColumnFamily.java:67)
        at org.apache.cassandra.db.ColumnFamily.create(ColumnFamily.java:61)
        at org.apache.cassandra.tools.SSTableImport.importJson(SSTableImport.java:194)
        at org.apache.cassandra.tools.SSTableImport.main(SSTableImport.java:421)
ERROR: null

I looked at the source code. There is an assert where the CFMetaData is checked to be not null. This is obviously saying it is null but why?
any suggestions greatly appreciated.

A: Ok this is what I did - I couldnt delete the post so just recording what I did. I did a fresh install of Cassandra 0.7.4. I did the same steps again. This time I just changed the timestamp value of the column a little (some random increase). The NPE was gone but it gave a out of memory error. I read here if you get the OOM error you can resolve it by changing the compaction setting in cassandra.yaml. Changed that and it works now. I really dont know which of the steps fixed the problem.


text:
Q: javascript progressive counter yesterday i found a nice effect on some website wich i decided to implement on my projects, its a simple javascript progressive counter, it will look something like this

obviously it starts from 0 to X without looping and looks more smoother in live web, anyway, i could not find a third party snipet, how i can achieve this!?

A: progressive-counter.js
progressiveCounter=function(params) {

    /*

    autor:

    some eccentric money maker <3

    usage:

    give a progressive transition effect to a counter who starts from X to Y

    params:

    id                  ~   string      ~   to identify internally the counter
    container           ~   object      ~   where the result will be displayed
    from                ~   int         ~   number to start
    dest                ~   int         ~   optional, number to end
    destFromProperty    ~   string      ~   optional, data defined with "data-" on "container" to specify number to end
    format              ~   function    ~   callback to be used to format the output
    finished            ~   function    ~   callback to be used at the end of iteration

    note:

    code made by another snipet of code found on some site, my thanks to original coders by the idea, all you need is share :*

    */

    // ...

    if(typeof(progressiveCounter_data)=="undefined")
    progressiveCounter_data={};

    // ...

    if( (typeof(params.id)!="string" || typeof(params.id)=="")
        || typeof(params.container)!="object"
        || (typeof(params.dest)=="undefined" && typeof(params.destFromProperty)=="undefined")   )
    return;

    // ...

    params.from=parseInt(params.from,10);

    if(typeof(params.from)!="number")
    return;

    if(params.destFromProperty)
    params.dest=$(params.container).data(params.destFromProperty);

    params.dest=parseInt(params.dest,10);

    if(typeof(params.dest)!="number")
    return;

    if(params.from>params.dest)
    return;

    if(typeof(params.format)!="function")
    params.format=null;

    if(typeof(params.finished)!="function")
    params.finished=null;

    // ...

    progressiveCounter_data[params.id]={

        container:params.container,
        from:params.from,
        dest:params.dest,
        shrsCounterTimestep:10,
        format:params.format,
        finished:params.finished

    };

    // ...

    progressiveCounter_iterate(params.id);

}

progressiveCounter_iterate=function(id) {

    // ...

    if(typeof(progressiveCounter_data)=="undefined" || typeof(progressiveCounter_data[id])!="object")
    return;

    // ...

    var data=progressiveCounter_data[id];

    // ...

    var delta=data.dest-data.from,
        threshold=15,
        lastThreshold=4,
        timestepIncrement=15,
        numberFormatted=""
        ;

    // ...

    if(delta<threshold)
    data.shrsCounterTimestep+=timestepIncrement;

    delta=Math.ceil(delta*0.05);

    if(data.from>=data.dest-lastThreshold){

        delta=1;
        data.shrsCounterTimestep=350;

    }

    data.from+=delta;

    // ...

    if(data.format)
    numberFormatted=data.format(data.from);
    else
    numberFormatted=data.from;

    // ...

    if(data.from>=data.dest){

        data.from=data.dest;
        $(data.container).text(numberFormatted);

        if(data.finished)
        data.finished();

    }
    else {

        $(data.container).text(numberFormatted);
        setTimeout(function() { progressiveCounter_iterate(id); },data.shrsCounterTimestep);

    }

};

basic usage
progressiveCounter({

    id:"stats_visits",
    container:$("#element").get(0),
    from:0,
    dest:43800

});


text:
Q: How do I do a binary diff on two identically sized files under Linux? I have two identically sized files, and I need to do a binary diff to check whether they're the same.
I'm currently runnnig diff file1.img file2.img but it's taking quite a while to process my 4 GB files. Is this the most efficient way to do this?

A: cmp is designed to find differences in binary files.  You might also try checksumming (sum) and compare the hashes.

A: If I just want to know if they are the same, I prefer to use sha1sum if it's available, or md5 as a fallback.
If I want to know how different they are, or where they're different, one thing that works is to crank them both through od ('octal dump', which usually has a hex option) to make temporary files and then diff those.

A: One of the most common ways of determining if two files are identical (assuming their sizes match) is using a program to create a "hash" (essentially a fingerprint) of a file. The most common ones are md5sum and sha1sum.
For example:
$ md5sum file1 file2
e0e7485b678a538c2815132de7f9e878  file1
4a14aace18d472709ccae3910af55955  file2

If you have many files that you need to check, for example if you are transferring a directory full of files from one system to another, you can redirect the output from the original system to a file, then md5sum/sha1sum can automatically use that file to tell you which files are different:
$ md5sum file1 file2 > MD5SUMS
... copy file1, file2, MD5SUMS across
$ md5sum --check MD5SUMS
file1: OK
file2: OK

A: Found a solution - the cmp tool which comes with most Linux flavours.

A: I just ran some benchmarks on a 100+ MB file.  diff was the fastest, while cmp came second, and using md5sum came in last.
# time diff file1 file2; echo $?

real    0m0.122s
user    0m0.009s
sys 0m0.113s
0
# time cmp file1 file2; echo $?

real    0m0.213s
user    0m0.097s
sys     0m0.117s
0
# time md5sum file1 > /tmp/test; time md5sum file2 > /tmp/test2; diff /tmp/test /tmp/test2; echo $?

real    0m0.279s
user    0m0.211s
sys     0m0.066s

real    0m0.316s
user    0m0.225s
sys     0m0.073s
0

I reran the exercise with a 4.3 GB file, and had to delete and recreate the file with dd since RAM caching was greatly affecting the results.
$time diff file1 file2; echo $?

real    0m19.325s
user    0m0.995s
sys 0m5.280s
0

$time cmp file1 file2; echo $?

real    0m36.106s
user    0m4.399s
sys 0m6.147s
0

$time md5sum file1 > /tmp/test; time md5sum file2 > /tmp/test2; diff /tmp/test /tmp/test2; echo $?

real    0m10.441s
user    0m8.054s
sys 0m2.357s

real    0m24.682s
user    0m8.027s
sys 0m3.442s
0

Based on these results I would recommend moving the files to a RAMFS mount, and sticking with diff.


text:
Q: How to /setblock a specific type of redstone (Debug mode) I've had a look at the new hidden world type on 1.8, and I've just wondered how to get a type of redstone that goes up in the north part of the square, and I want to use the /setblock command to create this without the appropriate blocks.

A: @ModDL gave a great answer, but sadly on my Minecraft 1.8, when I tried that using blockdata, it didn't do anything. I still appreciate his answer, although.
Check out the answers at How to place redstone using Command Blocks.
Even when I first examined it using F3 on my Minecraft in 1.8, it showed it like this:
north:none
south:none
etc.

I tried modification using /blockdata but that didn't work.
So then I thought: Hmm... what about data values?
So then I tried /setblock (x) (y) (z) redstone_wire (0-15) and then like a miracle, it worked!
It turns out Minecraft is showing what the damage value corresponds to.
In 1.8+ it interprets the damage value so that it's human-readable.
But in 1.7 and lower, it just shows (block name)/(damage value).

A: /setblock x y z minecraft:redstone_wire 0 replace {north:"none",south:"none",east:"none",west:"none",power:0}

Switch the none out for what you want:
none - no connection in that direction
side - goes horizontally in that direction
up - diagonally upward in that direction
in your case switch the north none with up.


text:
Q: Shows Invalid Object Name in Stored Procedure I am to very new to SQL Server and to the Stored Procedure. I tried to create a Stored Procedure for updating the table. I used the below statement in the stored procedure and executed it, worked fine
CREATE PROCEDURE [dbo].[usp_UpdateDB]

When I changed it to below code
ALTER PROCEDURE [dbo].[usp_UpdateDB]

It shows in the work area like this,

But when I execute the stored procedure, it shows

I even checked, the created usp_UpadteDB Stored Procedure exists under the Stored Procedures folder and did refreshes too. What could this be?

A: It got solved. I closed the SQL Server Management Studio and open again, checked the Stored Procedure. It is not showing Invalid object name any more.


text:
Q: Android Java: R.id.variable1..variable2..variable3..etc I'm trying to learn Java for Android and not sure how to even Google this. I was wondering if there's a way to programmably attach a number to the end of R.id.variable or R.drawable.variable etc?
Basically I have several images labeled image1, image2, image3, etc. I want to update the ImageView drawable to be based on another variable. So if that passed variable is "1", it will update the view to "image1". If it's "2" it will update "image2" and so on but I don't know if there's a way to attach "1" to "R.drawable.image" when calling the update.
How is the best way to go about doing this?

A: Maybe help:
Your images: image1.png, image2.png, ...., imageN.png
You can find their id :
getResources().getIdentifier("IMAGE_NAME", "drawable", context.getPackageName())

So:
 int idImage1 = getResources().getIdentifier("image1", "drawable", context.getPackageName())
 int idImage2 = getResources().getIdentifier("image2", "drawable", context.getPackageName())
  .....
 int idImageN = getResources().getIdentifier("imageN", "drawable", context.getPackageName())

A: What you're talking about is called Reflection.  It can get a bit messy, so for the situation you're describing it's probably better to have your images in an array or list and use the argument as the index to retrieve them.

A: Use an array! You can of course use whatever data structure you want, you might find that a List (specifically an ArrayList) lets you use some more of the Collections API. Alternatively if you want to refer to your images by name you can use a Map.
Image[] myImages = new Image[n];
//populate images e.g. myImages[0] = new Image();

void updateImage(int imageNo) {
    Image i = myImages[imageNp]; //arrays start at 0 not 1
    //do stuff to i
}

A: To grab a resource by dynamic name, use getIdentifier(). That function takes a string and returns the ID of the resource by that name
Here's an example from my code, where I get the resource ID of the string resource with the name "run_arbitrary-integer_summary":
getResources().getIdentifier(
            String.format("run_%d_summary", mSelectedRun),
            "string",
            getPackageName()
            );

There may be better ways of doing what you're doing, but I'll let people who are more familiar with Android go into that...


text:
Q: How to call all destructors? i have a big problem. When i throw an exception or call std::terminate or std::exit, the object destructor does not runs. Well this is the problem, my code is full of with this statements, because i was thinking this statements are calling destructor.
How i can solve this problem? I can not change the structure of the classes, i have 10K of code and many classes.
void Function(int Stage)
{
    switch (Stage)
    {
        case 0:
            //Somehow call the destructors
            break;
        case 1:
            //initialize
            break;
        default:
           //Give an error message and call the destructors
   }
}

A: The destructors should run automatically upon exceptions etc.., this is exactly why they were invented in the first place.
Perhaps you created you objects using new? In which case you need to delete them explicitly (and then the destructors will run).


text:
Q: Adding Zeros Until Length of String = n I made the mistake a while back of stripping the leading zeros off of some data that I know has a length of n digits.  I have filtered for only those with less than n digits, and there are variable lengths.  Is there a way to use the REPLACE function or something else to account for the fact that I want to keep adding zeros to these filtered cells until the length becomes n?
EDIT: My current function is simply
=IF(LEN(K2)=n-1,CONCATENATE(0,K2),IF(LEN(K2)=n-2,CONCATENATE(0,0,K2),IF(LEN(K2)=n-3,CONCATENATE(0,0,0,K2),....,"")))

but I imagine there must be a more efficient formula.

A: Eg:
=RIGHT("00000" & A1, 5)

Or:
=RIGHT(REPT("0",5) & A1, 5)

Adjust the 5 to the total padded length you want.

A: If all the number in the column are the same length you could do custom formatting = 0000000 with the number of 0's you need.


text:
Q: How to build only specific objects in the screen I have built an app that shows images like Pinterest
like that;
And, When I scroll down, after passing 25 images, my build widget refreshs the page and adds new 25 images to the screen and my screen has 50 images and so on. However, this takes me again the top of the screen because of adding new 25 images.  because of that, I see again the images that I already see.
And, I want to don't refresh the page again while adding new 25 images but my builder widget works only in this way.
My class file that has builder widget;
class HomeView extends StatefulWidget {
  @override
  _HomeViewState createState() => _HomeViewState();
}

class _HomeViewState extends State<HomeView> {

  HomeViewModel viewModel;
  @override
  Widget build(BuildContext context) {
    return BaseView<HomeViewModel>(
      onModelReady: (model) {
        model.init();
        model.setContext(context);
        viewModel = model;
      },
      builder: (context, value) => buildScaffold,
      model: HomeViewModel(),
    );
  }

  Scaffold get buildScaffold {
    return Scaffold(
      body: CustomScrollView(
        /* physics: BouncingScrollPhysics(), */
        slivers: <Widget>[
          buildSliverAppBar,
          buildSliverStaggeredGrid,
        ],
      ),
    );
  }

  SliverAppBar get buildSliverAppBar {
    return SliverAppBar(
      floating: true,
      pinned: true,
      snap: false,
      backgroundColor: Colors.white,
      title: buildSearchField,
      actions: <Widget>[buildIconButtonClose, buildanotherbutton],
    );
  }

  TextField get buildSearchField {
    return TextField(
      controller: viewModel.searchController,
      decoration: InputDecoration(hintText: "Search...", border: InputBorder.none),
      onSubmitted: (String keyword) => viewModel.loadImages(keyword),
    );
  }

  IconButton get buildIconButtonClose {
    return IconButton(
      onPressed: () => viewModel.resetImages(),
      icon: Icon(Icons.close, color: Colors.black),
    );
  }

  IconButton get buildanotherbutton {
    return IconButton(
      onPressed: () {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => Passaword()),
        );
      },
      icon: Icon(Icons.ac_unit, color: Colors.black),
    );
  }

  Widget get buildSliverStaggeredGrid {
    return SliverPadding(
      padding: EdgeInsets.all(0),
      sliver: Observer(builder: (_) {
        return viewModel.loadingImages
            ? SliverToBoxAdapter(
                child: Center(child: CircularProgressIndicator()))
            : SliverStaggeredGrid.countBuilder(
                crossAxisCount: 2,
                itemCount: viewModel.images.length,
                itemBuilder: (BuildContext context, int index) =>
                    buildImageTile(index),
                crossAxisSpacing: 5,
                mainAxisSpacing: 10,
                staggeredTileBuilder: (int index) {
                  return buildStaggeredTile(viewModel.images[index]);
                },
              );
      }),
    );
  }

  StaggeredTile buildStaggeredTile(UnsplashImage image) {
    double aspectRatio = image.height / image.width;
    double columnWidth = MediaQuery.of(context).size.width / 2;
    return StaggeredTile.extent(1, aspectRatio * columnWidth);
  }

  Widget buildImageTile(int index) {
    return FutureBuilder(
      future: viewModel.loadImage(index),
      builder: (context, snapshot) => ImageTileWidget(image: snapshot.data),
    );
  }
}

If you want my whole code, I can share with you. I thought my file that has builder widget code is enough to solve the problem.
my builder widget here;
  Widget get buildSliverStaggeredGrid {
return SliverPadding(
  padding: EdgeInsets.all(0),
  sliver: Observer(builder: (_) {
    return viewModel.loadingImages
        ? SliverToBoxAdapter(
            child: Center(child: CircularProgressIndicator()))
        : SliverStaggeredGrid.countBuilder(
            crossAxisCount: 2,
            itemCount: viewModel.images.length,
            itemBuilder: (BuildContext context, int index) =>
                buildImageTile(index),
            crossAxisSpacing: 5,
            mainAxisSpacing: 10,
            staggeredTileBuilder: (int index) {
              return buildStaggeredTile(viewModel.images[index]);
            },
          );
  }),
);

}


text:
Q: Add item to array based class property with generic method I have an example class, like:
export class FilterClass {
  searchText = '';
  someFilter: FilterType[] = [];
  otherFiler: OtherFilterType[] = [];

  setSearchText(searchText: string) {
    this.searchText = searchText;
  }
}

Now i'm trying to write a generic method to add new filters to filters arrays defined as this class properties. For now i have something like this:
  addFilter<T, K extends keyof FilterClass>(
    arrayName: K,
    filterToAdd: T
  ) {
    (this[arrayName] as unknown as T[]).push(filterToAdd);
  }

How can I get rid off casting it to unknown?


text:
Q: PreferenceScreen android:paddingTop not working With normal layout file, I can set padding top like this
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="?attr/actionBarSize"

>

However, with preference screen, it renders the padding short of some pixels (the action bar is 168 dp, but the padding appears only 144), any idea how to fix this cross-device way. Thanks.
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
 android:layout_width="match_parent"
 android:layout_height="match_parent"
 android:paddingTop="?attr/actionBarSize">

A: When using PreferenceScreen you don't have access to those xml attributes. But what you can do is add this attribute to it:
android:layout="@layout/header_setting"

Then create a XML layout file called in this example "header_settings" you can change the sizes and padding as normal. But applying the id's to the elements the PreferenceScreen knows where the titles goes or icon.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:padding="0dp"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+android:id/icon"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        android:layout_marginTop="15dp"
        android:layout_marginBottom="15dp"
        android:layout_width="40dp"
        android:layout_height="40dp" />

    <TextView android:id="@+android:id/title"
        android:layout_marginLeft="80dp"
        android:textColor="#000"
        android:layout_marginTop="23dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="18sp"/>
</LinearLayout>

And now here is an example on how the PreferenceScreen should look like:
    <?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout="@layout/pref_screen">

    <PreferenceCategory>
        <PreferenceScreen
            android:icon="@drawable/setting_star"
            android:layout="@layout/header_setting"
            android:title="Upgrade to Pro!">

        </PreferenceScreen>
    </PreferenceCategory>
</PreferenceScreen>

Notice how you only have access to the attributes: title, summary, and icon. The layout attribute lets you customize it to whatever you want to do. In the XML you must keep the id's the same since thats how the PreferenceScreen knows thats were to put the title text or the icon image.
I hope this helps!


text:
Q: how to change complex cypher queries to simple query in neo4j? i want to find the users with max number of friends and min number of friends.
here is my query:
"start n=node:users({query}) match p=n-[?:Friend*]->x
with distinct n,count(distinct x) as  cnt  "
+ "start n=node:users({query}) match p=n-[?:Friend*]->x
with distinct n,count(distinct x) as cnt1, min(cnt) as minnumber "
+ "start n=node:users({query}) match p=n-[?:Friend*]->x
with distinct n,count(distinct x) as friendsNumber, max(cnt1) as
maxnumber, minnumber  "
+ "where  friendsNumber=minnumber or friendsNumber=maxnumber  return n.name,
friendsNumber"

n is user and x is his friends.
but i used three nested query and i think its performance isn't good.is there another way to do this?
thanks.

A: maybe querying two times would be better
START n=node:users({query})
MATCH n-[:Friend]->x
WITH n,count(x) as cnt
RETURN n, cnt order by cnt desc limit 1;

START n=node:users({query})
MATCH n-[:Friend]->x
WITH n,count(x) as cnt
RETURN n, cnt order by cnt asc limit 1;

A: You don't want to use variable length paths here. Also no optional relationships as you are interested in people with friends.
I think running two queries might be most sensible here:
start n=node:users({query})
match p=n-[:Friend]->x
with ID(n),count(distinct x) as  cnt
with max(cnt) as max,min(cnt) as min

start n=node:users({query})
match p=n-[:Friend]->x
with n,count(distinct x) as  cnt
where cnt=max or cnt=min
return n.name

Something like this should also work: http://console.neo4j.org/r/xf3hm0
start n=node(*)
match p=n-[:KNOWS]-x
with n,count(distinct x) as  cnt
with collect([n,cnt]) as data, max(cnt) as max,min(cnt) as min
return extract(pair in
   filter(pair in data
     where tail(pair)=max OR tail(pair)=min) :
   head(pair)) as person


text:
Q: PHP: Better way to replace string value in array with an array? I'm new to PHP so I'm not sure how to optimize this code.
I execute a Python script from PHP and the $output variable returned is an array of arrays.
exec (" /Users/$USER/anaconda/bin/python /Applications/MAMP/cgi-bin/Evaluation1.py",$output)

Each array within the $output array contains one string value separated by commas. So $output is Array ( [0] => 1, 好, 0 [1] => 2, 妈妈, 3), etc.
In each array within the $output array, I use explode on the string value to create an array, and add it to my new $output array called $output2
$output2 = array();
foreach($output as $value){
$myArray = explode(',', $value);
$output2[] = $myArray;
}

Is there a way to just replace/overwrite the string value in the arrays within $output with the new array, instead of adding each item to a new $output2 array?

A: You could use array_walk to do the loop over output. You pass in a callback function that is called for each value by reference so any changes to the passed in value stick to the array.
Test data:
$output = array(
    '1,A,2',
    '2,B,3',
    '3,C,4'
);

PHP >= 5.3.0
array_walk($output, function(&$val){ $val = explode(',', $val); } );

Older PHP
function mySplit(&$val){
    $val = explode(',', $val);
}
array_walk($output, 'mySplit');

Both output:
Array
(
    [0] => Array
        (
            [0] => 1
            [1] => A
            [2] => 2
        )

    [1] => Array
        (
            [0] => 2
            [1] => B
            [2] => 3
        )

    [2] => Array
        (
            [0] => 3
            [1] => C
            [2] => 4
        )

)

A: Some great answers already. Just adding this for completeness.
$ar = array(
    "1,2,3",
    "4,5,6"
);

foreach($ar as $k => $v) {
    $ar[$k] = explode(',', $v);
}

Wold be interesting to see a a performance difference of the different methods although i doubt it would be much.


text:
Q: Is the set of all functions $f:Z_+\rightarrow Z_+$ that are eventually constant countable. another question here to see if I'm on the right track. Here is the problem that I have been proposed.
Determine if the set $H$ of all functions $f:Z_+\rightarrow Z_+$ that are eventually constant is countable.
Here is my solution.
I claim the set $H$ is countable. By definition, we say that $f$ is eventually constant if there is a positive integer $N$ such that $f(n)=c,\textrm{c a constant,}\ \forall\ n\ge N.$ Let $F$ be a set containing some $f:Z_+\rightarrow Z_+.$ Let $$H=\bigcup_{n\in\mathbb{Z_+}}F_n=\{f:Z_+ \rightarrow Z_+ |f\in F_n\ \textrm{for at least one}\ n\in Z_+\}.$$ Since $H$ is an arbitary union of sets, we can define a function $g:Z_+\rightarrow H$, where $g$ is an indexing function of $H$ and $Z_+$ is the index set given. Since $g$ is an indexing function, this implies that $g$ is surjective. By  Theorem 7.1, which states if $H$ is a nonempty set and there is a surjective function $f:Z_+ \rightarrow H$ then $H$ is countable, we have that $H$ is countable as claimed.

A: Alternatively, consider the following:
For a function $f:Z_+\rightarrow Z_+ $ such that $\exists N \in Z_+ : \forall n > N, f(n) = f(N) $
Let $M = min\{ N : \forall n > N, f(n) = f(N) \}$
and $S(f) = \sum_{i=1}^{M} f(i) + M$
Then for any value $k$, there are only finitely many such functions with $S(f) = k$. List all $f$ with $S(f)=1$ then all $f$ with $S(f)=2$ etc.

A: For each such function you have a polynomial p(x) in $\mathbb{Z}[x]$  with nth coefficient given by
$a_n = f(n+1) - f(n)$ and $a_0 = f(1)$.
Clearly f can be recovered from p and this correspondence is injective. So your set is countable.


text:
Q: Magento sites showing blank frontend and backend I have 3 magento sites in a single server:  www.site1.com, demo.site1.com, site2.com.  All 3 magento sites were working fine.
Then, all of a sudden, site1.com's frontend and backend showed blank.  Now demo.site1's frontend is showing blank, and admin panel is working fine.  site2.com is working fine for both frontend and backend.
Why these sites are showing blank in frontend and backend?  We are using amazon server, with only 60% space used.

A: delete maintainance. flag file or rename it.... it's present tin root of the magento site : Service Temporarily Unavailable Magento?


text:
Q: Namespacing routes file provides routing error I am trying to namespace my site into owner / admin, and hitting a routing error. When I try to create a new Financial Report (http://localhost:3000/en/admin/financial_reports/new)
I get
No route matches {:controller=>"financial_reports", :format=>nil}

Here is my routes.rb (shortened)
scope ":locale", locale: /#{I18n.available_locales.join("|")}/ do
 root :to => 'sites#index'
 get "logout" => "sessions#destroy", :as => "logout"
 get "login" => "sessions#new", as: "login"
namespace :admin do
    root :to => "base#index"
    resources :financial_reports do
      collection do
        get :monthly
        get :yearly
      end
    end
  end
namespace :owner do
    root :to => "base#index"
  end
match "*path", to: "sites#not_found" # handles /en/fake/path/whatever
end
root to: redirect("/#{I18n.default_locale}") # handles /
match '*path', to: redirect("/#{I18n.default_locale}/%{path}")
end

Here is my controller
app/controllers/admin/financial_reports_controller.rb
class Admin::FinancialReportsController < BaseController

def index
  @financial_reports = FinancialReport.all
end
def new
  @financial_report = FinancialReport.new
end
def create
  @financial_report = FinancialReport.new(params[:financial_report])
    if @financial_report.save
      flash[:notice] = 'Financial Report Uploaded Successfully'
      redirect_to root_url
    else
      flash[:alert] = "Financial Report not uploaded successfully"
      render "index"
    end
  end
  def yearly
    @financial_reports = FinancialReport.yearly
  end
  def monthly
    @financial_reports = FinancialReport.monthly
  end
end
and my view
app/views/admin/financial_reports/new.html.erb
<%= form_for(@financial_report) do |f| %>

  <%= f.label(:report_type) %>

  <%= f.radio_button :report_type, "Monthly" %> Monthly |
  <%= f.radio_button :report_type, "Yearly" %> Yearly

  <%= f.file_field :file %>

  <%= f.submit "Upload Monthly Record" %>

<% end %>

Any idea why i'm getting this error? Thanks

A: <%= form_for[:admin, @financial_report] do |f| %>
........................
.............
........

http://guides.rubyonrails.org/routing.html
Rails Namespace vs. Nested Resource


text:
Q: Why is /System/Library/User Template protected? Why can't users read /System/Library/User Template?
Is there anything in there that is sensitive and should be protected against reading?
If /System/Library/User Template were not protected against reading, it'd be useful to see how a freshly created user home looks like and to restore parts of it in your own home.

A: /System/Library/User Template is protected not only by its permissions, but also because of System Integrity Protection as it's under /System
A common troubleshooting method used by system administrators is to create a new user account and see if whatever problem the user is happening is also happening there.
If, for example, a malicious Program were to infect the computer it could use the user template to perform a variety of things on all new users that are created.
It's permissions are not really meant to prevent anything sensitive from leaving, but rather prevent anything malicious from entering.


text:
Q: js minesweeper board and row pushing Trying my hands on a beginner minesweeper project and have a question on nested loops. I understand the basic when its with numbers. However, adding arrays and objects into a nested loop iteration is a bit tricky for mind and need some clarity (understanding the logic better).
For the below code, does the "const row = []" reset back to an empty array after every time the inner loop finishes pushing the "tile" variable into "row"? I am assuming it does since X will go to "1", which it'll reset the loop again?
Declaring boardSize as 2, I got an output of:
board First Iteration: [[{0,0}, {0,1}]]
board Second Iteration: [[{0,0}, {0,1}],[{1,0},{1,1}]]
function createBoard(boardSize, numberOfMines){
    // Start of board
    const board = []

    for(let x=0; x < boardSize; x++){
        //Each row is 'x', top to bottom
        const row = []
        for(let y=0; y < boardSize; y++){
        //Each column is 'y', left to right

            const tile = {
                x,
                y
            }

             //boardSize = 2, 1) row = [{0,0}, {0,1}] 2) row = []

            row.push(tile);

        }
        //boardSize = 2, 1) board = [[{0,0}, {0,1}]] 2) [[{0,0}, {0,1}], [{1,0},{1,1}]]
        board.push(row)
        console.log(row)
    }

    return board;
}

createBoard(2);

A: Yes you are correct, const row is declared in a Scope, which is terminated after the iteration is finished, each iteration will have it's own row variable. Generally a new scope is created if the code is surrounded by Curly Braces {} such as If statements, Functions, and Loops, though there are a few extra cases.
The Lowest Scope will override scopes Above it, and variables Defined within a scope are only accessible to that scope and other scopes within it.
let x = 5
let y = 4
if (true) {
  let x = 3 // re-define x in Inner scope
  y = 2 // outer scope is accessible to child scopes
  let z = 1
  console.log(x) // 3
  console.log(y) // 2
  console.log(z) // 1
}
console.log(x) // 5 - since the other scope defined its own x, this remains unchanged
console.log(y) // 2 - Value was changed in inner scope
console.log(z) // undefined - does not exist in this scope.

This is generally bad naming practice though.

A: @Ethan's answer is good, and lexical scope is what your question is about.
I just wanted to share some one-liner options to construct a 2-D array of any length with coordinated-pairs (that seems to be what your function does).
This one uses keys as a kind of range function, and map over it:
(r => r.map(x => r.map(y => ({ x, y }))))([...Array(2).keys()])

// or, if board is not square:
[...Array(2).keys()].map(x => [...Array(3).keys()].map(y => ({ x, y })))

This one uses the function Array.from as a sequence generator, and has a smaller memory footprint:
(r => Array.from(r, (_, x) => Array.from(r, (_, y) => ({ x, y }))))({ length: 2 })


text:
Q: Qt Release application with PSQL database - error on loading driver With QtCreator (for version 57) I created simple application that connects to DB and waits for notifications. There isn't realy much code for it and all of it works on LINUX:
MyDataBase = new QSqlDatabase(QSqlDatabase::addDatabase("QPSQL", "Main"));

Unfortunetly after transitioning from Linux to Windows (on which app will by mainy used) I encounteredd some issues. As usuall, missign dlls, but those were quick fast (copy-paste given .dll). Now I can't run this still on Windows, because it refuses to connect to db. With system's variable I managed to find more. Now even when I see error I can't even grasp what else could I do to make it work:
Found metadata in lib C:/_Qt/5.7/mingw53_32/plugins/sqldrivers/qsqlpsqld.dll, metadata=
{
    "IID": "org.qt-project.Qt.QSqlDriverFactoryInterface",
    "MetaData": {
        "Keys": [
            "QPSQL7",
            "QPSQL"
        ]
    },
    "className": "QPSQLDriverPlugin",
    "debug": true,
    "version": 329472
}

"The plugin 'C:/_Qt/5.7/mingw53_32/plugins/sqldrivers/qsqlpsqld.dll' uses incompatible Qt library. (Cannot mix debug and release libraries.)"
               not a plugin

QFactoryLoader::QFactoryLoader() checking directory path "D:/QT_Notifi/build-Notifier-Desktop_Qt_5_7_0_MinGW_32bit-Release/release/sqldrivers" ...
loaded library "C:/_Qt/5.7/mingw53_32/plugins/sqldrivers/qsqlpsql.dll"

QLibraryPrivate::loadPlugin failed on "C:/_Qt/5.7/mingw53_32/plugins/sqldrivers/qsqlpsql.dll" : "Cannot load library C:\\_Qt\\5.7\\mingw53_32\\plugins\\sqldrivers\\qsqlpsql.dll: %1 is not correct application of Win32."

QSqlDatabase: QPSQL driver not loaded

QSqlDatabase: available drivers: QSQLITE QMYSQL QMYSQL3 QODBC QODBC3 QPSQL QPSQL7


text:
Q: MVC post not returning the proper ViewResult In the POST endpoint for my site's Contact page, which sends an email to the site owner based on user input, I am returning a ViewResult of the same view, but with a newly initialized (empty) view model.
My goal for the client is, upon receiving the POST response, give the user the same page, but with all the form fields emptied. Rather than this taking place, however, the user ends up on the same page with all of the same form information still filled out. The email is sent successfully, and no errors are thrown.
Any ideas?
Here are my GET and POST endpoints:
[HttpGet]
public ViewResult contact()
{
    return View(new ContactUsViewModel());
}

[HttpPost]
public async Task<ViewResult> contact(ContactUsViewModel inputModel)
{
    try
    {
        if (ModelState.IsValid)
        {
            string body =
                "
" +
                "
Email from {0} ({1})
" +
                "
Date: {2}
" +
                "
Phone: {3}
" +
                "
Message:

{4}
" +
                "
";
            string to = ConfigurationManager.AppSettings["ContactUsEmailAddress"];
            MailMessage message = new MailMessage();
            message.To.Add(new MailAddress(to));
            message.Subject = "Message from " + inputModel.Name;
            message.Body = String.Format(body, new string[]
                {
                    inputModel.Name, inputModel.Email, DateTime.Now.ToLongDateString(), inputModel.Phone, inputModel.UserMessage
                }
            );
            message.IsBodyHtml = true;

            using (var smtp = new SmtpClient())
            {
                await smtp.SendMailAsync(message);
                // the "true" parameter in the constructor just sets a "Message sent"
                // confirmation message in the view model that is displayed on the view
                // via Razor.
                return View(new ContactUsViewModel(true));
            }
        }
        else
        {
            return View(inputModel);
        }
    }
    catch (Exception ex)
    {
        string ourEmailAddress = ConfigurationManager.AppSettings["ContactUsEmailAddress"];
        inputModel.PublicErrorMessage = "There was a problem sending your message. Please send an email directly to " +
            "" + ourEmailAddress + " so we can hear from you :)";
        inputModel.InternalErrorMessage = ex.Message;
        return View(inputModel);
    }
}

In case this is relevant, here is my ContactUsViewModel as well:
public class ContactUsViewModel : BaseViewModel
{
    public ContactUsViewModel() { }
    public ContactUsViewModel(bool messageSent)
    {
        this.MessageSentConfirmation = "Your message has been sent. We will get back to you shortly!";
    }

    [Required(ErrorMessage = "Please include your name.")]
    public string Name { get; set; }

    [Required(ErrorMessage = "Please enter a valid email address.")]
    [EmailAddress(ErrorMessage = "Please enter a valid email address.")]
    public string Email { get; set; }

    [Phone(ErrorMessage = "Please enter a valid phone number.")]
    public string Phone { get; set; }

    [Required(ErrorMessage = "Please enter a message.")]
    public string UserMessage { get; set; }

    public string MessageSentConfirmation { get; private set; }
}

EDIT: I know that the Post-Redirect-Get design pattern would technically circumvent this issue, but it doesn't really resolve the technical limitation of not being able to return the same view with an empty view model. For that reason, I do not consider implementing PRG the solution.

A: This is @StephenMuecke 's solution from the comments section. Executing ModelState.Clear() in my controller method before my return statement solves the issue.


text:
Q: How can we know that |N is really the intersection of inductive sets? e := element of ;    fa := for all ; : := is valid ; P(X) := Powerset of X
An inductive set M is a subset of |R with the properties that
i)  1 e M
ii) fa x e M : x+1 e M
As the intersection |N must have all elements that the other subsets have. Because of the recursive Definition we know that
fa M e {x e P(|R) such that x is inductive} : 1 e M => 1+1 e M => ....
But I don't understand why there can be no inductive set Z which is also a real subset of |N, with other words why is |N the smallest inductive set? How can you formally proof that?

A: This is where proof by induction comes in! Proof by induction is the application of the induction axiom, which states: $$\mbox{$P(0)$ and ($P(n)\rightarrow P(n+1)$ for every $n\in\mathbb{N}$)$\implies$ $P(n)$ for every $n\in\mathbb{N}$}$$ for every property $P$.
Suppose $Z\subseteq\mathbb{R}$ is any inductive set, and consider the property $P(x)$ = "$x$ is an element of $Z$."

*

*Clearly we have $P(0)$ and $P(x)\rightarrow P(x+1)$ for all $x$; this is just because $Z$ is inductive.

*But this means $\mathbb{N}\subseteq Z$: if $P(0)$ holds, and $P(n)\rightarrow P(n+1)$ for ever natural number $n$, then - by the induction axiom - $P(n)$ holds for every natural number $n$.

This may feel a bit unsatisfying: where does the assumption that $\mathbb{N}$ satisfies the induction axiom come from? Well, nothing gets proved in a vacuum: we need to start with some axioms about $\mathbb{N}$ and $\mathbb{R}$ in order to be able to conclude anything, and the induction axiom - or one of its many variants - is a crucial assumption.
In fact, the induction axiom is equivalent to $\mathbb{N}$ being the smallest inductive set! This may feel a bit more slippery at first, but it's really no more complicated mathematically:

*

*Suppose we have a property $P$ such that $P(0)$ holds and, for every $n\in\mathbb{N}$, we have $P(n)\rightarrow P(n+1)$; we want to show that $P(n)$ holds in fact for every $n\in\mathbb{N}$, from the assumption that $\mathbb{N}$ is in fact the smallest inductive set.

*To do this, let $Z=\{n\in\mathbb{N}: P(n)\}$. By assumption on $P$, we know that $Z$ is an inductive set; since we're assuming that $\mathbb{N}$ is the intersection of all inductive sets, this means $\mathbb{N}\subseteq Z$.

*But that means that for every $n\in\mathbb{N}$, $P(n)$ holds.

*So we've just proved the induction axiom from the hypothesis "$\mathbb{N}$ is the smallest inductive set!"
This sort of examination of the relationship between axiom and theorem occurs throughout mathematics. Much of abstract algebra consists of understanding precisely which basic algebraic properties of the reals/naturals/etc. are necessary to get particular complicated behavior (in the interest of showing that these behaviors hold in more general situations), and it is a fundamental aspect of mathematical logic (especially reverse mathematics, which is worth mentioning if only for the really cool name).


text:
Q: servicestack.redis c# out of memory When using PooledClientManager in ServiceStack.Redis in C#, getting  the following error
Insufficent memory within specified address space range to continue the execution of the program
There is more than 8gb of ram, so i feel there is enough memory space availble in the system.
What might be the causes and how to resolve this issue.
Thanks in advance.


text:
Q: Automated Account Generation Notification in AWS I have a Master account with multiple sub-accounts in AWS. I want to get a notification whenever a new sub-account is created. How can I implement this, please?

A: You can create a trail in CloudTrail, forward the logs to CloudWatch logs and create alarm for "CreateAccount" event. More details and sample filters are here:
https://docs.aws.amazon.com/organizations/latest/userguide/orgs_monitoring.html
http://docs.amazonaws.cn/en_us/awscloudtrail/latest/userguide/cloudwatch-alarms-for-cloudtrail.html


text:
Q: Game Maker Studio 2 LOCAL multiplayer I want to make a simple multiplayer game with Game Maker Studio 2 for mobile platforms, but it should work locally (via wi-fi or bluetooth).
For e.g. this is a list of existing games and my game will be classified as (Bluetooth | WIFI Direct | Online).
I have some experience in programming and GML should not be a problem for me.
But I want to know for sure whether it is possible to implement Wi-Fi Direct and bluetooth communication?
Required answer those who have already done it. Any plug-ins required for this?
I do not want to reinvent the wheel and modify some libraries or broken code.  I just need a 100% working solution.
Why Game Maker Studio 2? Because I want to make a game with my friend who doesn't have any programming skills. So, we need some game editor like Game Maker Studio 2 despite the fact that I have programming experience. And now my task - is to solve the problem with local multiplayer before we start to make a game. Maybe there are other editors that fit these requirements?

A: Gamemaker has some built-in functions to make a local multiplayer (I assume it is what you mean by "WiFi"). if you are familiar with UDP/TCP, it's a plus. They can be found here :
https://docs.yoyogames.com/source/dadiospice/002_reference/networking/index.html
I personally used them for a local multiplayer and it worked fine.
For the bluetooth, the devs are working on some functions, but I believe they didn't release them yet.
If you want to make a global multiplayer, you have to face a few tehnical issues (port forwarding, global matchmaking, etc.) I recommand GMnet, that comes in two flavors :

*

*GMnet Punch if you simply want to communicate through a NAT with your own synchronisation strategy.

*GMnet Engine if you don't want to worry about the details and let them do all the work for you.
The official website : https://gmnet-engine.org/engine/
Keep im mind that for a global matchmaking, you will probably need some kind of relay server, so that players can find the games hosted by other players. It is not that hard and GMnet comes with a java server program for this purpose, but it needs to be hosted on a server with direct internet access (no NAT).
Hope it was helpful !


text:
Q: Finding the right algorithm for undirected graph We are given an undirected graph. There is a source and a sink and they are not connected directly in all possible cases. I want to find the minimum number of vertices to be removed(not the source or sink) that disconnects the source and the sink.
Is there any specific algorithm for this problem. Links would be helpful.

A: Maximum Flow Minimum Cut Theorem
It use the minimum cost to separate the graph to two parts, the source node in the first part, and sink in the second.
To set all the weight equal to 1 of all the edges. You can learn this theorem in the wiki


text:
Q: Como alterar form conforme cookies Estou trabalhando num site de apostas, gostaria de saber como posso fazer para quando a pessoa aposta, mudar a visualização daquela aposta (mostrar como já feita a aposta e dar o link caso queira editar). Lembrando que tem que ser conforme o login da pessoa, e as apostas estão num while, então tem que saber diferenciar a aposta que já foi feita da que não foi feita.
Espero ter sido Claro, senão me peçam para explicar melhor caso não tenha entendido.


text:
Q: What does "induce a topology" mean in this specific problem? A metric $d'$ is called equivalent to a metric $d$ if there are constants $c_0, c_1 > 0 $ sucht that
$$
c_0 d(x,y) \leq d'(x,y) \leq c_1 d(x,y)
$$
for all $x,y \in X$. Show that equivalent metrics induce the same topology on $X$
So I understand that if I have to equivalent metrics I shall show that the induce the same topology. But what does it mean for a metric to induce a topology in this problem?

A: Given a metric $d$ on a set $X$, the topology on $X$ induced by $d$ is the topology generated by open balls defined using $d$.  That is, a subset $U\subseteq X$ is open in this topology iff for each $x\in U$ there exists $r>0$ such that $\{y\in X:d(x,y)<r\}\subseteq U$.

A: In a metric space $X$ with a metric $d$, open balls of the form
$$B_\epsilon(y) = \{x \in X : d(x,y) < \epsilon\}$$
are defined to be open sets. The induced topology is the collection of all sets generated by these open balls through unions, complements, and finite intersections.

A: The topology induced by the metric is the topology with the set of balls (with respect to the metric) as a basis.
When you see an action verb in mathematics it must have some translation to an existential statement or definition because nothing "happens" in ZF or ZFC.


text:
Q: Getting crash when I am trying to fetch the data from SQlite table When I try to fetch the data from SQlite table it is getting crashed and prints the details as below in console. Can any one tell how to resolve these kind of crashes.
thread #11: tid = 0xa162, 0x0162b03d libsqlite3.dylib`sqlite3VdbeHalt + 3693, queue = 'com.org.test, stop reason = EXC_BAD_ACCESS (code=2, address=0x32)
    frame #0: 0x0162b03d libsqlite3.dylib`sqlite3VdbeHalt + 3693
    frame #1: 0x01626e49 libsqlite3.dylib`sqlite3VdbeExec + 46521
    frame #2: 0x01596be1 libsqlite3


text:
Q: After select dropdownlist value retrieve data from database and show in textbox in php I am trying that to get the price of a product after select product from dropdown list in respected textbox. So please help me.!
So when product select from dropdown its price should be display in resp textbox. so how to display that price in textbox..........
my code is below:-
<?php include_once("head.php"); ?>

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

<form action="process.php" class="register" method="POST">

 Bill Generation Form

    <fieldset class="row1">
        <legend>Customer Information</legend>

            Customer Name *

            <?php
            include_once("db.php");
            $data = mysql_query("select * from customer");
            while ($row = mysql_fetch_array($data)) {
                $id = $row['id'];
                $options .= "<option value=$id>" . $row['name'] . "</option>";
            }
            $menu = "<select name='cust_name' id='cust_name' class='selct_list'         onchange=showUser(this.value);demo(this.value)>" . $options . "</select>";
            echo $menu;
            ?>

Person info will be listed here.

    </fieldset>
    <legend>Products Details</legend>

            <input type="checkbox" required="required" name="chk[]" checked="checked"/>
            Product Name

                <?php
                include_once("db.php");
                $datas = mysql_query("select * from inventory");
                $options .= "<option value=''> select product </option>";
                while ($rows = mysql_fetch_array($datas)) {
                    $ids = $rows['id'];
                    $options .= "<option value= $ids>" . $rows['item'] . "</option>";
                }
                $menus = "<select name='BX_NAME[]' id='BX_NAME[]' class='selct_list' onchange=showProduct(this.value)>" . $options . "</select>";
                echo $menus;

                ?>

                Qty
                <input type="text" required="required" class="small" name="BX_age[]" value="<?php ?>">

            Tax %
                <input type="text" id="BX_gender" required="required" class="small" name="BX_gender[]">

            Unite Price
                <input type="text" id="BX_birth" required="required" name="BX_birth[]">

        <input type="button" value="Add New Row" onClick="addRow('dataTable')" class="btn btn-success btn-sm btn-line"/>

        <input type="button" value="Remove Selected Row" onClick="deleteRow('dataTable')"
               class="btn btn-warning btn-sm btn-line"/>

(All acions apply only to entries with check marked check boxes only.)

    <legend>Invoice Preference</legend>

Select Invoice Preference
        <select id="invoice" name="invoice" required="required">
            <option>....</option>
            <option>Invoice</option>
            <option>Quate</option>
            <option>Receipt</option>
        </select> </legend>

Person info will be listed here.

    <input class="submit" type="submit" value="Confirm »"/>

</form>

A: First of all, you have to give the value attribute to the <option> tag, then you have to call a javascript function onchange event of dropdown.
2) At that javascript function, put the code
dropdown options value, which is selected, and then use javascript code document.getElementById('your field id wher you want to show your value').value = your dropdownvalue;

A: I didn't read your code but i think what you are asking for is:
    if ($("#SELECT").val() === "ProductX") {
    $("#TEXTINPUT").val(PRICE);
}

Of course wrap it into an change Function like
$('#SELECT').change(function() {
}
I recomend using JQuery else just use the js commands
Cheers


text:
Q: Can't enter proxy credentials in Apple iTunes; all apps deleted I have been using iTunes to automatically sync apps on my iPod Touch 5th gen.
My computer is behind a proxy which I have no access to directly, but I have credentials. So I can't get anyone to allow iTunes through, unfortunately. But none of this really matters because iTunes would automatically ask me for my credentials for the proxy and I could connect to the Apple servers with no problem.
For some reason, iTunes used to ask me to authorize my computer all the time. I would just log in and authorize it while the sync was occurring. Yesterday, I wasn't asked for proxy authentication creds and when it asked me to authorize my computer, I couldn't because iTunes couldn't communicate with the Apple servers.
This resulted in all my apps being deleted. I want to restore them, but now I don't know how.
The iTunes version I have is 11.0.4 on Windows 7 64bit. I recently upgraded from the previous version so I believe this version introduced the bug.
My exact question is: Does anyone know how to manually enter the proxy credentials into iTunes 11.0.4? If not, does anyone know how to restore my apps to my iPod from a previous backup without the use of an internet connection?

A: Found the solution. Well, really a workaround. Seems my proxy was blocking connections to iTunes. I worked around this by using Fiddler2 (network software) which reroutes the web proxy through itself, then out to the world.
So whatever problem iTunes was running into, it didn't have a problem going through localhost then out to the world. Good for my purposes at least.


text:
Q: Adverb vs preposition
*

*He is going up the mountain road.

*He is going up along the mountain road.

In 1, up is working as a preposition, while along is the preposition in the 2.
Do the both carry same meaning?
Thank you.

A: Prepositions are always used with verbs and adding a preposition to the verb may change the sentence meaning drastically, specially if the verb is a movement verb (go, walk, run...)
In the first sentence, you have the preposition up with the verb go, which gives the sentence a meaning of someone moving to the top of the mountain road.
In the second sentence, you have two prepositions modifying the same verb, you have up and along, which gives the reader the impression that someone is moving to the top of the mountain road and while moving along it.
Other examples:

*

*John jumped into the portal

*John jumped down into the portal
In the examples above, clearly down is not necessary since the main idea is going into the portal. However, it highlits the fact that the portal was somewhere under the ground, which requires John to jump downwards in order to be in it. Now, suppose that the portal is in front of John, then he can't jump down into it, instead he needs to jump forward into it.

A: Both sentences carry the same meaning.


text:
Q: Trying to put an array into 'post__in' => array() query not working Slight problem, I have the following code:
$purchaseprodid = $_GET['ids'];
$args = array(
                  'post_type' => 'prizes',
                  'post__in' => array($purchaseprodid)
                  );
                query_posts($args);

                while (have_posts()) : the_post();

I am getting comma seperated numbers for id's in a url, and they dont seem to be querying the posts. If I manually type the id's in they work no problem, but just not when using a variable $purchaseprodid.
Any ideas?
Thanks!

A: You need to explode the string you obtain from $_GET['ids'] into an array, at the moment you a parsing a to string post__in rather than an array of IDs.
Try
$purchaseprodid = isset($_GET['ids']) ? explode(',',$_GET['ids']) : array();

However, you can sometimes run into difficulties using $_GET with WordPress, it's better to use the API provided and register your variable, see this question.

A: You can instead use the standard WordPress function wp_parse_id_list like this:
$purchaseprodid = isset( $_GET['ids'] ) ? wp_parse_id_list( $_GET['ids'] ) : array();

that checks that the input data is not already an array, clears duplicates and converts the type of each array element to integer.
More info at:
https://developer.wordpress.org/reference/functions/wp_parse_id_list/


text:
Q: How to convert $\ kWh/m^2 $ to $\ Joule/kg$ How to convert $$\ kWh/m^2$$ to $$\  Joule/kg$$
I want to compare the radiation produced by the sun over a location (where I live in, measured in $\ kWh/m^2$),  to the radiation a person gets from a CT scan in the unit sieverts (Sv, whose equivalence  is $\ Joule/kg $).
Thus you may want to know what produces more radiation:
The Global Horizontal Sun Radiation over Vilnius versus the radiation produced by a regular nose CT scan (which is in Sieverts)
For instance, you may get the solar radiation over a location data from
https://globalsolaratlas.info/?c=-28.56667,-70.75,3&s=-28.56667,-70.75
But I don't know how to compare both magnitudes
I need it for a research I am working on.
Thank you.

A: These two units don't match up.
You have a density of energy in $kWh = \frac{1000}{3600} Joule$ per square meter.
And you have a mass density of energy in Joule.
So you can't convert from one to another unless you had more information.
Also, this is probably more appropriated in the physics SE.


text:
Q: Создание nav-bar бутстрап Пытаюсь создать горизонтальный nav-bar вот код :

    Лого

Главная

Первая

Вторая

результат вот такой http://i.imgur.com/fBpqkq2.png

A: Исправьте

на

Также в Вашем примере отсуствует один закрывающий
.
Я в таких случаях беру с сайта пример из доков. И просто по одному убираю то, что мне не нужно... (http://getbootstrap.com/components/#navbar)


text:
Q: How can I traverse and extract data using Haskell xml cursors? Using the Haskell xml library by Galois Inc., I want to traverse XML using the cursors interface, without using monads.
And I want to check the tag name, tag attributes and text data enclosed by the tag.
How can I do this? Any examples?
To move the cursor, I could use nextDF to do depth-first left-to-right traversal. After moving the Cursor, I can use toTree to get Content, but from there, how do I convert to Element and then from getTag, use the contents within Tag to get tag name, tag attributes and text data enclosed by the tag?
The example should preferably include the opening of the file and then using the cursors interface.


text:
Q: Extract highest point in raster and convert to point vector I have a raster DEM and I want to extract from it the highest point found in every polygon of a polygon shapefile.
The result that I would like to obtain would be a point shapefile with 2 collumns: polygon ID and height.
I'm working in QGIS.
I tried SAGA raster statistics to polygon, but the result is just a polygon with the height value. I am trying to extract the point to a point vector layer.

A: You can use saga - raster values to points. Then use "join attributes by location" to join the points to the polygon layer. You can then select the max value from the attribute table of the joined points/polygon layer using "statistics by categories"

A: This is basically the same as the one provided by @firefly-orange already.

*

*Start SAGA Raster values to points tool. Select your raster layer as Grids.

*Select your polygon layer in the Polygon[optional] field and make sure to click on Iterate over this layer button. Then Run.

*You will obtain as many layers as your polygons. It will appear in reverse order on the layers panel, all named "Shapes". So you would probably want to rename these point layers to represent each of your polygon.

*Open any attribute table of newly created Shapes layer, and click twice on the header of your value column (the field name is automatically taken from your raster layer). The row with highest value comes on top. By hitting [CTRL+J] keys or Zoom map to the selected rows button, it will take you to the highest point.

A: Original question was certainly using QGIS 2.x so many algorithms have been added since. I don't know if this method could be used pre QGIS 3.x but it's certainly relevant now anyway.
I needed to do something similar where I wanted to locate more precise high points with the help of lidar data. My original high points were contained in a point layer that was based off much less precise raster data so what I turned out doing achieves what you were trying to do yourself.
There was no practical way to do it generating one point for each pixel as the spatial resolution of 1m would have been way too heavy to deal with. An alternate method to the other two answers is to isolate the pixel with highest value, turn everything else into NODATA, and only then generate points from the raster. The null ones are ignored.
I built a model (in QGIS 3.4) where I could iterate over my point layer but it could be done with a polygon layer too. Here's the sequence (if you take a look at the model below, you'd start from the Bounding boxes tool which you can replace with your polygon layer):

*

*Clip raster by mask layer

*

*Input: your raster layer

*Mask:  your polygon layer

*Zonal statistics

*

*Raster layer: the result from step 1

*Vector layer zones: your polygon layer

*Statistics to calculate: Max

*Reclassify by layer

*

*Raster layer: result from step 1

*Layer containing class breaks: result from step 2

*all value fields: _max (if you left the default field prefix in step 2)

*Use no data when no range matches value: Yes

*Raster pixels to points

*

*Raster layer: result from step 3

From this moment the output should be vector points at maximum pixel value from the original raster contained in your polygons. There are a few unneeded steps for you as I created a buffer around my original points to get polygons in which to find maximum values, and at the end I joined attributes from my bounding boxes so my output points would have the same attributes as my input points.
Of course, for this to work you have to click the button to iterate over your polygon layer, just like I had to iterate over my points. You'll have as many points layers as you had input polygons, but they can easily be merged into one layer afterwards.

A: Had same issue today: Get highest and lowes Alt from DEM within a polygon. I made a point grid with inbuilt tool "Create Grid", with reasonable X/Y spacing (10m i.e.) and set the extent of the polygon to be sampled. Then clip resulting grid points with polygon, and finally sample the DEM Raster with these points.. Easy as that!


text:
Q: create a secondary y-axis in R I had a question regarding creating secondary y-axis in R. Here is an example dataset
#generate some artifical data

per_cur <- runif(1171, 0.1, 7.62)
obs<-runif(1171,100,1000)

#create a density histogram of per_cur

par(mfrow=c(2,1))
op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)

#add obs with a secondary y-axis

par(new = TRUE)
plot(per_cur,obs, cex=.5, pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

It produces a plot which tells me the distribution of per_cur and also shows my the relationship
between per_cur and obs through the secondary y-axis. However, when I run the following code with the only
difference that I set the limit of primary y-axis using ylim=c(0,0.3) you can see the plot completely changes.
It gives the impression that relationship between the obs and pre_cur is different in both plots (more obs points
    come under the curve in first plot compared to the second plot).
op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE,ylim=c(0,0.3), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)
par(new = TRUE)
plot(per_cur,obs, cex=.5, pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

I wanted to ask is there any way my secondary y-axis also get adjusted as I adjust the primary y-axis limit so that
equal number of obs points are under the curve in both plots. Hope this is clear.

A: This can be accomplished by manipulating the ylim on each plot. For example:
#generate some artifical data

per_cur <- runif(1171, 0.1, 7.62)
obs<-runif(1171,100,1000)

#create a density histogram of per_cur

# use these variables to set the limits on all plots
y1max = max(density(per_cur)$y)
y2max = max(obs)

par(mfrow=c(2,1))
op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, ylim = c(0, y1max), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)

#add obs with a secondary y-axis

par(new = TRUE)
plot(per_cur,obs, cex=.5, ylim = c(0, y2max), pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)

Then you scale each axis by the same factor:
# used to scale the axes
factor <- 2

op <- par(mar = c(5,4,4,4) + 0.5)
hist(per_cur, prob=TRUE, ylim = c(0, y1max * factor), border="white",main=NULL,las=1,cex.axis=0.8,ann = FALSE)
lines(density(per_cur), col="blue",lwd=2)
par(new = TRUE)
plot(per_cur,obs, cex=.5, ylim = c(0, y2max * factor),pch=16, col=adjustcolor("black",alpha=0.2), axes = FALSE, ylab="Density")
axis(4,cex.axis=0.5)


text:
Q: How did the 11th Doctor know that he was going to survive? From the transcript of Doctor Who (2005) S08E01:

CLARA: Hello? Hello?
  DOCTOR 11 [OC]: It's me.
  CLARA: Yes, it's you. Who's this?
  DOCTOR 11 [OC]: It's me, Clara. The Doctor.
  CLARA: What do you mean, the Doctor?
[Trenzalore / City street]
DOCTOR 11: I'm phoning you from Trenzalore.
  CLARA: I don't
  DOCTOR 11: From before I changed. I mean it's all still to happen for me. It's coming. Oh, it's a-coming.

In the next scene (which was from episode The Time of The Doctor), it was shown that Clara was putting back the phone inside TARDIS. At that point, how did The Doctor come to know that he was going to regenerate but not die? Didn't he know that he already used all of his 12 regenerations and he was going to really die?

A: Since the Doctor knew he was going to regenerate in this scene, and he also looked young-looking, I think we can presume the Doctor made this call in between the following two scenes in "The Time of the Doctor":

*

*The scene where a very elderly-looking Eleventh Doctor suddenly realized he had another regeneration and used the regeneration energy to blast the Daleks:

DALEK: The rules of regeneration are known. You have expended all your
  lives.
DOCTOR: Sorry, what did you say? Did you mention the rules? Now,
  listen. Bit of advice. Tell me the truth if you think you know it. Lay
  down the law if you're feeling brave. But, Daleks, never, ever tell me
  the rules!
DALEK : Emergency! Emergency! The Doctor is regenerating! The Doctor
  is regenerating!
DOCTOR: Oh, look at this. Regeneration number thirteen. We're breaking
  some serious science here, boys. I tell you what, it's going to be a
  whopper!
DALEK: Exterminate! Exterminate the Doctor.
DOCTOR: You think you can stop me now, Daleks? If you want my life,
  ha, ha, come and get it!

*The following scene at the end of the episode, where Clara entered the TARDIS and found a young-looking Eleventh Doctor waiting for her, who explained his youthful appearance as a "reset" immediately prior to regeneration:

CLARA: Doctor!
DOCTOR: Hello.
CLARA: You're young again. You're okay. You didn't even change your
  face.
DOCTOR: Ha! It's started. I can't stop it now. This is just the reset.
  A whole new regeneration cycle. Ooo.

Also, you mention that in the phone call in "Deep Breath" we see a shot of Clara replacing the hanging phone on the TARDIS, a shot originally from "The Time of the Doctor"--and this scene did indeed happen between the two scenes I mentioned above, it's at 58:35 on the US blu ray (might be a little different on blu rays from other regions since the US blu ray is slowed down to 24 frames per second, whereas the episode was broadcast at 25 frames per second, a speed US televisions aren't designed to play).

A: He knew because this was after he got his second regeneration cycle, and his 13th regeneration was in it's final phase: the change ("Oh, it's coming"). Even then, he kind of described the regeneration as a death type thing, like his previous incarnation, but not obsessing and trying to avoid it. He wanted to Clara to know that, even though he might not exactly be the man she once knew, he's still and always will be the same caring, kind, witty Doctor, that she, and many others before her knew, and grew to respect and love. So there you go.


text:
Q: Stored procedures and UDF's Oracle vs SQL Server First thanks for any help that is offered. I'm a complete SQL Server newbie, working solely with Oracle and PL/SQL for the last 20 years.
Any relevant documentation I could be pointed too would be great, as my current sources haven't yet supplied answers!
Is the following true: Oracle Function = SQL Server User Defined Function
                       Oracle Procedure = SQL Server SPROC?
My simplified Oracle example:
select student_id
       ,someschema.f_get_accommadation_get(student_id) accommodation
from   students;

Where someschema.someschema.f_get_accommadation_get(student_id) is:
create or replace function someschema.f_get_accommadation_get(p_student_id in number)
return varchar2 is
local_sped number;

begin
  select sped_cd from someschema.student_sped
  into local_sped
  where student_id = p_student_id;

  if local_sped = 1 then return('A')
    elsif local_sped = 2 then return('B')
       else        return('C')
    end if;
  end if;
exception when others then return(null);
end;

Could I recreate the Oracle function as a UDF, converting the begin...exception...end to begin try and begin catch?
If not, what are my other strategies?
Thanks again

A: You are basically right. However, the function will perform like an absolute dog in SQL Server. I'm not sure whether it's any better in Oracle, but I certainly try and avoid scalar functions. For functions in general, you are better off making an inline table function (second example on this page) and then getting the values using CROSS APPLY.
However, in this case, I would almost certainly refactor it to be a LEFT OUTER JOIN with a CASE statement (see here).
That would look something like:
select student_id,
       CASE spec_cd WHEN 1 THEN 'A'
                    WHEN 2 THEN 'B'
                    WHEN 3 THEN 'C'
                    ELSE NULL END as ColumnName
from   students s left outer join
       someschema.student_sped ss
    on ss.student_id = s.student_id


text:
Q: How did the Yeerks help the Gedds survive? The Animorphs Wiki states that

Because they are slow and inefficient, the Gedds formed a symbiotic relationship with the Yeerks, who helped them survive in exchange for being hosts.

How exactly did the Yeerks help the Gedds survive?

A: This may be an exaggeration
The only instance I can find in the books of anyone actually claiming that the Yeerks and the Gedds had a symbiotic relationship came from Prince Seerow, shortly after being informed of the Yeerks' first attack on the Andalites. As the greatest advocate for the Yeerks, Seerow had much to lose from this sudden but inevitable betrayal, and it's reasonable to believe he may have stretched the facts just a little in his desperation to defend the Yeerks and/or his decisions.

<They gave you their word?!> Alloran practically shrieked. <Their word? They're parasites. The Yeerks steal the bodies of other species. What did you expect of them?>
<They have no history of harming intelligent life-forms. The Gedds are barely conscious in their natural state,> Prince Seerow argued. <It's not as if they were stealing the bodies of truly sentient creatures. They and the Gedds are symbiotic. They have ->
Alloran stepped closer to my father. <Listen to me, my prince.> The word "prince" was said with a sneer. <Approximately four hundred Gedds attacked our ground base last night. They overwhelmed the two dozen Andalite warriors on duty there. The two dozen Andalite warriors who had been specifically ordered not to fire on Gedds.>

Hork-Bajir Chronicles, pg 7
Further, there are also indications that the Gedds resisted their infestations to what small extents they could.

When it was my turn, the Gedd's head was thrust beneath the surface of the pool.

Hork-Bajir Chronicles, pg 21

I felt a resistance. A mind within the brain. Stronger than the tired, beaten Gedd. This [Hork-Bajir] was attempting to fight me!

Hork-Bajir Chronicles, pg 33

By the time I infested my first Gedd there was already a huge body of information on how best to subdue the Gedd mind. The same when it was time to move up to Hork-Bajir.

Visser, pg 32
Still, as the Wiki says, it's stated numerous times that the Gedds are barely sentient and physically awkward. While it's possible that they form an approximation of a symbiotic relationship through something like the Yeerks granting them their intelligence, such a situation is never stated outright, and the Gedds seem no more willing to be Controllers than most other races.


text:
Q: UIButton firing selector inconsistantly I have a UIButton linked up in IB correctly(I believe). The button fires inconsistently, every time I reload the view to show updated info, the button works sometimes and sometimes does not.It gives no errors. I can't find a pattern to when it works and when it doesn't, the same code is run every time I open the view and it still works when it wants.   Besides linking it in IB I have also tried to addTarget in ViewDidLoad and remove the IB connection but it still has the same inconsistency,
[_buttonScreen addTarget:self action:@selector(buttonScreenClicked)  forControlEvents:UIControlEventTouchUpInside];

If I add NSLog(@"Clicked"); to buttonScreenClicked I see that the method doesn't always get called, what would cause it to do this, I have made sure that I set:
[_buttonScreen setAlpha:0.1];
[_buttonScreen setHidden:NO];
[_buttonScreen setUserInteractionEnabled:YES];

I have no Image, text, or color in the button, but it still works sometimes.
I'm using AFKPageFlipper on the same view but it still had the same problem before I added AFKPageFlipper, so I don't think its that.
If anyone could point me in any direction to start trouble shooting this problem I would appreciate.
Thanks

A: I just had the same problem and worked it out.  The 5 seconds is the clue.
Somewhere you have a gesture recognizer covering the same space as your button.  More specifically you have a gesture recognizer that is eating your Taps but not your LongPresses.  If you just tap the button the gesture recognizer runs off with your event;  Hold your finger down long enough and the gesture recognizer no longer considers it a tap and the event is passed through to your button.
Instrument your Tap gesture recognizer handlers and the problem should pop out at you.

A: Make sure you don't have any other UIView descendants overlaying the button (like a transparent UIScrollView) as these will intercept the touch events first.
Also make sure that the containing view (the view with the button in) is correctly sized, by default you can place a view outside the bounds of another view and the clipsToBounds is set to false so you will see it but not be able to interact with it.

A: Things to try:
Do you have any other actions on the button?
Do you have any other UIViews which could possibly be accepting the key presses (above or below, or un-shown)
Also, please check that you have only one UIViewController instance for this screen. Other issues may arrise because of that.
What happens if you dont set the alpha level?
Do you release the object properly in the dealloc only ?
Hope this helps


text:
Q: undefined method `full_title' Hartl Rails Tutorial Hi I'm learning from the tutorial of mihaela hartla
I know that was similar topic but i the method still does not work
So, I keep getting the the error:

undefined method `full_title' for #<#<Class:0x005594c0761420>:0x005594c0295270>

error in this line (/sample_app/app/views/layouts/application.html.erb):
<title><%= full_title(yield(:title)) %></title>

Layouts file:
<!DOCTYPE html>
<html>
  <head>
    <title><%= full_title(yield(:title)) %></title>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all',
                                              'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

  <body>
    <%= yield %>
  </body>
</html>>
</html>

application_controller
include ApplicationHelper

class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception
  def hello
    render html: "Hello world!"
  end
end

application_helper
 module ApplicationHelper
  def full_title(page_title = '')
    base_title = 'Ruby On Rails Tutorial'

    if page_title.empty?
      base_title
    else
     "#{base_title} | #{page_title}"
    end
  end
end

A: Did you already check and try this --> undefined method `full_title'
Can you try commenting or removing
#include ApplicationHelper
in your application_controller as I am not sure if it is needed there.
Also, is your
rails -v
match 5.1.2 or the one in the tutorial

A: Doesn't seem to be anything wrong besides the unnecessary inclusion of the ApplicationHelper. Maybe restarting the server?

A: I have checked the repo you shared with us on Facebook group (url)
The problem there was simple - application_helper.rb is empty. In my environment I do not need to include the helper - it works like a charm. Can you please check this and confirm (or update the repo)?


text:
Q: Exceptions and IDispatchMessageInspector I'm using IDispatchMessageInspector to inspect request/response messages in my WCF service and log some data to our logging database. I also have a custom error handler which catches exceptions and transforms them to faults. I'd like to be able to log the exception (if any) in the IDispatchMessageInspector.BeforeSendReply() method but I cannot figure out how to capture exception data. Is there a fault collection of some sort that I should be looking for? I realize I could log the exception in the IErrorHandler.HandleError() method, but I'd like to include the exception details along with the other details that I'm capturing while inspecting the request/response messages. Thanks!

A: Here's something I wrote a while ago about this topic. Basically, an exception will cause a fault message to be sent to the client as a reply


text:
Q: User-Based Collaborative Filtering with sparse matrices Python I'm implementing the Recommender System for a portal with 1 million(a month) unique users and 13000 items and I'm keen to do it great in terms of Big Data.
# --- Start Item Based Recommendations with Sparse --- #
data = pd.read_csv('.../.csv').astype(float)

def cosine_similarities(mat):
    col_normed_mat = pp.normalize(mat.tocsc(), axis=0)
    return col_normed_mat.T * col_normed_mat

data_germany = data.drop('user', 1)
data = csc_matrix(data)
data_germany = csr_matrix(data_germany)
csc = cosine_similarities(data_germany)
csc = csc.tocoo(copy=False)

csc.data
Out[74]:
array([ 0.02988072,  0.01698824,  0.0174342 , ...,  0.03207501,
        0.09016696,  0.06804138])

Having Cosine Distance in my sparse matrix I can use all my items and get by row/col the data to advise it. That's simple one.
The question is how to do and implement User-Based CF with Sparse Matrices. SciPy Matrices are so bad in terms of diversity of existing methods. The methods doesn't allow me fully write code for doing User-Based CF with Sparse Matrices. I want to get the same affect for my CF but with Sparse Matrix.
# --- Start User Based Recommendations with **no Sparse --- #**
# Helper function to get similarity scores
def getScore(history, similarities):
   return sum(history*similarities)/sum(similarities)

# Create a place holder matrix for similarities, and fill in the user name column
data_sims = pd.DataFrame(index=data.index,columns=data.columns)
data_sims.ix[:,:1] = data.ix[:,:1]

#Loop through all rows, skip the user column, and fill with similarity scores
for i in range(0,len(data_sims.index)):
    for j in range(1,len(data_sims.columns)):
        user = data_sims.index[i]
        product = data_sims.columns[j]

        if data.ix[i][j] == 1:
            data_sims.ix[i][j] = 0
        else:
            product_top_names = data_neighbours.ix[product][1:10]
            product_top_sims = data_ibs.ix[product].order(ascending=False)[1:10]
            user_purchases = data_germany.ix[user,product_top_names]

            data_sims.ix[i][j] = getScore(user_purchases,product_top_sims)

# Get the top songs
data_recommend = pd.DataFrame(index=data_sims.index, columns=['user','1','2','3','4','5','6'])
data_recommend.ix[0:,0] = data_sims.ix[:,0]

# Instead of top song scores, we want to see names
for i in range(0,len(data_sims.index)):
    data_recommend.ix[i,1:] = data_sims.ix[i,:].order(ascending=False).ix[1:7,].index.transpose()

# Print a sample
print data_recommend.ix[:10,:4]


text:
Q: Regex to strip initial and terminating strings and replace strings I have a string that may begin with one or more %0D%0A, and also may end with one or more %0D%0A.  I want to strip any of those %0D%0A sequences from the string using regex.
To complicate it a little, the ASCII text between any possible initial or terminating %0D%0A sequences may also contain one or more %0D%0A strings, which need to be converted to ,%20 (comma space).
I would prefer to do this with a single regex, but if it needs to be two regex's that is acceptable.
As an example, for any of these strings:
x=%0D%0A%0D%0A%0D%0Ahello, world%0D%0A%0D%0A
x=%0D%0Ahello, world%0D%0A%0D%0A
x=hello, world%0D%0A
x=hello, world%0D%0A%0D%0A
x=%0D%0A%0D%0Ahello, world
x=%0D%0A%0D%0Ahello%0D%0Aworld%0D%0A
x=%0D%0Ahello%0D%0Aworld%0D%0A%0D%0A
x=hello%0D%0Aworld%0D%0A%0D%0A%0D%0A%0D%0A

I would like the output to be:
x=hello, world
This is what I have written so far to strip the initial and terminating %0D%0A sequences, but it does not work:
x=((?:%0D%0A)+(.*)|(.*)(?:%0D%0A)+|(?:%0D%0A)+(.*?)(?:%0D%0A)+)
Note that the x= is just arbitrary text that needs to be preserved.
Update:
My apologies; I did not want to overwhelm everyone with too many details, but the lack of them is resulting in helpful answers that won't work.  I'm sorry.
What I'm doing is using a javascript browser extension that replaces one string with another.  All I can provide to the extension is a regex pattern to match, and a replacement output string (which uses $1, $2, $3, etc. as matching sequences).
For example, if it receives a string of
helloworld
and I tell it to replace regex hello.* with good$1,
it will output goodworld.

A: Step 1 : Remove starting and ending occurences
(^(%0D%0A)+)|((%0D%0A)+$)
In javascript you would write x = x.replace(/(^(%0D%0A)+)|((%0D%0A)+)$/g, '');
Step 2 : Replace intermediate occurences of the group by comma
^.+(%0D%0A)+.+$

A: You would need two replace operations:

*

*trim the string on both sides, i.e. replace ^(?:%0D%0A)+|(?:%0D%0A)+$ with nothing

*translate the remaining occurrences, i.e. replace %0D%0A with ", "

var x = '%0D%0A%0D%0A%0D%0Ahello, world%0D%0A%0D%0A';

x = x.replace(/^(?:%0D%0A)+|(?:%0D%0A)+$/g, '');
x = x.replace(/%0D%0A/g, ', ');

alert(x);


text:
Q: Who are the top 3 actresses based on number of Super Hit movies (average rating >8) in drama genre using mysql  SELECT n.name as actress_name , r.total_votes , COUNT(r.movie_id) as movie_count, r.avg_rating as actress_avg_rating,
    RANK() OVER(
                ORDER BY
                COUNT(r.movie_id) DESC
                ) actress_rank
    FROM names as n
    INNER JOIN role_mapping as rm
    ON n.id = rm.name_id
    INNER JOIN movie as m
    ON rm.name_id = m.id
    INNER JOIN ratings as r
    ON m.id = r.movie_id
    INNER JOIN genre as g
    ON g.movie_id = r.movie_id
    WHERE r.avg_rating > 8 AND g.genre = 'Drama' AND rm.category ='actress'
    GROUP BY actress_name
    LIMIT 3;

Please help me with this! I am also confused if it is the average of 'avg_rating' column for a actress.

A: You just need aggregations , and partitioning within the RANK() analytic function, while removing LIMIT clause such as
SELECT *
  FROM
  (
   SELECT n.name AS actress_name ,
          AVG(r.avg_rating) AS actress_avg_rating,
          SUM(r.total_votes) AS total_votes,
          COUNT(r.movie_id) AS movie_count,
          RANK() OVER ( PARTITION BY n.name
                            ORDER BY COUNT(r.movie_id) DESC) AS actress_rank
     FROM names AS n
     JOIN role_mapping AS rm
      ON n.id = rm.name_id
     JOIN movie AS m
      ON rm.name_id = m.id
     JOIN ratings AS r
      ON m.id = r.movie_id
     JOIN genre AS g
      ON g.movie_id = r.movie_id
    WHERE r.avg_rating > 8 AND g.genre = 'Drama' AND rm.category ='actress'
    GROUP BY actress_name
  ) q
 WHERE actress_rank <= 3

A: First, properly run an aggregate query. MySQL due to the ONLY_FULL_GROUP_BY setting turned off permits non-aggregated columns to be omitted in GROUP BY clause which in proper ANSI SQL should error out unless omitted column(s) is functionally dependent on columns in GROUP BY.
Secondly, calculate needed RANK() partitioned on actress_name using the movie_count aggregate. And in outermost query, subset by calculaetd rank column. With CTEs, you can refactor code by these steps:
WITH agg (
  SELECT n.name AS actress_name
         , SUM(r.total_votes) AS total_votes        -- TURNED AGGREGATE
         , AVG(r.avg_rating)  AS movie_avg_rating   -- TURNED AGGREGATE (RENAMED ALIAS)
         , COUNT(r.movie_id)  AS movie_count
         , RANK() OVER(PARTITION BY n.name          -- ADDED PARTITION
                       ORDER BY COUNT(r.movie_id) DESC) AS actress_rank
  FROM names as n
  INNER JOIN role_mapping as rm
      ON n.id = rm.name_id
  INNER JOIN movie as m
      ON rm.name_id = m.id
      AND rm.category ='actress'
  INNER JOIN ratings as r
      ON m.id = r.movie_id
      AND r.avg_rating > 8
  INNER JOIN genre as g
      ON g.movie_id = r.movie_id
      AND g.genre = 'Drama'
  GROUP BY n.name
)

SELECT actress_name
       , total_votes
       , movie_avg_rating
       , movie_count
       , actress_rank
FROM agg
WHERE actress_rank <= 3


text:
Q: In this android-compose codelab why do they pass Lambda instead of navController? Why does this codelab at android developers passes a "onNextButtonClicked: () -> Unit," instead of just passing the "navController: NavController,"... it seems simpler.. is there a reason for this?

Codelab in github

A: This is called state hoisting. You could read more on official documentation.
A quick answer to your question though: The way you mentioned it will work. But by hoisting state — that is, to move a composable's state outside of the composable and push it further up, by making the composable stateless it results in components that are easier to reuse and test!

A: Passing the nav controller to screens is not a good practice, one of the previous answers.
Test writing:
When you reach the command you want through callback to the highest level; You are now comfortable for writing tests and you don't need to mock the nav controller.
Therefore, only by checking the callbacks that you have used, you can ensure the correctness of the functionality of your composables.
Consider the following example:
PostScreen

import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.Button
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember

@Composable
fun PostScreen(
    navigateToPostDetail: (PostId: PostId) -> Unit
) {
    val posts = remember {
        mutableListOf<Post>().apply {
            repeat(10) {
                add(
                    Post(
                        id = "$it", title = "Title $it"
                    )
                )
            }
        }
    }
    PostScreenContent(
        posts = posts,
        navigateToPostDetail = navigateToPostDetail
    )
}

data class Post(
    val id: String, val title: String
)

@Composable
internal fun PostScreenContent(
    posts: List<Post>,
    navigateToPostDetail: (PostId: PostId) -> Unit
) {
    LazyColumn {
        items(items = posts, key = { item -> item.id }) { item ->
            Text(text = item.title)
            Button(onClick = {
                navigateToPostDetail(PostId(item.id))
            }
            ) {
                Text(text = "Navigate To Detail")
            }
        }
    }

}

@JvmInline
value class PostId(val value: String)

PostScreenTest

import androidx.activity.ComponentActivity
import androidx.compose.runtime.remember
import androidx.compose.ui.test.junit4.createAndroidComposeRule
import org.junit.Rule
import org.junit.Test

internal class PostScreenTest {
    @get:Rule
    val composeTestRule = createAndroidComposeRule<ComponentActivity>()

    @Test
    fun clickOnPostItem() {
        var expectedPostId = "your expected id"
        var actualPostId: String
        with(composeTestRule) {
            setContent {
                val posts = remember {
                    mutableListOf<Post>().apply {
                        repeat(10) {
                            add(
                                Post(
                                    id = "$it",
                                    title = "Title $it"
                                )
                            )
                        }
                    }
                }
                PostScreenContent(
                    posts = posts,
                    navigateToPostDetail = {
                        actualPostId = it.value
                    }
                )
            }
            assertThat(actualPostId).isEqualTo(expectedPostId)
        }
    }
}

However, if you want to test the navigation logic of the whole app, it is enough to test your highest layer, the place where you used NavHost.


text:
Q: Is it possible to do live streaming with FFmpeg in AS3 I know its possible for FFmpeg to render from the webcam to SWF and FLV. But the problem is the SWF file can only be read via AS2 and FLV seems to only be loading a static frame from my Flash Player.
Is there a way for FFmpeg to render a AVM3 SWF or a stream-able FLV?