text:
Q: Bind VMware to specific GPU I have two GPUs in my setup and want to use GPU A for games while GPU B handles VMware VMs.
How can I achieve this?

A: Yes, this is possible if you have two Nvidia graphics card.

*

*Open Nvidia Control Panel and navigate to Manage 3D Settings1 → Program Settings.2

*

*Select your program3 or if not found add it to your list.4

*

*Now you can specificate the GPU used for CUDA5 and OpenGL Rendering.6 select your preferred GPU7 and you're good to go.


text:
Q: Alternative Javascript Method for PerformanceNavigation (Cross-browser Compatible) I have semi-successfully implemented the following Javascript, but am having some difficulties achieving cross-browser compatibility (specifically in Firefox) with window.performance.navigation, since it has since been deprecated.
Here's what I've implemented, so far:
window.addEventListener("load",function(event){
    var historyTraversal=event.persisted||
    (typeof window.performance!=="undefined"&&
    window.performance.navigation.type===2);
    if(historyTraversal){
        window.history.back();
    }
});

Any alternative ways to formatting this?

A: As mentioned on MDN, Performance.navigation is deprecated because it's marked as such in the Navigation Timing Level 2 specification. As recommended on the specs, PerformanceNavigationTiming should be used instead: this is compatible with all the latest major browsers.
The property you're looking for is now available here, and you can query it as var perfEntries = performance.getEntriesByType("back_forward");.

A: Unfortunately it doesn't work in Safari.
This does (see Safari back button doesn't reload page when used):
window.addEventListener("pageshow", function(evt){
    if(evt.persisted){
    setTimeout(function(){
        window.location.reload();
    },10);
}
}, false);

redpajama_set_name: RedPajamaStackExchange


text:
Q: wordpress pagination url first page i am using paginate_links on my website.
when i clicked number two url chage as mywebsite.com /page/2.
then i cicled pagination page number 1 and site url show mywebsite.com /page/1.
i want to remove /page/1 on home page firs page.
this issue only home page.category page are working good.
Ex : <<prev | 1 | 2 | next >>
Anyone can help me ?
paginate_links( array(
        'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),
        'format' => '/page/%#%',
        'current' => max( 1, get_query_var('paged') ),
        'total' => $wp_query->max_num_pages,
        'prev_next' => true,
        'prev_text'    => __('Prev Page'),
        'next_text'    => __('Next Page'),
        'type'  => 'array'
    ) );

A: There is a filter for this needs
add_filter( 'paginate_links', function($link){

    //Remove link page/1/ from the first element and prev element

    if(is_paged()){
        $link= str_replace('page/1/', '', $link);
    }

    return $link;
} );

A: if yoursite.com/page/1 and yoursite.com is the same, why don't you use jquery to change href attribute of your pagination links?
$(".pagination a:first").attr("href", "http://example.com/");

this code simply changes url of the pagination's first link.
Edit: this will change your site's prev link's href attribute. It won't be good if user is on page 3, or whatever.
Try this:
if($('.pagination a:first').attr('href') === "http://example.com/page/1") {
    // this is page 2.
    $(".pagination a:first").attr("href", "http://example.com/");
}
    $(".pagination a:nth-child(2)").attr("href", "http://example.com/");

FIDDLE


text:
Q: How to isolate builds in jenkins using docker I am using jenkins 2 on a dedicated server. My build is a multibranch pipeline and the first step of this build is to do a docker-compose up -d in order to run databases (redis and mongo) and running tests against them.
Everything works fine until you have 2 commits on different branches at the same time ; one of the 2 build cannot start the container, because the port is of course already taken.
I would love to be able to run the 2 builds on 2 different branches in parallels : how cat I achieve that ?
My docker-compose.yml file looks like this:
mongo:
  image: mongo:2.6.12
  ports:
    - 27017:27017
  mem_limit: 100m

redis:
  image: redis:3.0.7-alpine
  ports:
    - 6379:6379
  mem_limit: 60m

My build is done with a Jenkinsfile and I have read there is a way to run a build inside a container
docker.image("some image").inside{
    // build
}

A: I would recommend you omit port exposing. Or you need expose docker port to random docker port
mongo:
  image: mongo:2.6.12
  ports:
    - 27017
  mem_limit: 100m

redis:
  image: redis:3.0.7-alpine
  ports:
    - 6379
  mem_limit: 60m

if your application running into docker network port exposing don`t needed.


text:
Q: Two ways of implement Delegation in Swift, what is the difference? Say for example you have a protocol in Swift:
protocol WeatherServiceDelegate: class {
    func didCompleteRequest(result: String)
}

Two ways of implementing them:
Way 1: Via class inheritance
class ViewController: UIViewController, WeatherServiceDelegate {
     ....
}

Way 2: Via extension
However, Swift does provide a keyword extension which can be used to implement the protocol methods
extension ViewController: WeatherServiceDelegate{
    func didCompleteRequest(result: String){
        print(result)
    }
}

Is there any difference on those two methods?

A: Per Apple's guide:

Extensions add new functionality to an existing class, structure, enumeration, or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling).

So it appears in your case there is little difference except in how you want to arrange your code.

A: Well! There's no difference at runtime. But when adding protocol conformance to a model, prefer adding a separate extension for the protocol methods. This keeps the related methods grouped together with the protocol and can simplify instructions to add a protocol to a class with its associated methods.
Preferred:
    class MyViewController: UIViewController {
    // class stuff here
}

// MARK: - UITableViewDataSource
extension MyViewController: UITableViewDataSource {
    // table view data source methods
}

// MARK: - UIScrollViewDelegate
extension MyViewController: UIScrollViewDelegate {
    // scroll view delegate methods
}

Not Preferred:
class MyViewController:UIViewController,UITableViewDataSource,UIScrollViewDelegate {
// all methods

}


text:
Q: How to can a fragment in TabActivity from AppActivity I am novice and trying to develop some app in my mind. Stuck with below error.
I have a main tabbed activity. 1st Tab is Add Record(Fragment), 2nd tab is Tracker( Fragment)of the added record. This Tracker have a filter button. When i click on Filter, Filter activity is opened which contains expandable list items. User selects some criteria and apply filter. Here i want to navigate to FilterActivity to 2nd Tracker tab. How can i do this?
When i try below line, the application halts and shows unfortunately your app has stopped error and momentary i am navigating to my Tracker tab. How to avoid that error message?
Intent intent=new Intent(FilterActivity.this,ShowTrackerRecycler.class);

Here ShowTrackerRecycler is a fragment which extends Fragment.
Getting below error:
java.lang.ClassCastException: com.aaa.bbb.ShowTrackerRecycler cannot be cast to android.app.Activity

A: You have to call the activity that uses the tracker fragment. In that activity then load the fragment.
So create an intent leading to the TabActivity which holds the trackerFragment
Add data for the activity to know what to do:
intent.putExtra("showTracker", true);
Then when the TabActivity loads,
Check for the extra data and load the fragment based on the data:
Bundle bundle = getIntent().getExtras();
if (bundle != null && bundle.getBoolean("showTracker")) {
    // LOAD TRACKER FRAGMENT
}


text:
Q: Coloring with Hue for a function on a lattice grid I wish to color a 2-dimensional lattice grid according to the value of a function at each lattice-node.
More specifically, if I have 9 angles in a 3x3 array,
angles={{0, π, π}, {0, 0, π/2}, {π/2, 0, 3 π/3}}

then one can plot these angles on a lattice-grid by the following code in Mathematica:
angles = {{0, π, π}, {0, 0, π/2}, {π/2, 0, 3 π/3}};
GraphicsGrid[
 Map[Graphics[{
    LightGray, Circle[{0, 0}, 1],
    Hue[#/(2 π), .6, .8], Thick, Arrowheads[Medium], Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &,
  angles, {2}]]

Here, the colouring is done using the Hue command according to the value of each angle. However, now I want to compute a function f[i,j]; to be more specific,
f[i_,j_]:=Cos[angles[[i + 1, j]] - angles[[i, j]]] + Cos[angles[[i, j+1]] - angles[[i, j]]];

with
angles[[n+1,i_]]:=angles[[1,i]];
angles[[i_,n+1]]:=angles[[i,1]];

i.e., the boundary conditions.
In the first code, Hue is used with the angles[[i,j]] (through #), which is probably straightforward. But is it possible to use f[i,j] instead, where f[i,j] is defined as above?
P.S. This question is related to: data visualization on a lattice grid
Thanks!
dbm
P.S. The final code, thanks to BoLe's answers:
Clear["Global`*"];
n := 10
angles = Table[RandomReal[{-Pi, Pi}], {i, n}, {j, n}];
f[here_, down_, right_] := Cos[down - here] + Cos[right - here]
g[list_, {i_, j_}] :=
 Module[{m, n}, {m, n} = Dimensions[list]; {list[[i, j]],
   If[i != m, list[[i + 1, j]], -list[[1, j]]],
   If[j != n, list[[i, j + 1]], -list[[i, 1]]]}]
GraphicsGrid[
 MapIndexed[
  Graphics[{LightGray, Circle[{0, 0}, 1],
     Hue[Rescale[f @@ g[angles, #2], {-2, 2}, {0, 1}]], Thin,
     Arrowheads[Small], Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &,
  angles, {2}]]

A: Define f and apply it to every element of the matrix (that becomes three elements). Mod ensures periodic boundaries.
f[here_, down_, right_] := Cos[down - here] + Cos[right - here]

MapIndexed[
 f @@ Extract[angles,
    Mod[{#2, #2 + {1, 0}, #2 + {0, 1}}, 3, 1]] &,
 angles, {2}]

Replying to first comment.
(* @whuber example *)
angles = 2 Pi ImageData[
    ImageAdjust[Blur[RandomImage[1, {20, 10}], 8], 4]];

GraphicsGrid[Map[Graphics[{
     Gray, Thin, Arrowheads[Small],
     Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &, angles, {2}]]

Coloring according to f, which can be between -2 and 2 I think, rescaled to 0-to-1 for Hue.
GraphicsGrid[MapIndexed[Graphics[{
     Hue[Rescale[
       f @@ Extract[angles,
         Mod[{#2, #2 + {1, 0}, #2 + {0, 1}}, 3, 1]],
       {-2, 2}, {0, 1}]],
     Thin, Arrowheads[Small],
     Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &, angles, {2}]]

Replying to fourth comment: One way to code custom boundary conditions is to define a custom extraction function and place it in place of Extract.
g[list_, {i_, j_}] := Module[{m, n},
  {m, n} = Dimensions[list]; {
   list[[i, j]],
   If[i != m, list[[i + 1, j]], -list[[1, j]]],
   If[j != n, list[[i, j + 1]], -list[[i, 1]]]}]

GraphicsGrid[MapIndexed[Graphics[{
     Hue[Rescale[f @@ g[angles, #2], {-2, 2}, {0, 1}]],
     Thin, Arrowheads[Small],
     Arrow[{{0, 0}, {Cos[#], Sin[#]}}]}] &, angles, {2}]]


text:
Q: Merge selected changes in a file stepwise I've made some changes to a file on a git branch (let's call this branch experimental). I'd now like to merge in some, but not all of the changes I made to this file into my development branch. Is there a way to go through each change within this file step-wise and manual tell git to merge a particular change or ignore it?

A: If the changes in experimental are already at a commit granularity, then you want
git checkout development
git cherry-pick <sha ID>
...

If your changes to experimental are more random smaller commits or one huge commit, then I'd follow this flow:
git checkout development
git merge experimental --squash --no-commit

This puts all the changes into your index
Then add interactively:
git add -i

This presents a pretty basic UI where you can initially unstage everything, then pick in hunks, and even edit hunks on a line-by-line granularity.
Once you're satisfied with what you have in staging,
git commit

You still have random changes in the 'modified' state, basically (1 - what-you-committed).
You want to get rid of this using:
git reset --hard HEAD


text:
Q: Video codecs on IGEL clients? Or HTML5 Video Tag? I have a difficult problem. I have a python web application that creates a HTML5 Video Tag like it's done in this example:
https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_video_autoplay
It's working fine in Firefox! BUT: I have a IGEL Client solution with Firefox 52.7.2 and there I get the error message "Video format or MIME type is not supported". But I CAN play the video directly in the IGEL Firefox Browser with the URL.
Anyone with an idea where the problem could be?


text:
Q: Gluing text to longtable I am an occasional LaTex user. My question relates to the use of longtable. If I understand the standard table constructs, then "tabular" defines the layout of the actual table grid with contents, and "table" creates an environment for the table that governs the placement and also contains the associated text, such as the caption, notes, etc. Now, as I understand it, "longtable" basically replaces "tablular," but it cannot be placed into a "table" environment.
I need some text that is associated with the table to print out immediately below it, and don't know who to force that:
\begin{center}
{\footnotesize
\begin{longtable}{lr}
\caption{Probit estimates for household matching, Burundi, 2006}\\
\hline
      & \textbf{Public/WFP transfers} \\
\cline{2-2}
      & \textbf{dF/dX} \\
\cline{2-2}
\endfirsthead
\multicolumn{2}{c}%
{\tablename\ \thetable\ -- \textit{Continued from previous page}} \\
\hline
      & \textbf{Public/WFP transfers} \\
\cline{2-2}
      & \textbf{dF/dX} \\
\cline{2-2}
\endhead
\hline \multicolumn{2}{r}{\textit{Continued on next page}} \\
\endfoot
\hline
\endlastfoot
\multirow{2}{*}{leave-out mean of beneficiaries h'hold in the PSU} & 0.7929*** \\
     & [0.0479] \\
\multirow{2}{*}{household size} & -0.0093** \\
      & [0.0037] \\
\multirow{2}{*}{h'hold head is female} & 0.0337 \\
      & [0.0300] \\
… MANY MORE ROWS
Number of observations  & 3203 \\
\% of correct predictions & 84.01 \\
\hline
\end{longtable}}
\end{center}

Immediately followed by:
Robust standard errors in brackets.\\
*** p<0.01, ** p<0.05, * p<0.1\\
Authors' estimations using 2006 QUIBB survey.\\
\textbf{Note}: For the impact analysis, the sample is restricted to
 the relevant geographic area. i.e. only the PSU with at least one
 household who have benefited from the WFP transfer

.
Thanks

A: longtable environments do not float, so the text placed after the table in the source will be typeset after the table. Also a center environment has no affect on longtable (which technically is always full width).
As an alternative to just placing it after the table you can place it in a \multicolumn so it is aligned with the columns.
\documentclass{article}
\usepackage{multirow,longtable}
\begin{document}

{\footnotesize
\begin{longtable}{lr}
\caption{Probit estimates for household matching, Burundi, 2006}\\
\hline
      & \textbf{Public/WFP transfers} \\
\cline{2-2}
      & \textbf{dF/dX} \\
\cline{2-2}
\endfirsthead
\multicolumn{2}{c}%
{\tablename\ \thetable\ -- \textit{Continued from previous page}} \\
\hline
      & \textbf{Public/WFP transfers} \\
\cline{2-2}
      & \textbf{dF/dX} \\
\cline{2-2}
\endhead
\hline \multicolumn{2}{r}{\textit{Continued on next page}} \\
\endfoot
\hline
\endlastfoot
\multirow{2}{*}{leave-out mean of beneficiaries h'hold in the PSU} & 0.7929*** \\
     & [0.0479] \\
\multirow{2}{*}{household size} & -0.0093** \\
      & [0.0037] \\
\multirow{2}{*}{h'hold head is female} & 0.0337 \\
      & [0.0300] \\
… MANY MORE ROWS
Number of observations  & 3203 \\
\% of correct predictions & 84.01 \\
\hline
\end{longtable}}

\noindent
Robust standard errors in brackets.\\
*** $p<0.01$, ** $p<0.05$, * $p<0.1$\\
Authors' estimations using 2006 QUIBB survey.

\noindent
\textbf{Note}: For the impact analysis, the sample is restricted to
 the relevant geographic area. i.e. only the PSU with at least one
 household who have benefited from the WFP transfer

\end{document}


text:
Q: How can I handle a list of checkboxes dynamically created in flutter? Using flutter, I am trying to build a list of values with some text and a customized checkbox next to it. Tapping anywhere on the text or checkbox should show the enabled state and tapping again should disable it. I am unsure how to handle the state of each checkbox separately. I tried using CheckBoxListTile too but I am not sure how I can achieve what I want. Can someone provide any examples?

A: use List contains returns bool.
here is example
List<int> selectedList = [];
List<Widget> mList; //you can't add equal
createMenuWidget(Course courses) {
  for (int b = 0; b < courses.length; b++) {
    Map cmap = courses[b];
    mList.add(CheckboxListTile(
      onChanged: (bool value){
        setState(() {
          if(value){
            selectedList.add(cmap[course_id]);
          }else{
            selectedList.remove(cmap[course_id]);
          }
        });
      },
      value: selectedList.contains(cmap[course_id]),
      title: new Text(cmap[course_name]),
    ));
  }
}

A: The simple Way to Do this with Dynamic List of Data with CheckBox.
List<String>data= ["Mathew","Deon","Sara","Yeu"];
List<String> userChecked = [];

ListView.builder(
    itemCount: data.length,
    itemBuilder: (context, i) {
      return ListTile(
        title: Text(
            data[i])
        trailing:Checkbox(
                value: userChecked.contains(data[i]),
                onChanged: (val) {
                  _onSelected(val, data[i]);
                },
              )
            //you can use checkboxlistTile too
      );
    })
// now we write the functionality to check and uncheck it!!

void _onSelected(bool selected, String dataName) {
if (selected == true) {
  setState(() {
    userChecked.add(dataName);
  });
} else {
  setState(() {
    userChecked.remove(dataName);
  });
}

}
And Its Done !!...
Enjoy Fluttering...
Give a thumbs up as it will work for you !! :P

A: Please use package grouped_buttons.
It support both checkbox and radio.
https://pub.dartlang.org/packages/grouped_buttons
CheckboxGroup(
      labels: <String>[
        "Sunday",
        "Monday",
        "Tuesday",
        "Wednesday",
        "Thursday",
        "Friday",
        "Saturday",
      ],
      disabled: [
        "Wednesday",
        "Friday"
      ],
      onChange: (bool isChecked, String label, int index) => print("isChecked: $isChecked   label: $label  index: $index"),
      onSelected: (List<String> checked) => print("checked: ${checked.toString()}"),
    ),

and full example of usage in here https://github.com/akshathjain/grouped_buttons/blob/master/example/lib/main.dart
and author's logic to implement
https://github.com/akshathjain/grouped_buttons/blob/master/lib/src/checkbox_group.dart
Basically, author use two List of Strings to control selected and unselect
void onChanged(bool isChecked, int i){
  bool isAlreadyContained = _selected.contains(widget.labels.elementAt(i));

  if(mounted){
   setState(() {
    if(!isChecked && isAlreadyContained){
      _selected.remove(widget.labels.elementAt(i));
    }else if(isChecked && !isAlreadyContained){
      _selected.add(widget.labels.elementAt(i));
    }

    if(widget.onChange != null) widget.onChange(isChecked, widget.labels.elementAt(i), i);
    if(widget.onSelected != null) widget.onSelected(_selected);
   });
 }
}

A: Screenshot (Null safe)

Code:
class _MyPageState extends State<MyPage> {
  final Map<String, bool> _map = {};
  int _count = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () => setState(() => _map.addEntries([MapEntry('Checkbox #${++_count}', false)])),
      ),
      body: ListView(
        children: _map.keys
            .map(
              (key) => CheckboxListTile(
                value: _map[key],
                onChanged: (value) => setState(() => _map[key] = value!),
                subtitle: Text(key),
              ),
            )
            .toList(),
      ),
    );
  }
}

A: Here's some sample code for CheckboxListTile. You can find more examples in the gallery.

import 'package:flutter/material.dart';

class Demo extends StatefulWidget {
  @override
  DemoState createState() => new DemoState();
}

class DemoState extends State<Demo> {
  Map<String, bool> values = {
    'foo': true,
    'bar': false,
  };

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(title: new Text('CheckboxListTile demo')),
      body: new ListView(
        children: values.keys.map((String key) {
          return new CheckboxListTile(
            title: new Text(key),
            value: values[key],
            onChanged: (bool value) {
              setState(() {
                values[key] = value;
              });
            },
          );
        }).toList(),
      ),
    );
  }
}

void main() {
  runApp(new MaterialApp(home: new Demo(), debugShowCheckedModeBanner: false));
}

A: Use chekboxListTile
Here is the sample code
    @override
    Widget build(BuildContext context) {
      return Center(
        child: CheckboxListTile(
          title: Text('Check me'),
  );
    }

By the way, You can also add checkbox in ListView in Flutter. Apps sample is given below-
Main.dart
import 'package:flutter/material.dart';
import 'checkbox_in_listview_task-7.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue,
      ),
home: CheckBoxInListview(),
    );
  }
}

checkbox_in_listview_task.dart
import 'package:flutter/material.dart';

class CheckBoxInListview extends StatefulWidget {
  @override
  _CheckBoxInListviewState createState() => _CheckBoxInListviewState();
}

class _CheckBoxInListviewState extends State<CheckBoxInListview> {
  bool _isChecked = true;

  List<String> _texts = [
    "InduceSmile.com," "Flutter.io",
    "google.com",
    "youtube.com",
    "yahoo.com",
    "gmail.com"
  ];
  @override
  Widget build(BuildContext context) {
return Scaffold(
      appBar: AppBar(
        title: Text("CheckBox in ListView Example"),
      ),
      body: ListView(
        padding: EdgeInsets.all(8.0),
        children: _texts.map((text) => CheckboxListTile(
          title: Text(text),
           value: _isChecked,
              onChanged: (val) {
              setState(() {
               _isChecked = val;

            });
          },
        )).toList(),
      ),
    );
  }
}

And here is the output

A: I think it will work as you want. It also stores all selected checkbox value(s) into a List variable. so you please simply put this code in main.dart file and execute to check how it works.
import 'package:flutter/material.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(title: 'Multi-Select & Unselect Checkbox in Flutter'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List _selecteCategorys = List();

  Map<String, dynamic> _categories = {
    "responseCode": "1",
    "responseText": "List categories.",
    "responseBody": [
      {"category_id": "5", "category_name": "Barber"},
      {"category_id": "3", "category_name": "Carpanter"},
      {"category_id": "7", "category_name": "Cook"}
    ],
    "responseTotalResult":
        3 // Total result is 3 here becasue we have 3 categories in responseBody.
  };

  void _onCategorySelected(bool selected, category_id) {
    if (selected == true) {
      setState(() {
        _selecteCategorys.add(category_id);
      });
    } else {
      setState(() {
        _selecteCategorys.remove(category_id);
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: ListView.builder(
          itemCount: _categories['responseTotalResult'],
          itemBuilder: (BuildContext context, int index) {
            return CheckboxListTile(
              value: _selecteCategorys
                  .contains(_categories['responseBody'][index]['category_id']),
              onChanged: (bool selected) {
                _onCategorySelected(selected,
                    _categories['responseBody'][index]['category_id']);
              },
              title: Text(_categories['responseBody'][index]['category_name']),
            );
          }),
    );
  }
}

A: here how you can do it
import 'package:flutter/material.dart';

class RegisterFragments extends StatefulWidget {
  RegisterFragments({Key key, this.step}) : super(key: key);
  final int step;

  _RegisterFragmentsState createState() => _RegisterFragmentsState();
}

class _RegisterFragmentsState extends State<RegisterFragments> {
  Map<String, bool> values = {"abc": false, "def": true, "ghi": false};
  List<String> _do = ['One', 'Two', 'Free', 'Four'];
  String _dropdownValue = 'One';

  @override
  Widget build(BuildContext context) {
    switch (widget.step) {
      case 0:
        return buildDo();
        break;
      case 1:
        return Container(
          child: ListView.builder(
            shrinkWrap: true,
            itemCount: values.length,
            itemBuilder: (BuildContext context, int index) {
              switch (widget.step) {
                case 0:
                  return buildDo();
                  break;
                case 1:
                  return buildService(context, index);
                  break;
                default:
                  return Container();
                  break;
              }
            },
          ),
        );
        break;
      default:
        return Container();
        break;
    }
  }

  Widget buildService(BuildContext context, int index) {
    String _key = values.keys.elementAt(index);

    return Container(
      child: Card(
        child: CheckboxListTile(
          title: Text(_key),
          onChanged: (bool value) {
            setState(() {
              values[_key] = value;
            });
          },
          value: values[_key],
        ),
      ),
    );
  }

  Widget buildDo() {
    return DropdownButton<String>(
      isExpanded: true,
      hint: Text("Service"),
      items: _do.map<DropdownMenuItem<String>>((String value) {
        return DropdownMenuItem<String>(
          value: value,
          child: Text(value),
        );
      }).toList(),
      onChanged: (String newValue) {
        setState(() {
          this._dropdownValue = newValue;
        });
      },
      value: _dropdownValue,
    );
  }
}

A: In case you are using the CheckBoxGroup or anything similar AND are inside a slider, do not forget to put it in a StatefulBuilder:
    return StatefulBuilder(// StatefulBuilder
    builder: (context, setState) {
  return CheckboxGroup(
    orientation: GroupedButtonsOrientation.HORIZONTAL,
    margin: const EdgeInsets.only(left: 12.0),
    onSelected: (List selected) => setState(() {
      _checked = selected;
    }),
    labels: teamWorkoutDays,
    checked: _checked,
    itemBuilder: (Checkbox cb, Text txt, int i) {
      return Column(
        children: <Widget>[
          Icon(Icons.polymer),
          cb,
          txt,
        ],
      );
    },
  );
});


text:
Q: How to mark DataFrame rows with nan in any column I'd like to use a DataFrame with a DatetimeIndex to align data from different sets (the columns) on their timestamps.  Each data set may have overlapping and non-overlapping timestamps.  As a simple example
import pandas as pd

N = 5
ts_idx1 = pd.date_range('2015-05-22 15:00:00', periods=N, freq='10S')
a = pd.DataFrame(np.random.randn(5), index=ts_idx1, columns=['a'])

ts_idx2 = pd.date_range('2015-05-22 15:00:20', periods=N, freq='10S')
b = pd.DataFrame(np.random.randn(5), index=ts_idx2, columns=['b'])

ab_df = a.join(pd.DataFrame(b, columns=['b']), how='outer')

ab_df might look something like this
                           a           b
2015-05-22 15:00:00    0.293741          nan
2015-05-22 15:00:10   -0.799414          nan
2015-05-22 15:00:20    0.361964    -0.403397
2015-05-22 15:00:30   -0.932385    -0.070403
2015-05-22 15:00:40   -0.702407     0.819322
2015-05-22 15:00:50         nan    -0.771400
2015-05-22 15:01:00         nan    -0.915791

Is there a quick way of determining if any DataFrame columns contain a nan (essentially a set intersection) to determine which are the timestamps or rows that have valid data (non-nan) in all columns.   I can think of the following as a possible solution:
valid_mask = [np.all(~np.isnan(x)) for x in ab_df.values]

but it seems a little cryptic, is there a better way with a DataFrame method?

A: There's a somewhat more native approach combining notnull and all:
>>> df.notnull().all(axis=1)
2015-05-22 15:00:00    False
2015-05-22 15:00:10    False
2015-05-22 15:00:20     True
2015-05-22 15:00:30     True
2015-05-22 15:00:40     True
2015-05-22 15:00:50    False
2015-05-22 15:01:00    False
dtype: bool
>>> [np.all(~np.isnan(x)) for x in df.values]
[False, False, True, True, True, False, False]

Sometimes it's simpler to use df.dropna() rather than materializing a mask, but having an explicit mask can be handy too.


text:
Q: What is the best solution to pause and resume pthreads? I've found the following topic (here) about pthreads but there are many good solutions.
I wanted to know if the following piece of code is valid and if so, why the same lock is used to call pthread_cond_wait as well as access it and then unlocked right away:
void suspendMe()
{
    pthread_mutex_lock(&m_SuspendMutex);
    pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
    pthread_mutex_unlock(&m_SuspendMutex);
}

Would it not be better to use 2 separate mutexes here, or is this the correct way to suspend a pthread??
Thanks in advance!
EDIT:
Awesome replies, thanks all.
Just one more related question. Since I want to resume a thread separately in another function, would this be more proper in resuming it?
void suspendMe()
{
    pthread_mutex_lock(&m_SuspendMutex);
    pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
}
void resumeMe()
{
    pthread_cond_signal(&m_ResumeCond);
    pthread_mutex_unlock(&m_SuspendMutex);
}

Thanks again everyone!! :~)

A: Actually, this code isn't thread safe. The mutex isn't actually protecting anything, leaving the implied predicate vulnerable to race conditions.
Look at this code -- what is the mutex protecting? What protects the suspend/resume state?
void suspendMe()
{
    pthread_mutex_lock(&m_SuspendMutex);
    pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
}
void resumeMe()
{
    pthread_cond_signal(&m_ResumeCond);
    pthread_mutex_unlock(&m_SuspendMutex);
}

This is correct:
void suspendMe()
{ // tell the thread to suspend
    pthread_mutex_lock(&m_SuspendMutex);
    m_SuspendFlag = 1;
    pthread_mutex_unlock(&m_SuspendMutex);
}
void resumeMe()
{ // tell the thread to resume
    pthread_mutex_lock(&m_SuspendMutex);
    m_SuspendFlag = 0;
    phtread_cond_broadcast(&m_ResumeCond);
    pthread_mutex_unlock(&m_SuspendMutex);
}
void checkSuspend()
{ // if suspended, suspend until resumed
    pthread_mutex_lock(&m_SuspendMutex);
    while (m_SuspendFlag != 0) pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
    pthread_mutex_unlock(&m_SuspendMutex);
}

The thread should call checkSuspend at safe points where it can be suspended. Other threads can call suspendMe and resumeMe to suspend/resume the thread.
Notice that now the mutex protects the m_SuspendFlag variable, ensuring that the thread is told to suspend, told to resume, and checks whether it should suspend or stay suspended under protection, making the code thread-safe.

Would it not be better to use 2 separate mutexes here, or is this the correct way to suspend a pthread??

Using two mutexes would defeat the entire point of condition variables. The whole mechanism by which they work is that you can check whether there is something you should wait for and then atomically wait for it without either holding the lock while you wait or having to release the lock and then wait. If you hold the lock while you wait, how can any other thread change the state? And if you release the lock and then wait, what happens if you miss the change in state?
By the way, it almost never makes sense to pause or resume a thread. If you feel like you need to pause a thread from the outside, that just indicates that you coded the thread to do something you didn't actually want it to do. Questions about pausing or resuming threads often indicate an incorrect mental model of thread programming. A thread might need to wait for something, but it shouldn't be "paused" from the outside because it should already know by its own coding when it shouldn't do some particular bit of work.

A: This is the correct way. pthread_cond_wait unlocks m_SuspendMutex, then waits on m_ResumeCond and then locks m_SuspendMutex again before returning.
The reason it works this way is because condition variables are used to signal a change of some state, and since this state is shared it must be locked while some thread is accessing it. E.g. consider implementing a queue of events:
T get_item()
{
    pthread_mutex_lock(&mutex);
    while(qu.empty())
        pthread_cond_wait(&cond, &mutex);
    T ret = qu.front();
    qu.pop();
    pthread_mutex_unlock(&mutex);
    return ret; // we got an item from a queue
}

void add_item(T x)
{
    pthread_mutex_lock(&mutex);
    qu.push(x);
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}

Note that:

*

*All the access to the queue qu is synchronized using the mutex.

*When we wait on the condition variable, we must unlock the mutex in order to allow the other threads to add items to the queue, and when it have been changed we must lock the mutex again to actually inspect the queue. This is exactly what pthread_cond_signal does.

A:
I wanted to know if the following piece of code is valid

Yes.

and if so, why the same lock is used to call pthread_cond_wait as well as access it and then unlocked right away:

The pthread_cond_wait() requires a locked mutex. This is because of the way condition varaibles are used. Normally they are used like this:
pthread_mutex_lock(&m_SuspendMutex);
while (!ready())
{
    pthread_cond_wait(&m_ResumeCond, &m_SuspendMutex);
}

// Modify the resources protexted by the lock.
pthread_mutex_unlock(&m_SuspendMutex);

So you acquire the lock saying you want to modify the resources protected by the lock. But if the object is not in a ready() state then you suspend your thread with pthread_cond_wait() which suspends the thread and unlocks the mutex (thus allowing other threads to aquire the lock and potentially transform the object into a ready() state).
When the ready state is achieved the m_ResumeCond is signalled and a waiting thread is released from suspension. But before it is allowed to exit pthread_cond_wait() it must reaquire the lock on m_SuspendMutex to make sure it is the only thread modifying the resources protected by the mutex.
To make sure the above is done correctly in an atomic fashion (the unlock/suspend/resume/lock) must by done by  pthread_cond_wait().

Would it not be better to use 2 separate mutexes here

No.

or is this the correct way to suspend a pthread??

As good as any other I suppose.


text:
Q: Views does not import to Entity Framework I have a few views in my database that im using in my ASP MVC-application. Now I am experiencing a very strange problem. There are 8 views in the database but even if I check them all in the Create Enity Data Model-guide only 7 of them are available as objects in the datacontext.
If I try to import ONLY the view that gets left out I get an empty model.
Is there some kind of limitation that I dont know of? Or is this a known problem?

A: Sounds like there is something special with this view. Things to check:

*

*Are the rights the same on this view as others?

*Try running a select on this view from query manager to confirm that it works

*Open up the "empty" model in an xml view and see if there are any error messages in it

A: I have ran into issues importing tables and views with no key defined. The entity framework will try to assign one automatically if it can, but if you have duplicate data you may have to create a primary key before EF will bring it in.

A: That didnt do the trick. I removed all joins from the view definition and added a very simple view (basically just a select from a single table). That worked. Then I added the joins one by one and made the view more complicated for each step. Now I have the same view as I had before I started this process and I can now import it without problems. Something is strange in the state of Denmark


text:
Q: EF Core with Pomelo.EntityFramework.Core 3.1.1 - Slow Query I'm using Pomelo.EntityFrameworkCore.MySql (3.1.1) with my MySql database.
I'm running the following query:
var model = await _dbContext.Model.FirstOrDefaultAsync(x => x.MyString == myString);

Model Definition:
    [Table("model")]
    public class Model
    {
        [Key]
        [Column("id")]
        public int Id { get; set; }

        [Column("my_string", TypeName = "varchar(36)")]
        public string MyString { get; set; }

        [Column("status")]
        public string Status { get; set; }
    }

The Model table only has 1 record.  However, this query takes a whopping 2+ seconds... this seems a little long for such a small simple query.  Have I mis-configured something somewhere?

A: Pomelo and MySQL do not run truly async queries.
We are currently performance tuning against EFCore 3.1 and Pomelo.EFCore 3.1.  One of our more complicated queries runs a full 2 seconds faster running sync (10609-11126ms) vs async (13073ms).


text:
Q: Local subdomains and DNS I have a following issue. I have in house server (old Dell desktop PC). I have about 9 devices I'm using to test my websites (written mainly in PHP and Python).
In the past, I was creating Nginx virtual hosts and was editing hosts file to point virtual subdomain to my main server, ex. dev.domain.com, dev.anotherdomain.net.
With lot of devices and websites it became really hard to manage it (+ I don't know how to edit hosts files on Android and iPad tablets).
I'm wondering (however my knowledge in that aspect is quite limited) if it's possible to set up DNS server (Bind9?) on my server and point its IP as the second NS in my internet connection? Would that work? If not, how do you usually manage that kind of stuff?
Regards,
Kyriagos

A: I set up a local DNS server as a forwarding-only server, give it the address of your ISP's nameservers. Then add a local domain to it's config. Add the necessary forward and reverse records for each local name you want to use on the web-server.
Set all the PCs to use the local DNS server. (Ideally using DHCP)
Then when PCs ask for the address of foo.example.com (computer foo in your local domain example.com), your local DNS server knows it is authoritative for that domain and gives the answer itself.
For any other query, the local nameserver forwards the query to your ISP's DNS server (or whatever you configure as a more knowledgable DNS server).


text:
Q: Add script for a HTML class in ASP.NET I´m add to my ASP.NET project a html audio player. I divided it with jquery in different classes that I can style it with css.
For the script call I use.
<script>
        $( function() { $( 'audio' ).audioPlayer(); } );
</script>

But if I use it in ASP.NET it doesn't work.
I add the scripts to a bundle.
public class BundleConfig
{
    public static void RegisterBundles(BundleCollection bundles)
    {

        bundles.Add(new ScriptBundle("~/bundles/audioplayer").Include(
                    "~/Scripts/jquery-{version}.js",
                    "~/Scripts/audioplayer.js"));
     }
}

And I add render the scripts at the bottom of the side.
@section Scripts {
@Scripts.Render("~/bundles/audioplayer")
}

Now, if i debug the side, he only show me the normal  tag, without any design. They don't add my -tag with the function.
Maybe someone finds my fault or what I forgot that it will work?

A: I got it working on my side.Please try this:
@{
    ViewBag.Title = "Home Page";
    Layout = null;
}

<link href="~/Content/audio.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-1.12.2.min.js"></script>
<script src="http://osvaldas.info/examples/audio-player-responsive-and-touch-friendly/audioplayer.js"></script>

<script type="text/javascript">
    $(function () {
        $('audio').audioPlayer();
    });
</script>
<div style="width:300px;">
    <audio src="~/Music/song.mp3" preload="auto" controls autoplay loop></audio>
</div>

Output:


text:
Q: Typescript : Search if an array (row) exists in a 2D array I'm trying to check if an array of coordinates [x,y,z] exists in a 2D array of other coordinates [[x,y,z],[x',y',z'],..]. I wonder if indexOf can be used here.
var ALLcoordinates:number[][];
ALLcoordinates = [];

var coordinates: number[];
coordinates = [alea1, alea2, alea3];

for (var i=0; i< dims; i++) {
    ALLcoordinates[i]=[];
    for (var j=0; j<chainSize; j++){
        ALLcoordinates[i][j]=0;
    }
}

So how can I make Typescript search "by rows"? Can I adapt indexOf for 2D arrays, or I do have to use loops? Here is my code, but I get quite an obvious error on data type : "Argument of type 'number[]' is not assignable to parameter of type 'number'."
if (coordinates.indexOf(ALLcoordinates) == -1) {

        // do stuff
 }

I would be glad for any help or ideas, thanx!

A: I would declare two custom classes Vector3 & Pair:
class Vector3 {

    public constructor(
        public x: number,
        public y: number,
        public z: number
    ) { }

    public isEqual(vector: Vector3) {
        return vector.x === this.x &&
            vector.x === this.x &&
            vector.x === this.x;
    }

}

class Pair {

    public constructor(
        private v1: Vector3,
        private v2: Vector3
    ) { }

    public getIndex(vector: Vector3) {
        if (this.v1.isEqual(vector)) return 0;
        if (this.v2.isEqual(vector)) return 1;
        return -1;
    }

    public contains(vector: Vector3) {
        return this.getIndex(vector) !== -1;
    }

}

Then you will end up with a nice API for your use case:
const v1 = new Vector3(1, 2, 3);
const v2 = new Vector3(4, 5, 6);
const v3 = new Vector3(7, 8, 9);

const pair = new Pair(v1, v2);

console.log(
    pair.contains(v1), // true
    pair.contains(v2), // true
    pair.contains(v3)  // false
);

A: You could write a function for it:
let ALLcoordinates:number[][] = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
let coordinates1: number[] = [1, 2, 3];
let coordinates2: number[] = [2, 3, 1];

function contains(array2d: number[][], array: number[]) {
    let result = array2d.filter((item) => {
        if(item.length === array.length) {
            for(var i = 0; i < item.length; i++) {
                if(item[i] !== array[i]) {
                    return false;
                }
            }
            return true;
        }
        return false;
    });
    return result.length > 0;
}

console.log(contains(ALLcoordinates, coordinates1)); //true
console.log(contains(ALLcoordinates, coordinates2)); //false

Testable Here (check console for output)


text:
Q: jsf2 get updated value from bean through javascript Here is my problem:
I have some table with users <rich:dataTable> and table for adding new user <table>. Then I'm clicking on <a4j:commandButton oncomplete="fnIsAdded()"> my form submitted and in fnIsAdded() I need to pass value from bean, like  <a4j:commandButton oncomplete="fnIsAdded(#{bean.somProperty})">. This is not working, so I need to pass it first to some hidden field <h:inputHidden value="#{bean.somProperty}"> and when to take it by javascript. My problem now is that the value that is get from javascript (from hidden field) is not refreshed if it's changed in bean. Once it got some value it stays static.

A: If #{bean.somProperty} returns a string which does not represent a boolean or a number in JavaScript syntax, then you need to quote it, otherwise JavaScript will interpret it as a variable name.
<a4j:commandButton ... oncomplete="fnIsAdded('#{bean.somProperty}')" />

As to the concrete question, just ajax-render the component.
<a4j:commandButton ... render="hidden" />
<h:inputHidden id="hidden" ... />


text:
Q: How to hide Edit button on navigation bar after click on more button on tabbar (In swift)? As I have 7 Tabbar button, iOS creates "more" button automatically and after click on that remaining tabbar button appears with "Edit" button on navigation bar.
I don't want this button, is there any way to remove or hide it?


text:
Q: Alias to create a Python package Wondering how to create an alias for creating a Python package. A Python package is nothing more than a folder with an empty __init__.py file inside it. So basically I need something like alias pydir="mkdir {dirname};cd {dirname};touch __init__.py". Is that something I can do with an alias? I'm using zsh if that matters. Thanks for your time!

A: What I wanted was a function. Here's what I came up with if anyone's interested:
pydir () { mkdir $1; touch $1/__init__.py; }


text:
Q: How to find the median number of events per year? Pandas group by datascience question I have a dataset where each row is an an event of terrorism and I want to find the median number of people killed per attack in each country-year unit. In df1, each row is an event of terrorism with columns iyear, country, nkill, and NumbAttack. in df2, each row is a country-year unit, with columns country, iyear, totalnkill, NumbAttackperYear, and MedKillperAttack.
STARTING WITH df1:

country
iyear
nkill
NumbAttack

Nigeria
2000
4
1

Nigeria
2000
7
1

Nigeria
2000
10
1

Nigeria
2002
10
1

Mali
2000
2
1

Mali
2000
12
1

Mali
2000
17
1

Mali
2001
12
1

Mali
2001
15
1

ENDING WITH df2:
| country| iyear | totalnkill | NumbAttackPerYear| MedKillperAttack|
| -------- | -------- |---------|------------|------------|
| Nigeria  | 2000     |   21    |     3      |     7      |
| Nigeria  | 2001     |   0     |     0      |     0      |
| Nigeria  | 2002     |   10    |     1      |     10     |
| Mali     | 2000     |   21    |     3      |     12     |
| Mali     | 2001     |   27    |     2      |    13.5    |
I understand how to use group by to get the totalnkill and NumbAttack:
df2 = df1.groupby(['country', 'iyear'])['nkill', 'NumbAttack'].sum()

Then renaming the columns:
df2 = df2.rename(columns={'nkill': 'totalnkill', 'NumbAttack': 'NumbAttackperYear'})

This part works! But I can't figure out an algorithm or an idea of how to find the Median number of people killed per attack for each country year unit. I get how you could take an average by just deviding totalnkill by NumbAttackperYear, but not Median. I'm really new to coding so I have trouble understanding the information in documentation etc, please help!! It would be great if you can explain what you are doing if it is complicated so I can learn. Thanks!


text:
Q: C# Binary string to Bytearray without conversion I call an API to get a PDF file. The API returns it as a string with binary data.
Now I need to save it to a file without any conversion of the data.
How can I do this in C#?
I have been trying
    string file = await service.GetDocumentsAsync(document.FileId);  //  Gets the filedata
    byte[] byteArray = file.Select (c => (byte)c).ToArray ();
    using (var stream = new FileStream($"c:\\temp\\{document.Id}.pdf", FileMode.Create))
    {
        stream.Write (byteArray,0,file.Length);
        stream.Close ();
    }

I do get the PDF, but it only has blank pages.
The beginning of the string when i look at it in the Debugger:

A: As suggested we had to change what the API returned. We use RestSharp and had to use Response.RawByte iso. Response.


text:
Q: Spring boot transaction in open session in view By default Spring boot uses open session in view pattern.
Does it mean that each time method annotated with @Transactional uses the entity manager created at the beginning of the request or creates a new one each time?

A: A transaction, unless with REQUIRES_NEW will re-use an existing thread bound  EntityManager or Session (depending if you use JPA or plain Hibernate). The open session in view, will open and bind one at the start of a request.
So it will reuse the current thread bound one.
For plain Hibernate you can check the SpringSessionContext class. For JPA this is a bit hidden in proxies, but you could check the EntityManagerFactoryUtils class.


text:
Q: D3 Javascript plotting function I am trying to write a tutorial about d3 and I found couple websites that can help but with not enough details.
I have the following code that outputs a bar chart:
<html>
<head>
<div id="mainGraph">
        </div>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript">

var t = 1, // start time (seconds since epoch)
    v = 0, // start value (subscribers)
    data = d3.range(33).map(next); // starting dataset

 function next() {
   return {
    time: ++t,
     value: v = ~~Math.max(10, Math.min(80, Math.exp(t)))
   };
}
setInterval(function() {
   data.shift();
   data.push(next());
 }, 1500);

  var w = 40,
      h = 100;

  var x = d3.scale.linear()
      .domain([0, 1])
      .range([0, w]);

  var y = d3.scale.linear()
      .domain([0, 100])
     .rangeRound([0, h]);

     var chart = d3.select("body")
     .append("svg:svg")
     .attr("class", "chart")
     .attr("width", w * data.length + 10)
     .attr("height", h);

     chart.selectAll("rect")
     .data(data)
    .enter().append("svg:rect")
     .attr("x", function(d, i) { return x(i) + 5; })
     .attr("y", function(d) { return h - y(d.value) + 5; })
     .attr("width", w)
     .attr("height", function(d) { return y(d.value); });

     chart.append("svg:line")
     .attr("x1", 0)
     .attr("x2", w * data.length)
     .attr("y1", h + 5)
     .attr("y2", h + 5)
     .attr("stroke", "#000");

    </script>
    </body>
    </html>

The first question is what does function()
the second question is when I try to change the set of data so i am trying to put v in function of t like v = Math.exp (t)
this is not working and its giving me a black line only even though I changed the interval of max and min.
Thank you.

A: function() as in :
setInterval(function() { ... });

is called a lambda function (or anonymus if you prefer). This means that the function has no name, and cannot be called outside it's scope. In this case, the setInterval  function requires a function as parameter, so we send in the full function definition instead of just a reference to it.


text:
Q: Make htaccess accept domain.com and www.domain.com How to modify this htaccess so that it will allow www.domain.com and domain.com. Now when i give www.domain.com, it changes it to domain.com
Options -Indexes
Options +FollowSymLinks

RewriteEngine on

RewriteCond %{HTTP_HOST} ^www\.(.+)$ [NC]
RewriteRule ^ http://%1%{REQUEST_URI} [L,R=301]

RewriteRule ^$ website/index.php [L]
RewriteCond %{DOCUMENT_ROOT}/website%{REQUEST_URI} -f
RewriteRule .* website/$0 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* website/index.php?q=$0 [QSA]

Sorry, dont have much knowledge with htaccess

A: Just take out first 301 rules that strips www:
Options -Indexes
Options +FollowSymLinks

RewriteEngine on

RewriteRule ^$ website/index.php [L]

RewriteCond %{DOCUMENT_ROOT}/website%{REQUEST_URI} -f
RewriteRule .* website/$0 [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule .* website/index.php?q=$0 [L,QSA]


text:
Q: Background image working with SurfaceView Working with a SurfaceView to make a 2d game i do not know who to put a background image in it efficiently.
I want to avoid drawing it each frame because it is an static image, any help?

A: The SurfaceView's Surface is a single layer.  You can specify a dirty rect to reduce your draw area when you lock the Canvas, but you have to draw everything in the rect every frame -- background and all.
You could use a pair of SurfaceViews, one at the default Z-ordering, one at "media" depth.  Use SurfaceView.setZOrderMediaOverlay() to do that.  The layers will be composited by the system before being rendered.
If you were using OpenGL ES rather than Canvas, it'd generally be more efficient to just redraw the background from a texture each time.  (If HWC runs out of overlays, that's essentially what SurfaceFlinger is doing anyway.)
See the "multi-surface test" in Grafika for an example of using multiple overlapping surfaces.


text:
Q: How can I use performance profiling with a Flutter add-to-app app using Flutter Attach? I have a Flutter app that I've added to an existing Android app. I'm trying to profile this app, but my issue is that I can't seem to maintain profile mode and also use Flutter Attach to actually view the Flutter DevTools window. My process is as follows -- select 'Profile app' from Android Studio. App starts in profiling mode. Then I close the app, start Flutter Attach from Android Studio, and re-open the app so Flutter Attach connects. However at this point it says 'Syncing files to [Device name]...' and when that's done, I can open the DevTools but it's back in debug mode. The same happens if I start up Flutter Attach waiting for a connection and then start the profiling mode, it seems to be the process of attaching and syncing files that puts it into debug mode. But I could be missing something. (The fact that I have to restart the app in order for Flutter Attach to see it is also weird, and possibly related I guess)

A: Mostly solved -- simply using flutter attach --profile in the command line will keep the app in profile mode and allow you to open Dev Tools in the browser. However, I'm still unsure if it is possible to use the --profile option in when starting Flutter Attach from Android Studio, which would allow Android Studio's performance windows to be used, which seem better than the browser ones.


text:
Q: Xcode iOS Simulator Scheme Selector Displaying The Simulator Identifier This is what I see on XCode 6.4. I removed all other versions of XCode and reinstalled 6.4. Let me know how to address this. Thanks.

A: All I have to do was to delete copies of the same simulator entry in the Simulator through the Manage Devices and that solved the issue for me.


text:
Q: C# - Jquery : Pass regular params and list> with $.post from view to controller I try to pass 'regular' parameters type from an ajax call ($.post) from a view to a controller which is supposed to receive those parameters plus a List>.
I need this List cause those parameters will be different from model.types, and the method in the controller dispatch all params in a switch case to private methods.
I tried several jquery objects builds, JSON.stringify, the array with indexes in the string (I know I can't name columns explicitly... part of my question) which always ends in the List> to null in the backend method.
The 'params' are visible in xhr debug, but the parameter _options is always null (ref controller method).
Here is my vars and my ajax call :
 function initDocumentsPreviewsActions() {
        $('.documents-list-preview-action').on('click', function () {

            if (xhrPreviewLoad != undefined)
                xhrPreviewLoad.abort();

            $('#documents-preview').html('

');
            documentCurrentIndex = $(this).data('btnindex');
            setDatatableRowActive();

            var documentType = $(this).data('documenttype');
            var adherentRessourceId = $(this).data('adherentressourceid');
            var annee = $(this).data('annee');
            var echeancier = $(this).data('echeancier');
            var destinataireid = $(this).data('destinataireid');
            var destinatairetypeid = $(this).data('destinatairetypeid');
            var emetteurid = $(this).data('emetteurid');
            var emetteurmandatid = $(this).data('emetteurmandatid');
            var trimestres = $(this).data('trimestres');
            var params = [
                { '_annee': '' + annee + '', '_echeancier': '' + echeancier + '', '_trimestres': '' + trimestres + '' }
            ];

xhrPreviewLoad = $.ajax({
                url: '/Documents/PreviewDocumentSingle',
                data: {
                    _documentType: documentType,
                    _adherentRessourceId: adherentRessourceId,
                    _annee: annee,
                    _destinataireId: destinataireid,
                    _destinataireType: destinatairetypeid,
                    _emetteurId: emetteurid,
                    _emetteurMandatId: emetteurmandatid,
                    _echeancier: echeancier,
                    _options: JSON.stringify(params)
                },
                dataType: 'json',
                type: 'POST'
            }).done(function (documentPartialView) {
                $('#documents-preview').html('');
                xhrPreviewLoad = undefined;
            });
        });
}

xhd Parameters in Firefox debugger :
_documentType   AppelCotisation
_adherentRessourceId    836
_annee  2018
_destinataireId 11
_destinataireType   Syndicat
_emetteurId 16289
_emetteurMandatId   5986
_echeancier False
_options    [{"_annee":"2018","_echeancier":"False","_trimestres":"undefined"}]

Controller method :
[HttpPost]
public JsonResult PreviewDocumentSingle(string _documentType, int _adherentRessourceId, int _destinataireId, string _destinataireType, int _emetteurId, int _emetteurMandatId, List<KeyValuePair<string, string>> _options)
        {
//(_options = null)
//some code
 return JsonResult
}

I already have done this a long time ago but I cannot put a hand or my brain on it. I'm sure it's a little thing.
I expect to get ALL my parameters correctly or being suggested to declare another List of a different type in the backend (and how to formalize it in front), or Array... well... any help is good to come.
But I'd really like to keep mus ctor in the backend as it is.

A: I finally findout myself how to solve this simple problem by changing to a Dictionnaray instead of a List> in my controller's method parameters and build a simple js object like this :
        var options = {};
        options['_annee'] = annee;
        options['_echeancier'] = echeancier;
        options['_trimestres'] = trimestres;


text:
Q: No signature of method: groovyx.net.http.HTTPBuilder.get() in intellij I am trying to use groovy's HTTPBuilder. I'm getting:

groovy.lang.MissingMethodException: No signature of method:
  groovyx.net.http.HTTPBuilder.get() is applicable for argument types:
  (groovyx.net.http.Method, groovyx.net.http.ContentType,
  com.company.sample.mypackage.myClient$_foo_closure1) values: [GET,
  application/json,
  com.company.sample.mypackage.myClient$_foo_closure1@7ee6e5bc] Possible
  solutions: grep(), get(java.util.Map), get(java.util.Map,
  groovy.lang.Closure), wait(), getUri(), any()

I think I'm using something almost exactly like the example on HTTPBuilder's documentation. I'm wondering if my problem is environmental with how I have my project set up in Intellij? It's the first time I've set up a maven project in intellij on my own so I'm suspicious.
package com.company.sample.mypackage
import groovyx.net.http.HTTPBuilder
import static groovyx.net.http.Method.GET
import static groovyx.net.http.ContentType.JSON

public class myClient {

    public static void main(String[] args) {
        foo();
    }

    public static void foo() {

        def http = new HTTPBuilder( 'http://foo.com' )
        http.get(GET, JSON) { <---EXCEPTION HAPPENS HERE
            uri.path = '/api/myapi'

            response.success = { resp, json ->
                println 'Successful'
            }
            response.failure = { resp ->
                println 'failure'
            }
        }

    }
}

Also note: I'm using java 1.7, groovy 2.4.3 and http-builder 0.6...in case that's part of the problem.

A: You should invoke request not get
public static void foo() {

    def http = new HTTPBuilder( 'http://foo.com' )
    http.request(GET, JSON) {
        uri.path = '/api/myapi'

        response.success = { resp, json ->
            println 'Successful'
        }
        response.failure = { resp ->
            println 'failure'
        }
    }
}


text:
Q: JSF: Conversion Error setting value '' for 'null Converter' I am getting the null Converter error for what I thought was a very simple scenario:

<ui:composition template="/template/template_v1.xhtml"
            xmlns="http://www.w3.org/1999/xhtml"
            xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:h="http://java.sun.com/jsf/html">

<h:form>

        <h:outputLabel for="txtUsername">Username:</h:outputLabel>
        <h:inputText id="txtUsername" name="Username"
                     value="#{userBean.user.id}"
                     styleClass="text" />
        <rich:message id="errorUsername" for="txtUsername"/>

</h:form>

/* The User Bean - simplified */
@ManagedBean
@ViewScoped
public class UserBean implements Serializable {
    private User user;

    public User getUser() {
        // Contains logic for reading a user from the database or creating a new
        // user object
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    }
/* The user Entity - Simplified */
@Entity
@Table(name = "user")
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "user_type", discriminatorType = DiscriminatorType.STRING)
public class User implements IEntity<String>, Serializable {
private static final long serialVersionUID = 1L;

    private String id;

    @Id
    @Column(name = "username", length = 50)
    @NotNull(message = "{userIdMandatory}")
    @Size(max = 50)
    public String getId() {
        return this.id;
    }

    public void setId(String id) {
        this.id = id;
    }

    }
/* The IEntity interface */
public interface IEntity<ID extends Serializable> {
    ID getId();
    void setId(final ID pId);
}

So essentially I'm trying to bind a string property of my user entity to a inputText field. As far as I'm concerned there should be no need for a conversion so I shouldn't be getting the error I'm seeing.
Interestingly, if I add the following getter and setter to my entity:
public String getTmpId() {
    return this.id;
}

public void setTmpId(String id) {
    this.id = id;
}

And then make the necessary changes to my view to bind to tmpId rather than id, everything works as expected.
This seems like a bug to me either to do with the fact that I am binding to a getter/setter defined in an interface, defined in a generic interface or because the getter is marked with the Id attribute. I would appreciate someone else's ideas however.
As an aside, I have inherited this design and don't particularly like it so I may just end up refactoring it to introduce a new username property rather than trying to use the Id.

A: To the best of my knowledge I believe this is caused by an obscure bug in BeanELResolver which is used to get the type of the property being bound to - rather than returning String it is returning Serializable, for which there is no converter and hence the error I am seeing.
It's not particularly elegant, but I have worked around this by adding a userId property to my userBean and then binding to that in my view instead of the Id property on the user entity. I then use that value to set the Id manually on the entity when I save it:

<ui:composition template="/template/template_v1.xhtml"
            xmlns="http://www.w3.org/1999/xhtml"
            xmlns:ui="http://java.sun.com/jsf/facelets"
                xmlns:h="http://java.sun.com/jsf/html">

<h:form>

        <h:outputLabel for="txtUsername">Username:</h:outputLabel>
        <h:inputText id="txtUsername" name="Username"
                     value="#{userBean.userId}"
                     styleClass="text" />
        <rich:message id="errorUsername" for="txtUsername"/>

/* The New User Bean - simplified */
@ManagedBean
@ViewScoped
public class UserBean implements Serializable {
    private string userId;
    private User user;

    public String getUserId() {
        return userId;
    }

    public void setUserId(String userId) {
        this.userId = userId;
    }

    public User getUser() {
        // Contains logic for reading a user from the database or creating a new
        // user object
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public void saveUser() {
        if (user.getId() == null) {
            user.setId(userId);
        }
        // Actual saving omitted for brevity
    }
}


text:
Q: How to validate react input fields with some custom validation I am working with react and making some new input fields dynamically, and using React-gook-form for validation.
What I am doing is -

*

*I have one dropdown in which I have numbers as dropdown, like 1,2,3,4

*So which ever dropdown user is selecting I am creating that much input field

*if user selects 3 then 3 input fields

What I am trying to achieve is

*

*When user create two input fields i do not want both of them to have same input.

*Like if first input is having D as input then the second one should not take D in second one.

PS- here just for minimal code i am creating only one set of input, like first name
It can be when i select 2 then I can create two set of inputs having Fname and Lname in each set so there both fname should not take same value and same goes for lname.
What I have done
this one to hold the state, initial one is selected and one input is created.
const [initialSet, setinitialSet] = useState(1);

On select change doing this
    const Select_change = (e) => {
    let val = parseInt(e.target.value);
    setinitialSet(val);
  };

Now using that initial state to loop my elements to create input fields

      {[...Array(initialSet).keys()].map((li, index) => (

            <input
              type="text"
              name={`data[${index}].name`}
              id={"name" + index}
              className="form-control"
              placeholder="F Name"
              ref={register({ required: `F name ${index} is required` })}
            />

              F Name

            {errors.data && errors.data[index] && errors.data[index].name && (

                  {errors.data[index].name.message}

            )}

      ))}

Now I just want to validate the fname so that two input fields of f name should not have same input.
Code sandbox link
I have full working code in my code sandbox

A: You can use an array of inputs so when you select 3 you create an array with 3 elements that will contain the data.
const [initialSet, setinitialSet] = useState([]);
and here's the creation process:
const Select_change = (e) => {
  let val = parseInt(e.target.value);
  setinitialSet( new Array(val));
}

optionally you can initialise the array to zeros if you want
setinitialSet( new Array(val).fill(0) );
When you loop over the inputs you will use the index of the element in the array.
You can even store names and errors in each element of the element if you want a complicated logic.


text:
Q: Magento promotions shopping cart price rule - combined simple and downloadable products Hope someone can help here...
Magento 1.7.0.2
I have created a very simple shopping cart price rule.
If total quantity in cart is greater than 1 > apply 10% discount.
This works fine, if i have 2 simple products in my cart or if i have 2 downloadable products in cart.
But if i have 1 simple and 1 downloadable, no discount is added.
This worked fine on an older version of magento.
I have tried to change to rule, to look at the subtotal of the cart, but it is stille the same.
Hope someone, can give me an idear of why this is happening.
Thanks.

A: just for confirmation as it is working for me
you got to Promotions > Shopping Basket Rules > Then create new rule.
under conditions set the following:
If ALL  of these conditions are TRUE : Total Items Quantity  equals or greater than  3
Then under actions:
for the Apply dropdown: choose Fixed amount discount for the whole basket then below this add your percentage.
This is the basic requirement. There are more settings you can / tweak apply here.
Hope that helps?


text:
Q: Add a unique File ID to PDF documents received I need to track PDF documents RECEIVED.      I can keep a list of the documents in a database, however sometimes the documents get renamed or moved, so the file path to the PDF is not always reliable.
For other document types, I sometimes add a unique ID as metadata, so that I can recognize that a file that was moved and/or renamed is the same as one seen previously.
I am looking for a solution that will work on Windows 10, and would prefer a solution based on Node.js, although Python would also be acceptable.
The documents are received from many different sources, and I do not have the option of requiring the source of the document to add a unique identifier.
I have use IPTCinfo in this way for media files, but (as far as I know) that can't be used with PDFs.
I am looking for something similar that can be used with PDFs.

A: Use md5sum:
import os

def check_md5sum(file_path):
    md5sum = os.system(f'md5sum {file_path}')
    return md5sum


text:
Q: api examples have bad callback syntax for safari and mobile chrome So in this example, the callback function syntax will break on Safari and mobile Chrome and Safari.
utils.api.cart.getContent(options, (err, response) => {
  $modalOverlay.hide();
  $cartCounter.text(response.data.cart.items.length + " items in your cart");
  $modalContent.html(response.content);
});

Should be written as ...
utils.api.cart.getContent(options, function(err, response) {
  $modalOverlay.hide();
  $cartCounter.text(response.data.cart.items.length + " items in your cart");
  $modalContent.html(response.content);
});

A: The code examples are using ES6 syntax. You can see other examples here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions


text:
Q: How to print the contents of a two-dimensional array of characters? I'm trying to print an array of characters in C but i can't print everything.
I want to print :
b1
b2
My code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main() {
  char def[3][10];     //define a multidimensional array of characters
  strcpy(def[0],"b1"); //insert "b1" at first line
  strcpy(def[1],"b2"); //insert "b2" at first line
  printf("%s",def);    //print everything?
}

The above code prints just b1. I already tried :
printf("%s",def[0]);
printf("%s",def[1]);

But i have error "invalid use of array with unspecified bounds"

A: printf("%s", def);

%s conversion specification expects a string. def is an array of strings and not a string.
To print the first string do this:
printf("%s", def[0]);

if you want to print the second string then do this:
printf("%s", def[1]);

and if you want to print both strings:
printf("%s%s", def[0], def[1]);

To print all strings in your array:
for (i = 0; i < sizeof def / sizeof *def; i++)
{
    printf("%s", def[i]);
}

A: You first initialize array with syntax like so whole array gets null value.
and then do the same procedure you are able to get your strings at output.
syntax:
char def[3][10]={};
or
first define this array and then by bzero function make whole array to zero value.
bzero(def,sizeof(def));
you need to include stdlib.h header file in your program.

A: You could print a whole multi-dimensional array of char as a single string, with a single call:
printf("%s", (char*) multiDimensionalArray);

Because elements of a multi-dimensional array are contiguos. But, exactly as simple arrays, printf stops at the first termination character, so it's usually pointless because we almost always have a termination character at the end of each "row" just like you, or some uninitialized garbage.
char def[3][2];

memcpy(def[0], "b1", 2);
memcpy(def[1], "b2", 2);

def[2][0] = '\0';

printf("%s", (char*) def);  // print everything

But use arrays this way is painful, what you need is a loop over the array.
(you can simply use *puts to print strings)


text:
Q: Different spectrogram between audio_ops and tf.contrib.signal I am trying to update the feature extraction pipeline of an speech command recognition model replacing the function audio_ops.audio_spectrogram() by tf.contrib.signal.stft(). I assumed that they were equivalent, but I am obtaining different spectrogram values with the same input audio. Could someone explain the relation between the two methods, or whether it is possible to obtain the same results using tf.contrib.signal.stft()?
My code:
1) audio_ops method:
from tensorflow.contrib.framework.python.ops import audio_ops
import tensorflow as tf
import numpy as np
from tensorflow.python.ops import io_ops

#WAV audio loader
wav_filename_placeholder_ = tf.placeholder(tf.string, [], name='wav_filename')
wav_loader = io_ops.read_file(wav_filename_placeholder_)
sample_rate = 16000
desired_samples = 16000 #1 sec audio
wav_decoder = audio_ops.decode_wav(wav_loader, desired_channels=1, desired_samples=desired_samples)

#Computing the spectrograms
spectrogram = audio_ops.audio_spectrogram(wav_decoder.audio,
                                              window_size=320,
                                              stride=160,
                                              magnitude_squared=False)
with tf.Session() as sess:
    feed_dict={wav_filename_placeholder_:"/<folder_path>/audio_sample.wav"}
    #Get the input audio and the spectrogram
    audio_ops_wav_decoder_audio, audio_ops_spectrogram = sess.run([wav_decoder.audio, spectrogram], feed_dict)

2) tf.contrib.signal method:
#Input WAV audio (will be initialized with the same audio signal: wav_decoder.audio )
signals = tf.placeholder(tf.float32, [None, None])

#Compute the spectrograms and get the absolute values
stfts = tf.contrib.signal.stft(signals,
                               frame_length=320,
                               frame_step=160,
                               fft_length=512,
                               window_fn=None)
magnitude_spectrograms = tf.abs(stfts)
with tf.Session() as sess:
    feed_dict = {signals : audio_ops_wav_decoder_audio.reshape(1,16000)}
    tf_original, tf_stfts, tf_spectrogram, = sess.run([signals, stfts, magnitude_spectrograms], feed_dict)

Thank you in advance

A: Found these helpful comments in github that discuss the differences:
https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-345741527
https://github.com/tensorflow/tensorflow/issues/11339#issuecomment-443553788

You can think of audio_ops.audio_spectrogram and audio_ops.mfcc as
  "fused" ops (like fused batch-norm or fused LSTM cells that TensorFlow
  has) for the ops in tf.contrib.signal. I think the original motivation
  of them was that a fused op makes it easier to provide mobile support.
  I think long term it would be nice if we removed them and provided
  automatic fusing via XLA, or unified the API to match
  tf.contrib.signal API, and provided fused keyword arguments to
  tf.contrib.signal functions, like we do for
  tf.layers.batch_normalization.
audio_spectrogram is a C++ implementation of an STFT, while
  tf.signal.stft uses TensorFlow ops to compute the STFT (and thus has
  CPU, GPU and TPU support).
The main cause of difference between them is that audio_spectrogram
  uses fft2d to compute FFTs while tf.contrib.signal.stft uses Eigen
  (CPU), cuFFT (GPU), and XLA (TPU). There is another very minor
  difference, which is that the default periodic Hann window used by
  each is slightly different. tf.contrib.signal.stft follows
  numpy/scipy's definition.


text:
Q: message sent to deallocated instance After more than one day reading questions and trying to apply answers, I must ask more help.
My ios6 app has a table view on the main screen. After selecting a cell, we access a view controller with a UINavigationBar which has a custom "Back" button calling this method :
- (IBAction)goback:(id)sender {
    [SVProgressHUD dismiss];
    if(self.presentingViewController) {
        NSLog(@"  Dismissing View Controller: %@.", self.presentingViewController);
        [self dismissViewControllerAnimated:NO completion:nil];
    }
}

Usually, this method works well. It only crashes if we press the Back button very quickly, just after the loading of the content (using json and AFNetworking). 5 seconds later, the back button is working fine, but if we click it right after the loading, we get this error :
[28103:c07]   Dismissing View Controller:     <UITabBarController: 0x7578170>.
[28103:c07] *** -[CustomViewController respondsToSelector:]: message sent to deallocated instance 0x1257cf70

Obviously, it's a memory problem. That's why I tried to track "Zombies". Profiling my app, I get this report. It shows that there is too much release, but I can't tell which one is the culprit.
Does anyone know how to interpret this report ?
Is this line normal ?
84  0x10291ff0  Release 3   MyApp   __destroy_helper_block_

Please tell me if any further information is needed. I thank you for your help.
#   Address Event Type  RefCt   Responsible Library Responsible Caller
0   0x10291ff0  Malloc  1   UIKit   -[UIClassSwapper initWithCoder:]
1   0x10291ff0  Retain  2   UIKit   UINibDecoderDecodeObjectForValue
2   0x10291ff0  Retain  3   UIKit   -[UIRuntimeConnection initWithCoder:]
3   0x10291ff0  Retain  4   UIKit   -[UIRuntimeConnection initWithCoder:]
4   0x10291ff0  Retain  5   UIKit   UINibDecoderDecodeObjectForValue
5   0x10291ff0  Retain  6   UIKit   UINibDecoderDecodeObjectForValue
6   0x10291ff0  Retain  7   UIKit   -[UIStoryboardScene setSceneViewController:]
7   0x10291ff0  Retain  8   UIKit   -[UINib instantiateWithOwner:options:]
8   0x10291ff0  Release 7   UIKit   -[UINibDecoder finishDecoding]
9   0x10291ff0  Release 6   UIKit   -[UIRuntimeConnection dealloc]
10  0x10291ff0  Release 5   UIKit   -[UIRuntimeConnection dealloc]
11  0x10291ff0  Release 4   UIKit   -[UINibDecoder finishDecoding]
12  0x10291ff0  Release 3   UIKit   -[UINibDecoder finishDecoding]
13  0x10291ff0  Release 2   UIKit   -[UINibDecoder finishDecoding]
14  0x10291ff0  Retain  3   UIKit   -[UIStoryboardSegue initWithIdentifier:source:destination:]
15  0x10291ff0  Retain  4   UIKit   -[UIViewController setChildModalViewController:]
16  0x10291ff0  Retain  5   UIKit   -[UIApplication _addViewControllerForLockingStatusBarTintColor:]
17  0x10291ff0  Retain  6   UIKit   -[UINib instantiateWithOwner:options:]
18  0x10291ff0  Retain  7   UIKit   +[UIProxyObject addMappingFromIdentifier:toObject:forCoder:]
19  0x10291ff0  Retain  8   UIKit   -[UINib instantiateWithOwner:options:]
20  0x10291ff0  Retain  9   UIKit   +[UIProxyObject addMappingFromIdentifier:toObject:forCoder:]
21  0x10291ff0  Retain  10  UIKit   -[UIProxyObject initWithCoder:]
22  0x10291ff0  Retain  11  UIKit   -[UIRuntimeConnection initWithCoder:]
23  0x10291ff0  Retain  12  UIKit   -[UIRuntimeConnection initWithCoder:]
24  0x10291ff0  Retain  13  UIKit   -[UIRuntimeConnection initWithCoder:]
25  0x10291ff0  Retain  14  UIKit   -[UIRuntimeConnection initWithCoder:]
26  0x10291ff0  Retain  15  UIKit   -[UIRuntimeConnection initWithCoder:]
27  0x10291ff0  Retain  16  UIKit   -[UIRuntimeConnection initWithCoder:]
28  0x10291ff0  Retain  17  UIKit   -[UIRuntimeConnection initWithCoder:]
29  0x10291ff0  Retain  18  UIKit   -[UIRuntimeConnection initWithCoder:]
30  0x10291ff0  Retain  19  UIKit   -[UIRuntimeConnection initWithCoder:]
31  0x10291ff0  Retain  20  UIKit   -[UIRuntimeConnection initWithCoder:]
32  0x10291ff0  Retain  21  UIKit   -[UIRuntimeConnection initWithCoder:]
33  0x10291ff0  Retain  22  UIKit   -[UIRuntimeConnection initWithCoder:]
34  0x10291ff0  Retain  23  UIKit   -[UIRuntimeConnection initWithCoder:]
35  0x10291ff0  Retain  24  UIKit   -[UIRuntimeConnection initWithCoder:]
36  0x10291ff0  Retain  25  UIKit   -[UIRuntimeConnection initWithCoder:]
37  0x10291ff0  Retain  26  UIKit   -[UIRuntimeConnection initWithCoder:]
38  0x10291ff0  Retain  27  UIKit   -[UIProxyObject initWithCoder:]
39  0x10291ff0  Retain  28  UIKit   -[UIRuntimeConnection initWithCoder:]
40  0x10291ff0  Retain  29  UIKit   -[UIRuntimeConnection initWithCoder:]
41  0x10291ff0  Retain  30  UIKit   UINibDecoderDecodeObjectForValue
42  0x10291ff0  Retain  31  UIKit   UINibDecoderDecodeObjectForValue
43  0x10291ff0  Retain  32  UIKit   UINibDecoderDecodeObjectForValue
44  0x10291ff0  Retain  33  UIKit   UINibDecoderDecodeObjectForValue
45  0x10291ff0  Release 32  UIKit   -[UINib instantiateWithOwner:options:]
46  0x10291ff0  Release 31  UIKit   +[UIProxyObject removeMappingsForCoder:]
47  0x10291ff0  Release 30  UIKit   +[UIProxyObject removeMappingsForCoder:]
48  0x10291ff0  Release 29  UIKit   -[UINibDecoder finishDecoding]
49  0x10291ff0  Release 28  UIKit   -[UINibDecoder finishDecoding]
50  0x10291ff0  Release 27  UIKit   -[UINibDecoder finishDecoding]
51  0x10291ff0  Release 26  UIKit   -[UINibDecoder finishDecoding]
52  0x10291ff0  Release 25  UIKit   -[UINibDecoder finishDecoding]
53  0x10291ff0  Release 24  UIKit   -[UINibDecoder finishDecoding]
54  0x10291ff0  Release 23  UIKit   -[UIRuntimeConnection dealloc]
55  0x10291ff0  Release 22  UIKit   -[UIRuntimeConnection dealloc]
56  0x10291ff0  Release 21  UIKit   -[UIRuntimeConnection dealloc]
57  0x10291ff0  Release 20  UIKit   -[UIRuntimeConnection dealloc]
58  0x10291ff0  Release 19  UIKit   -[UIRuntimeConnection dealloc]
59  0x10291ff0  Release 18  UIKit   -[UIRuntimeConnection dealloc]
60  0x10291ff0  Release 17  UIKit   -[UIRuntimeConnection dealloc]
61  0x10291ff0  Release 16  UIKit   -[UIRuntimeConnection dealloc]
62  0x10291ff0  Release 15  UIKit   -[UIRuntimeConnection dealloc]
63  0x10291ff0  Release 14  UIKit   -[UIRuntimeConnection dealloc]
64  0x10291ff0  Release 13  UIKit   -[UIRuntimeConnection dealloc]
65  0x10291ff0  Release 12  UIKit   -[UIRuntimeConnection dealloc]
66  0x10291ff0  Release 11  UIKit   -[UIRuntimeConnection dealloc]
67  0x10291ff0  Release 10  UIKit   -[UIRuntimeConnection dealloc]
68  0x10291ff0  Release 9   UIKit   -[UIRuntimeConnection dealloc]
69  0x10291ff0  Release 8   UIKit   -[UIRuntimeConnection dealloc]
70  0x10291ff0  Release 7   UIKit   -[UIRuntimeConnection dealloc]
71  0x10291ff0  Release 6   UIKit   -[UIRuntimeConnection dealloc]
72  0x10291ff0  Release 5   Foundation  -[NSAutoreleasePool drain]
73  0x10291ff0  Retain  6   MyApp   -[SSPullToRefreshView initWithScrollView:delegate:]
74  0x10291ff0  Release 5   MyApp   -[SSPullToRefreshView initWithScrollView:delegate:]
75  0x10291ff0  Retain  6   UIKit   -[UIWindow _setRotatableClient:toOrientation:updateStatusBar:duration:force:isRotating:]
76  0x10291ff0  Retain  7   libsystem_sim_blocks.dylib  _Block_object_assign
77  0x10291ff0  Retain  8   libsystem_sim_blocks.dylib  _Block_object_assign
78  0x10291ff0  Release 7   Foundation  __NSFireDelayedPerform
79  0x10291ff0  Release 6   UIKit   -[UIStoryboardSegue dealloc]
80  0x10291ff0  Release 5   Foundation  __NSFireDelayedPerform
81  0x10291ff0  Release 4   UIKit   -[UIStoryboardScene dealloc]
82  0x10291ff0  Retain  5   UIKit   __91-[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]_block_invoke_0238
83  0x10291ff0  Release 4   UIKit   __destroy_helper_block_250
84  0x10291ff0  Release 3   MyApp   __destroy_helper_block_
85  0x10291ff0  Release 2   UIKit   -[UIWindowController transitionViewDidComplete:fromView:toView:removeFromView:]
86  0x10291ff0  Retain  3   UIKit   -[UIViewController _dismissViewControllerWithTransition:from:completion:]
87  0x10291ff0  Retain  4   UIKit   __91-[UIWindowController transition:fromViewController:toViewController:target:didEndSelector:]_block_invoke_0238
88  0x10291ff0  Retain  5   UIKit   -[UIViewController _didFinishDismissTransition]
89  0x10291ff0  Retain  6   UIKit   -[UIApplication _removeViewControllerForLockingStatusBarTintColor:]
90  0x10291ff0  Release 5   UIKit   -[UIApplication _removeViewControllerForLockingStatusBarTintColor:]
91  0x10291ff0  Release 4   UIKit   -[UIApplication _removeViewControllerForLockingStatusBarTintColor:]
92  0x10291ff0  Release 3   UIKit   -[UIViewController setChildModalViewController:]
93  0x10291ff0  Release 2   UIKit   -[UIViewController _didFinishDismissTransition]
94  0x10291ff0  Release 1   UIKit   -[UIWindowController transitionViewDidComplete:fromView:toView:removeFromView:]
95  0x10291ff0  Release 0   UIKit   -[UIViewController _dismissViewControllerWithTransition:from:completion:]
96  0x10291ff0  Zombie  -1  UIKit   -[UIScrollView(UIScrollViewInternal) _delegateScrollViewAnimationEnded]

-- edit --
Here is how I use AFNetworking to retrieve data on each page of my app :
[[APIClient sharedClient] getPath:request
                            parameters:params
                               success:^(AFHTTPRequestOperation *operation, id responseObject) {
                                   [SVProgressHUD dismiss];
                                   [self.pullToRefreshView finishLoading];

                                   ... read data ...

                               } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                                   [SVProgressHUD showErrorWithStatus:error.localizedDescription];
                               }];

There is no will/didUnload methods, only this one:
- (void)viewWillDisappear:(BOOL)animated{
    [SVProgressHUD dismiss];
    [_pubnub unsubscribeFromChannel: self.pro.channel];
}


text:
Q: How to configure my TL-WR741N to forward DNS from my Chromecast to Unblock-US DNS servers I am looking for help.  I live in Czech Republic and am currently subscribed to Netflix by using www.unblock-us.com.
I have now acquired a Chromecast, however I am unable to use it with Netflix as the Chromecast has the Google DNS servers hardcoded into it.
I have read that it is possible to make to changes to your server so that the Google servers are bypassed and you can use for example in my case the unblock-us servers.
I have tried to access my router using telnet but port 23 is blocked.
I am able to log into the router via my browser but I have no idea how to make these changes.

A: You can set your router to use whatever DNS server you like, but if your Chromecast has hardcoded DNS servers (probably 8.8.8.8 and 8.8.4.4), it won't even ask your router for DNS info and will continue to resolve to wherever its DNS server tells it to.
You can capture any internal DNS traffic from your chromecast and redirect it to the unblock-us servers but most routers won't support this functionality, I know mine doesn't.
DD-WRT is a router firmware that you can install and will perform what you are trying to achieve. It is not overly difficult to install but must be careful and you run the risk of bricking your router. If you go down this road I recommend you read all the DD-WRT documentation related to your router carefully before installing anything.

A: You can try the instruction here, but before that, make sure that your device supports dd-wrt.
I was in the exactly same situation as you, and I had to get a new router, and installed tomato firmware before I could do the configuration, and even so, the router was unstable.


text:
Q: How to use Pandas groupby apply() without adding an extra index I very often want to create a new DataFrame by combining multiple columns of a grouped DataFrame. The apply() function allows me to do that, but it requires that I create an unneeded index:
 In [359]: df = pandas.DataFrame({'x': 3 * ['a'] + 2 * ['b'], 'y': np.random.normal(size=5), 'z': np.random.normal(size=5)})

 In [360]: df
 Out[360]:
    x         y         z
 0  a  0.201980 -0.470388
 1  a  0.190846 -2.089032
 2  a -1.131010  0.227859
 3  b -0.263865 -1.906575
 4  b -1.335956 -0.722087

 In [361]: df.groupby('x').apply(lambda x: pandas.DataFrame({'r': (x.y + x.z).sum() / x.z.sum(), 's': (x.y + x.z ** 2).sum() / x.z.sum()}))
 ---------------------------------------------------------------------------
 ValueError                                Traceback (most recent call last)
 /home/emarkley/work/src/partner_analysis2/main.py in <module>()
 ----> 1 df.groupby('x').apply(lambda x: pandas.DataFrame({'r': (x.y + x.z).sum() / x.z.sum(), 's': (x.y + x.z ** 2).sum() / x.z.sum()}))

 /usr/local/lib/python3.2/site-packages/pandas-0.8.2.dev-py3.2-linux-x86_64.egg/pandas/core/groupby.py in apply(self, func, *args, **kwargs)
     267         applied : type depending on grouped object and function
     268         """
 --> 269         return self._python_apply_general(func, *args, **kwargs)
     270
     271     def aggregate(self, func, *args, **kwargs):

 /usr/local/lib/python3.2/site-packages/pandas-0.8.2.dev-py3.2-linux-x86_64.egg/pandas/core/groupby.py in _python_apply_general(self, func, *args, **kwargs)
     417             group_axes = _get_axes(group)
     418
 --> 419             res = func(group, *args, **kwargs)
     420
     421             if not _is_indexed_like(res, group_axes):

 /home/emarkley/work/src/partner_analysis2/main.py in <lambda>(x)
 ----> 1 df.groupby('x').apply(lambda x: pandas.DataFrame({'r': (x.y + x.z).sum() / x.z.sum(), 's': (x.y + x.z ** 2).sum() / x.z.sum()}))

 /usr/local/lib/python3.2/site-packages/pandas-0.8.2.dev-py3.2-linux-x86_64.egg/pandas/core/frame.py in __init__(self, data, index, columns, dtype, copy)
     371             mgr = self._init_mgr(data, index, columns, dtype=dtype, copy=copy)
     372         elif isinstance(data, dict):
 --> 373             mgr = self._init_dict(data, index, columns, dtype=dtype)
     374         elif isinstance(data, ma.MaskedArray):
     375             mask = ma.getmaskarray(data)

 /usr/local/lib/python3.2/site-packages/pandas-0.8.2.dev-py3.2-linux-x86_64.egg/pandas/core/frame.py in _init_dict(self, data, index, columns, dtype)
     454         # figure out the index, if necessary
     455         if index is None:
 --> 456             index = extract_index(data)
     457         else:
     458             index = _ensure_index(index)

 /usr/local/lib/python3.2/site-packages/pandas-0.8.2.dev-py3.2-linux-x86_64.egg/pandas/core/frame.py in extract_index(data)
    4719
    4720         if not indexes and not raw_lengths:
 -> 4721             raise ValueError('If use all scalar values, must pass index')
    4722
    4723         if have_series or have_dicts:

 ValueError: If use all scalar values, must pass index

 In [362]: df.groupby('x').apply(lambda x: pandas.DataFrame({'r': (x.y + x.z).sum() / x.z.sum(), 's': (x.y + x.z ** 2).sum() / x.z.sum()}, index=[0]))
 Out[362]:
             r         s
 x
 a 0  1.316605 -1.672293
 b 0  1.608606 -0.972593

Is there any way to use apply() or some other function to get the same results without the extra index of zeros?

A: You're producing an aggregate r and s value per group, so you should be using Series here:
In [26]: df.groupby('x').apply(lambda x:
             Series({'r': (x.y + x.z).sum() / x.z.sum(),
                     's': (x.y + x.z ** 2).sum() / x.z.sum()}))
Out[26]:
           r           s
x
a  -0.338590   -0.916635
b  66.655533  102.566146


text:
Q: How to set version property on domain object creation? I'm trying to model a parent/child relationship.
I have the following domain class:
package test
class Person {
Person mother
Person father
String name
static hasOne = [father: Person, mother: Person]
    static constraints = {
        name()
        father(nullable:true)
        mother(nullable:true)
    }
    def Set<Person> children(){
        return Person.findAllByMother(this)
    }
}

I have performed generate-all
However, if I try to create a new Person, I get the following error:
Message: Parameter "#2" is not set; SQL statement:
insert into person (id, version, father_id, mother_id, name) values (null, ?, ?, ?, ?) [90012-164]
    Line | Method
->>  329 | getJdbcSQLException   in org.h2.message.DbException

Where should the version parameter be generated?  I thought that this should be generated auto-magically during the save call.
UPDATE: The issue seems to be related to the father/mother relationship, since removing it and re-generating views means that elements are persisted ok.

A: The issue seems to be related to the fact that I had tried to create a di-directional relationship in the class.  This in fact is not required.  There is a uni directional relationship Person -> father and Person -> mother.  The inverse is calculated under children (which I shall extend to include father as well.)
My final class is:
package test
class Person {
    int id
    Person mother
    Person father
    String name
    static constraints = {
        name()
        father(nullable:true)
        mother(nullable:true)
    }

    def Set<Person> children(){
         return Person.findAllByMother(this)
    }
}

I'm still new to Grails.


text: Q: Will QString::fromLocal8Bit() use UTF-8 when needed? UTF-8 is an 8-bit encoding. User can have LANG set to for example ja_JP.utf8, so this makes this then also a "local", Japanese encoding. All things seem to match, but documentation only states that QTextCodec::codecForLocale() will be used, and its documentation doesn't say if it's only about Latin1 vs Latin2 vs etc. (although "codec for locale" sounds like arbitrary codec for the LANG setting would be used, even non-8bit one, is also this true?).


text:
Q: Can't get pushes list while passing "searchCriteria.refName=master" parameter in Azure DevOps Here is my code snippet:
/*
 * Get Pushes List Doc: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/list?view=azure-devops-rest-5.1
 */
function getPushesList(){
    global $baseUri;
    global $organization;
    global $project;
    global $repositoryId;
    global $branch;
    global $username;
    global $accessToken;
    $url = $baseUri . '/' . $organization . '/' . $project . '/_apis/git/repositories/' . $repositoryId . '/pushes?api-version=5.1';
    $queryArr = [
        'searchCriteria.refName' => $branch,
        'searchCriteria.includeRefUpdates' => 'false',
        '$top' => 1,
    ];
    $queryStr = http_build_query($queryArr);
    $authorization = 'basic ' . base64_encode($username . ':' . $accessToken);
    $url .= '&' . urldecode($queryStr);
    //$url sample: https://dev.azure.com/kmx3ecup/img_bed/_apis/git/repositories/img_bed/pushes?api-version=5.1&searchCriteria.refName=&searchCriteria.includeRefUpdates=false&$top=1
    // echo $url;exit;
    $ch = curl_init();
    $options = [
        CURLOPT_URL => $url,
        CURLOPT_HTTPHEADER => [
            'authorization: ' . $authorization
        ],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_SSL_VERIFYPEER => false,
        CURLOPT_SSL_VERIFYHOST => 0,
    ];
    //In case you need a proxy
    // $options[CURLOPT_PROXY] = 'http://127.0.0.1:1087';
    curl_setopt_array($ch, $options);
    $retArr = curl_exec($ch);
    if(curl_errno($ch)){
        echo 'Error: ' . curl_error($ch);
    }
    curl_close($ch);
    return $retArr;
}

$baseUri = 'https://dev.azure.com';

$organization = '<YOUR_ORGANIZATION>';
$project = '<YOUR_PROJECT_NAME>';
$repositoryId = '<YOUR_REPOSITORY_ID_OR_REPOSITORY_NAME>';
$branch = '';
//Question: if I set $branch to "master", then it returns: {"count":0,"value":[]}, but actually master branch have many files.
//DOC: https://learn.microsoft.com/en-us/rest/api/azure/devops/git/pushes/list?view=azure-devops-rest-5.1
//$branch = 'master';
$username = '<YOUR_USERNAME>';
$accessToken = '<YOUR_ACCESS_TOKEN>';
$reponseJson = getPushesList();
echo $reponseJson;

Question: If I set $branch to "master",it returns: {"count":0,"value":[]}, but actually master branch have many files, and if I set $branch to empty string, it returns normal result,  but, I have only one branch, that is master branch, I mean if I set branch to empty string, it's still getting files from the default branch(master branch) right?

A: If you want to use parameter searchCriteria.refName to query the master branch, you should set $branch to refs/heads/master which is the ref name for master branch.
If you set $branch to empty string, the result is not from the default barnch. You will get the pushes lists ordered by push id in the repo's level.
In your case, it will return the lists of master branch, since you only have one branch.


text:
Q: Undo local changes that exist in a shelveset? Problem
Often times, while a team is repairing one part of the code base, we have to have a shelveset of theirs locally so that we can continue working. However, in the process of working I need to shelve my changes for a code review for example. This isn't too much of a problem because I can get their shelveset first, exclude those changes, make my changes, and shelve them.
However, when they have checked in their changes there is no good way for me (except by hand) to simply undo their shelveset (the files that exist in that shelveset specifically). At least I haven't found a way, and so that's why I'm asking.
Research
So based on the documentation here, there are no commands in tfpt that would do this. Further, based on the documentation here, there are no commands in tf that would do this either. I drilled into the Shelvesets and Undo commands as well looking for possible switches.

A: Starting in Premium version of Visual Studio there are a feature to Suspend your work and after Resume it. You can read the documentarion about it here