text:
Q: Double ID tag in Materialize css Joomla I am currently making a template in Joomla using Materialize CSS as the framework. I get stuck with the part where I make a dropdown menu in Joomla. The HTML should go as followed (as explained on the documentation page of Materialize)

one

two

three

 Dropdownarrow_drop_down

My index.php goes as follows:

                <?php echo $logo; ?>
                    <?php if ($this->params->get('sitedescription')) : ?>
                        <?php echo '
' . htmlspecialchars($this->params->get('sitedescription')) . '
'; ?>
                <?php endif; ?>

                <jdoc:include type="modules" name="position-1" style="none" />

                        <?php echo $logo; ?>
                            <?php if ($this->params->get('sitedescription')) : ?>
                                <?php echo '
' . htmlspecialchars($this->params->get('sitedescription')) . '
'; ?>
                        <?php endif; ?>

                <jdoc:include type="modules" name="position-1" style="none" />

The problem is that I use the menu module twice because of the mobile menu. An ID tag can only be used once so the dropdown doesn't work.
Does anyone know how I can fix this?

A: Its not a good idea to have the same module position duplicated in the template multiple times as it will render the same markup every time.
Instead, the best approach is to create a copy of the menu module and publish it to your mobile menu position.

*

*In Joomla Admin, duplicate the current menu module

*Publish the duplicated menu module to a new position e.g. "mobile-nav". All other settings for this duplicated module can be identical to the original (desktop) menu module.

*Update your template code to include position for "mobile-nav" where the mobile navigation should be displayed.

Update template code for new module position (just swap out position-1 with mobile-nav):

            <?php echo $logo; ?>
                <?php if ($this->params->get('sitedescription')) : ?>
                    <?php echo '
' . htmlspecialchars($this->params->get('sitedescription')) . '
'; ?>
            <?php endif; ?>

    <jdoc:include type="modules" name="mobile-nav" style="none" />


text:
Q: how am i supposed to handle this? i am saving a product in my create action, once it is saved i would like it to redirect it to show action like this.
if @product.save
  redirect_to :action => :show

and my show action displays the content of the product with the requested id. Since I am redirecting, I would lose all my instance variables. So how to pass the id? Should I use flash for this? Or is there a better way of doing this

A: The scaffold generator produces code like:
if @product.save
  redirect_to @product
else
  render :new
end

Rails will look to use a product_path pointing to the show action with the :id being @product.id
This assumes you have, in your config/routes.rb
Rails 2.X
map.resources :products

Rails 3.X
resources :products

redpajama_set_name: RedPajamaStackExchange


text:
Q: Get messageID from pdus object My app listens to new sms'n. Now When I receive a new one I create a SmsMessage. For doing further operations on this, I need the Id of the message. So I query the content resolver like this:
 final Bundle bundle = intent.getExtras();

    try {

        if (bundle != null) {
            //get the protocol discription unit ( SMSs)
            final Object[] pdusObj = (Object[]) bundle.get("pdus");

            for (int i = 0; i < pdusObj.length; i++) {

                SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
                String phoneNumber = currentMessage.getDisplayOriginatingAddress();
                String message = currentMessage.getDisplayMessageBody();
                long time_rcv = currentMessage.getTimestampMillis();

                String [] relevantColumns = {"_id", "address", "body", "date_sent"};
                Cursor cursor = context.getContentResolver().query(
                        Uri.parse("content://sms/inbox"),
                        relevantColumns,
                        "address = '" + phoneNumber + "' AND body = '" + message
                                + "' AND date_sent = '" + time_rcv + "'",
                        null,
                        null);

                if (cursor != null && cursor.moveToFirst()) {
                    int id = Integer.valueOf(cursor.getString(0));
                    Log.d(TAG,"ID SMS: " + id);
                }
                else
                    Log.e(TAG,"Failed to find ID");

                Log.i(TAG, "FROM: " + phoneNumber + "; MSG: " + message);

                Toast.makeText(context, "From: " + phoneNumber + ", MSG: " + message, Toast.LENGTH_LONG).show();
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "Exception receiver" + e);

    }

Whatever happens it never finds the message.

A: My code was correct. The only problem is, that the sms isn't in the sms/inbox until my receivebroadcast is finished. So the next time you run the code and fill the fields manually the code finds the sms and gives you the id.


text:
Q: how to make this lazyload scrolling working with provider it take about 7 days trying make a working example for lazyload listview with provider in flutter with real world example and it's still not working because i think something is missing
As a note : the first load , works good and when i scroll it's print (scroll) but nothing happened it's still in the same page
if i try to return _todolist variable in the _onScrollUpdated it not change page correctly and after three times i see this error

E/flutter ( 7713): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)]
Unhandled Exception: type 'String' is not a subtype of type
'List' E/flutter ( 7713): #0      TodoService.fetchTodos
(package:flutter_todo_provider/services/todo_service.dart:32:21)

json example
https://jsonformatter.org/52c83e
todos_screen.dart
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_todo_provider/helpers/http_exception.dart';

import 'package:provider/provider.dart';
import 'package:flutter_todo_provider/.env.dart';
import 'package:flutter_todo_provider/services/todo_service.dart';

class TodosScreen extends StatefulWidget {
  @override
  _TodosScreenState createState() => _TodosScreenState();
}

class _TodosScreenState extends State<TodosScreen> {
  ScrollController _controller;
  List<dynamic> _todoList;
  bool _isLoading ;
  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(_onScrollUpdated);
  }
  void dispose() {
    _controller.dispose();
    super.dispose();
  }
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text(Configuration.AppName),
      ),
      body: FutureBuilder(
          future: _fetchListItems(),
          builder: (context, snapshot){
            if(snapshot.hasData){
              return _listItems(snapshot.data);
            }
            return _buildProgressIndicator();
          }
      ),
    );
  }
  _fetchListItems() async {
    try {
      await Provider.of<TodoService>(context, listen: false).loadNextPage();
      _todoList = Provider.of<TodoService>(context, listen: false).items;
    } on HttpException catch (e) {
      EasyLoading.showError(e.message);
    }
    return  _todoList ;

  }

  Widget _listItems(data){
    _isLoading =  Provider.of<TodoService>(context, listen: false).isLoading ;
    return ListView.builder(
      controller: _controller,
      itemCount: data.length  ,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(data[index].title),
          subtitle:Text(data[index].content),
          trailing: Icon(Icons.print),
        );
      },
    );
  }

  Future<void> _onScrollUpdated() async {
    print("Scroll11");
    var maxScroll = _controller.position.maxScrollExtent;
    var currentPosition = _controller.position.pixels;
    if (currentPosition == maxScroll ) {
      try {
        await Provider.of<TodoService>(context, listen: false).loadNextPage();
        _todoList = Provider.of<TodoService>(context, listen: false).items;

//   return  _todoList ; if use this line i see the error
      } on HttpException catch (e) {
        EasyLoading.showError(e.message);
      }
    }
  }

  Widget _buildProgressIndicator() {
    _isLoading =  Provider.of<TodoService>(context, listen: false).isLoading ;
    return new Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Center(
        child: new Opacity(
          opacity: _isLoading ? 1.0 : 00,
          child: new CircularProgressIndicator(),
        ),
      ),
    );
  }
}

todo_service.dart
 import 'dart:io';
    import 'package:dio/dio.dart';
    import 'package:flutter/foundation.dart';
    import 'package:flutter_todo_provider/.env.dart';
    import 'package:flutter_todo_provider/models/todo.dart';

    class TodoService with ChangeNotifier {
      bool isLoading = false;
      bool isFetching = false;
      int currentPage = 1;
      int totalRows = 10;
      List<Todo> items = [];

      loadNextPage() async {
        await fetchTodos(currentPage);
        currentPage++;
        notifyListeners();
      }

      Future fetchTodos(int currentPage) async {

        try {
          //404
          var options = Options(headers: {
            HttpHeaders.authorizationHeader: 'Basic ${Configuration.authToken}'
          });
          Map<String, dynamic> qParams = {
            'current_page': currentPage,
          };
          Response  response = await Dio().get('${Configuration.ApiUrl}/todos/my_todos',   options: options, queryParameters: qParams);
          List<dynamic> responseBode =  response.data["data"];
          responseBode.forEach(( dynamic json) {
            items.add(Todo.fromJson(json));
          });
          notifyListeners();

        } on DioError catch (e) {
          print("Error Message" + e.response.statusMessage);
          return items=[];
        }

      }

}

A: Here is the code:
class TodoScreen extends StatefulWidget {
  // Your service goes here
  // (the class extending ChangeNotifier)
  @override
  _TodoScreenState createState() => _TodoScreenState();
}

class _TodoScreenState extends State<TodoScreen> {
  final TodoService todoService = TodoService();

  ScrollController _controller;

  @override
  void initState() {
    super.initState();
    _controller = ScrollController();
    _controller.addListener(_onScrollUpdated);
    loadNextPage();
  }

  void dispose() {
    _controller.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Configuration.AppName'),
      ),
      body: ChangeNotifierProvider.value(
        value: todoService,
        child: Consumer<TodoService>(builder: (_, ctl, __) {
          if (todoService.isLoading) {
            return _buildProgressIndicator();
          } else {
            return _listItems(todoService.items);
          }
        }),
      ),
    );
  }

  Widget _listItems(data) {
    return ListView.builder(
      controller: _controller,
      itemCount: data.length,
      itemBuilder: (context, index) {
        return ListTile(
          title: Text(data[index].title),
          subtitle: Text(data[index].content),
          trailing: Icon(Icons.print),
        );
      },
    );
  }

  Widget _buildProgressIndicator() {
    return new Padding(
      padding: const EdgeInsets.all(8.0),
      child: new Center(
        child: CircularProgressIndicator(),
      ),
    );
  }

  Future<void> _onScrollUpdated() async {
    var maxScroll = _controller.position.maxScrollExtent;
    var currentPosition = _controller.position.pixels;
    if (currentPosition == maxScroll) {
      todoService.loadNextPage();
    }
  }
}

Note that i didn't make changes to your service. The notifyListeners will do all the job for us.
When you are using Provider, the idea is to keep all your data inside the controller or service (the class that extends ChangeNitifier) and just use the variables with notifyListeners to change the behavior of your screen.
The screen needs to be listening for changes, for this we use the pair ChangeNotifierProvider.value with Consumer(builder: (_, ctl, __) {}).
Use ChangeNotifierProvider in some upper level of the widget tree and use Consumer only where you need the widget to be updated. You can even use more than one Consumer, they all just need to be under ChangeNotifierProvider.


text:
Q: I am not able to launch npx create react app. What do i do? Your environment has been set up for using Node.js 18.2.0 (x64) and npm.

C:\Users\aanan>npx create-react-app my-app

Creating a new React app in C:\Users\aanan\my-app.

Installing packages. This might take a couple of minutes.
Installing react, react-dom, and react-scripts with cra-template...

Aborting installation.
Unexpected error. Please report it as a bug:
Error: spawn UNKNOWN
    at ChildProcess.spawn (node:internal/child_process:413:11)
    at Object.spawn (node:child_process:689:9)
    at spawn (C:\Users\aanan\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\cross-spawn\index.js:12:24)
    at C:\Users\aanan\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:383:19
    at new Promise (<anonymous>)
    at install (C:\Users\aanan\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:334:10)
    at C:\Users\aanan\AppData\Local\npm-cache\_npx\c67e74de0542c87c\node_modules\create-react-app\createReactApp.js:461:16
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
  errno: -4094,
  code: 'UNKNOWN',
  syscall: 'spawn'
}

Deleting generated file... package.json
Deleting my-app/ from C:\Users\aanan
Done.

C:\Users\aanan>


text:
Q: Angular: abort POST request The XMLHttpRequest.abort() aborts the request that was already sent. How could I achieve this in Angular, preferably with HttpClient?
Use case: The application is uploading files. I want the user to be able to cancel the request that is in progress.

A: Service:
upload() {
  return this.httpClient.post(); // Some url etc.
}

Component:
  uploadFileSubscription: Subscription;
  uploadFile() {// executed by eg. click
  this.uploadFileSubscription = this.service.upload().subscribe();
}

Then whenever you want to cancel that upload request just execute this.uploadFileSubscription .unsubscribe();


text:
Q: Navigtionbar Title after select row I created navigationbar, but when I select for example row A מot written in the bar A
how I do it?
Thanks

A: When you select a row are you pushing a new view controller or do you purposefully want to stay on the same view?
If you want to stay on the same view use the following within your didSelectRowAtIndexPath method...
self.title = @"New Title";

Or if you are trying to change the view use the following...
[self.navigationController pushViewController:newViewcontroller animated:YES];

Within the newViewController you can use self.title to set the title of that view.


text:
Q: How to prove $1 + \frac{1}{\sqrt{2}} +... +\frac{1}{\sqrt{n}} <\sqrt{n}\ .\left(2n-1\right)^{1/4} $
Prove that $$1 + \frac{1}{\sqrt{2}} +... +\frac{1}{\sqrt{n}} <\sqrt{n}\ .\Bigl(2n-1\Bigr)^{\frac{1}{4}} $$

My Approach :
I tried by applying Tchebychev's Inequality for two same sets of numbers;
$$1 , \frac{1}{\sqrt{2}} ,... ,\frac{1}{\sqrt{n}}$$
And got , $$\Bigl(1 + \frac{1}{\sqrt{2}} +... +\frac{1}{\sqrt{n}}\Bigr)^2 <n\Bigl(1 + \frac{1}{2} +... +\frac{1}{n}\Bigr) $$
Again I tried by applying Tchebychev's Inequality for another two same sets of numbers;
$$1,\frac{1}{2},...,\frac{1}{n}$$ And got, $$\Bigl(1 + \frac{1}{2} +... +\frac{1}{n}\Bigr)^2 <n\Bigl(1 + \frac{1}{2^2} +... +\frac{1}{n^2}\Bigr)$$
With these two inequities i tried solving further more, but i couldn't. So can you please help me solving this further. And if there is some other approach for this question then please answer that way too.
Thank you.

A: Assume that for any $k\geq 1$ we have $\frac{1}{k}=a_k b_k$, with $a_k$ and $b_k$ being roughly of the same magnitude and such that both $a_k$ and $b_k$ are telescopic terms. Then
$$ \sum_{k=1}^{n}\sqrt{\frac{1}{k}}\leq \sqrt{\sum_{k=1}^{n}a_k}\sqrt{\sum_{k=1}^{n}b_k}, $$
which follows from the Cauchy-Schwarz inequality, is both an accurate and simple inequality. Let us see if we manage to find such $a_k$ and $b_k$. They both have to be close to $\frac{1}{\sqrt{k}}$, and on its turn $\frac{1}{\sqrt{k}}$ is pretty close to $2\sqrt{k+1/2}-2\sqrt{k-1/2}$, which is a telescopic term. With the choice
$$ a_k=2\sqrt{k+1/2}-2\sqrt{k-1/2},\quad b_k=\frac{\sqrt{k+1/2}+\sqrt{k-1/2}}{2k} $$
$b_k$ is not telescopic, but still $b_k\leq\frac{1}{\sqrt{k}}$. So by letting $S_n=\sum_{k=1}^{n}\frac{1}{\sqrt{k}}$ we get:
$$ S_n \leq \sqrt{\sqrt{4n+2}-\sqrt{2}}\sqrt{S_n} $$
and the resulting inequality
$$ \sum_{k=1}^{n}\frac{1}{\sqrt{k}} = H_n^{(1/2)} \leq \sqrt{4n+2}-\sqrt{2} $$
is much sharper than $\leq \sqrt{n}(2n-1)^{1/4}$.

A: Your inequality should be not strong.
We can prove that for all natural $n\geq1$ the following inequality holds:
$$\sum_{k=1}^n\frac{1}{\sqrt{k}}\leq\sqrt{n}\sqrt[4]{2n-1}.$$
Indeed,
$$\sum_{k=1}^n\frac{1}{\sqrt{k}}\leq1+\int\limits_1^{n}\frac{1}{\sqrt x}dx=2\sqrt{n}-1.$$
Thus, it's enough to prove that
$$2\sqrt{n}-1\leq\sqrt{n}\sqrt[4]{2n-1}.$$
Let $n=(x+1)^2,$ where $x\geq0$.
Thus, we need to prove that
$$2x+1\leq (x+1)\sqrt[4]{2x^2+4x+1}$$ or
$$(x+1)^4(2x^2+4x+1)\geq(2x+1)^4$$ or
$$x^3(2x^3+12x^2+13x+4)\geq0,$$ which is obvious.
Done!

A: The strict inequality (which only holds for $n\gt1$) can be proved by induction, by showing that
$$\sqrt n\cdot(2n-1)^{1/4}+{1\over\sqrt{n+1}}\lt\sqrt{n+1}\cdot(2n+1)^{1/4}$$
for $n\ge N$ for some $N$ and then checking the base cases up to $N$.
We first rewrite the inductive inequality above as
$$\sqrt{n(n+1)}\cdot(2n-1)^{1/4}\lt(n+1)(2n+1)^{1/4}-1$$
Noting that both sides are positive for $n\ge1$, we can square to the equivalent inequality
$$n(n+1)\sqrt{2n-1}\lt(n+1)^2\sqrt{2n+1}-2(n+1)(2n+1)^{1/4}+1$$
which is certainly true if
$$n(n+1)\sqrt{2n+1}\lt(n+1)^2\sqrt{2n+1}-2(n+1)(2n+1)^{1/4}$$
But this reduces to $2(2n+1)^{1/4}\lt\sqrt{2n+1}$, which simplifies to $16\lt2n+1$. So the inductive inequality holds for $n\ge N=8$. And as luck would have it, the base cases for $n=2$ to $8$ have been checked in Yves Daoust's answer.

A: Using Cauchy Schwartz inequality with

*

*$u=(1,1,...,1)$

*$v=\left(1 , \frac{1}{\sqrt{2}} ,... ,\frac{1}{\sqrt{n}}\right)$
we have
$$\vec u \cdot \vec v\le |\vec u||\vec v| \implies 1 + \frac{1}{\sqrt{2}} +... +\frac{1}{\sqrt{n}} \le\sqrt{n}\ \cdot\left(\sqrt{1 + \frac{1}{2} +... +\frac{1}{n}}\right)$$
and thus it suffices to prove that
$$\sqrt{n}\ \cdot\left(\sqrt{1 + \frac{1}{2} +... +\frac{1}{n}}\right)<\sqrt{n}\ .\left(2n-1\right)^{\frac{1}{4}}$$
that is
$$1 + \frac{1}{2} +... +\frac{1}{n}<\sqrt{2n-1}$$
which is true for $n=2$ and it reduces to prove by induction
$$\sqrt{2n-1}+\frac{1}{n+1}<\sqrt{2n+1}$$
which is true indeed
$$\frac{1}{n+1}<\sqrt{2n+1}-\sqrt{2n-1}$$
$$\frac{1}{(n+1)^2}<2n+1+2n-1-2\sqrt{4n^2-1}$$
$$4n-\frac{1}{(n+1)^2}>2\sqrt{4n^2-1}$$
$$16n^2+\frac{1}{(n+1)^4}-\frac{8n}{(n+1)^2}>16n^2-4$$
$$\frac{1}{(n+1)^4}-\frac{8n}{(n+1)^2}+4>0$$
$$4(n+1)^4-8n(n+1)^2+1>0$$
$$4(n^4+4n^3+6n^2+4n+1)-8n(n^2+2n+1)+1>0$$
$$4n^4+8n^3+8n^2+8n+5>0$$
Therefore the given inequality holds for $n\ge 2$, for $n=1$ we can check directly that equality holds.

A: $$\frac1{\sqrt{\lceil x\rceil}}\le\frac1{\sqrt x}$$
and integrating from $0$ ("excluded") to $n$,
$$\sum_{k=1}^n\frac1{\sqrt k}<\int_0^n\frac{dx}{\sqrt x}=2\sqrt n.$$
This leads us to
$$2\sqrt n<\sqrt n\sqrt[4]{2n-1}.$$
This inequality is certainly true for $n>8$, and we can check the remaining values explicitly.
$$1 \le 1 \\
1.70710678119 < 1.8612097182 \\
2.28445705038 < 2.59002006411 \\
2.78445705038 < 3.2531531234 \\
3.23167064588 < 3.87298334621 \\
3.63991893634 < 4.46091344257 \\
4.01788340935 < 5.02382911018 \\
4.37143679994 < 5.56631536743 \\
4.70477013328 < 6.09162955461 \\\cdots$$

A: Here is a slightly different start than that of @michael-rozenberg, avoiding integrals in case one would like to:
Start by writing (assuming $n>1$)
$$
\frac{1}{\sqrt{1}}+\frac{1}{\sqrt{2}}+\cdots+\frac{1}{\sqrt{n}}<
\frac{1}{\sqrt{1}}+\frac{2}{\sqrt{2}+\sqrt{1}}+\cdots+\frac{2}{\sqrt{n}+\sqrt{n-1}}.
$$
Multiplying by conjugates you will find that the sum on the right-hand side equals
$$
1+2\bigl((\sqrt{2}-\sqrt{1})+\cdots+(\sqrt{n}-\sqrt{n-1})\bigr)=1+2(\sqrt{n}-1).
$$
Thus, your sum is less than
$$
2\sqrt{n}-1.
$$
Then continue in the same manner as in the nice solution by @michael-rozenberg.


text:
Q: How to write testable code in Swift So this question of mine all began when I started to do unit testing for a simple 2 line of postNotification and addObserver. From this similar question here you can see that to make it testable you need to add ~20 lines & part away from the common way of writing your code.
Facing this problem was actually the first time I understood the difference between Unit Testing and TDD. Unit testing is easy if your code is testable ie if you are following the TDD mindset. Next I was brought to how can I write testable code, which I didn't find much guidelines, every tutorial simply just jumps into writing a unit test. Apple own documentation has nothing for this.
My initial thought was that I need to aim for 'functional programming' and write my functions in a pure function way. But then again this is very time consuming and may require lots of refactoring in existing codes or even for new projects lots of added lines and I'm not even sure if that is the correct approach. Are there any suggested guidelines or standards for writing testable code in an easy way?
What I know myself already:
I know that you shouldn't write any code, unless there is a test for it to fail, so basically I have to write the test first and as soon as I get an error, even a compiler error then I would have to switch back to the actual class being tested write whatever necessary and make my test code not give any errors , then switch back to the test class and continue writing my test and fixing compile errors until done. Then run the test and see if it checks what I want it to check.
For all tests I should make sure that my tests would pass and fail exactly where I expect to fail ie the test would pass when it's expected to fail.
What I don't know is how can I smoothen the process in a more easier way.
I am not asking for how to write a testable code for NSNotificationCenter, I am asking for general guidelines for writing testable code.

A: This is a rather large question, and one where developers' views sway to very different directions. It is also important to note that making code testable is in many essential ways not a Swift specific question: a lot of what makes you able to write testable code routinely and conveniently actually relies on you following some fundamental, generally applicable principles. Often test driven design practices help you indirectly, by validating you have followed practices that make executing your code via tests plausible, beside bringing you other programmer productivity and reliability benefits. So, unfortunately writing testable code is not a question of learning some mechanical tricks of working with Xcode, rather than often a proof of you having designed and planned the programs and libraries you write keeping to some good practices.
I'll do my best to link below to some Swift specific resources to demonstrate the more general principles I tend to myself follow to make my code testable.

*

*Making your code testable is often a side effect of following sound object oriented design principles.

*

*You may find reading about the SOLID principles useful.

*Take a look also at this Swift based demonstration of each of the five SOLID principles.

*Google's Code Reviewer's Guide (PDF) is also great resource for learning about typical OOD problems and how to avoid (also by no coincidence, this OOD related document happens to be subtitled "Writing Testable Code").

*Following a sound object oriented design is often itself the side effect of good higher level architectural decisions. Basically, think early and often about the kinds of types you plan to introduce in the object graph of the program. What are the roles and dependencies between them? Are any of the dependencies in your object graph hard to meet or correctly construct when executing your code from different contexts (e.g. from UI code vs a unit test)?

*

*There is a lot of computer science literature about architectural design patterns. The Gang of Four remains a valuable book to read about this topic (although not all of it applies to your typical Swift program).

*Take a look at this Swift design patterns demonstration for an overview of how many common design patterns can be implemented in Swift.

*Especially if your code is for a mobile app, you should read about VIPER, a mobile app oriented architectural pattern emerged out of the typical architectural needs of iOS apps.

*To link design patterns to the SOLID principles listed above, the "Single Responsibility" principle is perhaps the one principle most glaringly violated in many large Cocoa programs that is a result of bad architectural practices, also resulting in very difficult to test code. People in fact often for jokingly refer to MVC as applied in practice in Cocoa as the "Massive View Controller".

The above points raised are in no way Swift specific, and I would expect not terribly controversial claims. Swift does however also offer language features that also help you write reliable, bug free code, in part as these language features help you make your code testing friendly. Here's a few of good Swift practices:

*

*Use value types when you can: Swift is well suited for writing programs which minimise automatic reference counted references (pointers). This carries with it performance benefits, but also improves your chances of writing reliable code that minimises unexpected dependencies and data races which can be difficult to capture in testing.

*Keep things immutable when you can: the syntax conventions and type system in Swift help you avoid mutable state, which amongst other things has a negative impact on testability of your code (configuring your object graph for testing can become difficult, as will achieving real-world usable test coverage of your code if the possibile state space in your program is large).

*Apple has also made available some guidance on the architectural matter of value types and immutability that also touches on testability of your code.

*Use protocols when you can: to understand why, read up on the Liskov substitution principle :-) More seriously, preferring protocols over concrete types helps you write testable code for instance by for allowing you to fulfil dependencies in a test setting with test specific types that fake or mock some resources irrelevant for your tests.

*Use functional programming techniques (when it makes sense): often composing functionality with functions helps you write readable, flexible code that avoids mutable state. I recommend Functional Swift by Chris Eidhof and others as a good guide to applying functional patterns in Swift.

Again, this question is large and I am really just scratching the surface with my answer, in order to make the point that there is no single magic bullet to testability – it's something you achieve as a result of following many best practices when designing your code.


text:
Q:  in SQL Can anybody give a little context on what <parm = "period_end"/> does in a query?
For eg: cast(<parm = "period_end"/>  as date), changes the type to date but if no value is assigned to <parm = "period_end"/> then how would the above work?


text:
Q: Is there a faster way to insert text into a document with multiple lines using the ECHO command? I am making a batch script that creates a .json script if it is not found in a specific location. If it needs to be made, I also have my batch script insert all of the default code for the JSON. I can make a 1:1 copy of the original I'm making the new one from, but I want to know if there's a faster way to do so without having to copy the code line for line with the current syntax that I'm using. I am inserting the code via the ECHO command in this manner:
ECHO %CODELINE%>> "%JSONSCRIPT%

I want to know if there is something I can do so that each line doesn't have to start with ECHO and end with >> "%JSONSCRIPT%. Is this possible? Here is a snippet from my script for one of the JSON files to be created:
:MAKEJSON
BREAK>"Scripts\JSON1.json"
ECHO {>> "Scripts\JSON1.json"
ECHO   "list": [>> "Scripts\JSON1.json"
ECHO     {>> "Scripts\JSON1.json"
ECHO       "var": {>> "Scripts\JSON1.json"
ECHO         "showName": "Example 01",>> "Scripts\JSON1.json"
ECHO         "targetName": "TBD">> "Scripts\JSON1.json"
ECHO       },>> "Scripts\JSON1.json"
ECHO       "type": {>> "Scripts\JSON1.json"
ECHO         "showName": "Example 02",>> "Scripts\JSON1.json"
ECHO         "typeName": "[Test]",>> "Scripts\JSON1.json"
ECHO       }>> "Scripts\JSON1.json"
ECHO     },>> "Scripts\JSON1.json"
ECHO     {>> "Scripts\JSON1.json"
ECHO       "var": {>> "Scripts\JSON1.json"
ECHO         "showName": "Test 2",>> "Scripts\JSON1.json"
ECHO         "varName": "[Test2]">> "Scripts\JSON1.json"
ECHO       },>> "Scripts\JSON1.json"
ECHO       "type": {>> "Scripts\JSON1.json"
ECHO         "showName": "Sampletext",>> "Scripts\JSON1.json"
ECHO         "typeName": "TBD",>> "Scripts\JSON1.json"
ECHO       }>> "Scripts\JSON1.json"
ECHO     }>> "Scripts\JSON1.json"
ECHO   ]>> "Scripts\JSON1.json"
ECHO }>> "Scripts\JSON1.json"

A: Why don't you just create a "template" text file that has all of the actual text you want, and then reference that in your script instead?
For example, your template text file would contain:
{
  "list": [
    {
      "var": {
        "showName": "Example 01",
        "targetName": "TBD"
      },
      "type": {
        "showName": "Example 02",
        "typeName": "[Test]",
      }
    },
    {
      "var": {
        "showName": "Test 2",
        "varName": "[Test2]"
      },
      "type": {
        "showName": "Sampletext",
        "typeName": "TBD",
      }
    }
  ]
}

And your script would simply have:
type "Scripts\template.txt" >> "Scripts\JSON1.json"

A: A template is usually used to create varying content.
So a batch has the additional use to insert variables into the template.
This batch simplifies output by using a (code block) with redirection:
@Echo off

For /L %%n in (1,2,10) Do Call :MAKEJSON %%n

Goto :Eof
:MAKEJSON
Set /A n=100 + %1,m=101 +%1,T = %1 + 1
Set  "JSONSCRIPT=Script\JSON%1.json"
( Echo={
  Echo=  "list": [
  Echo=    {
  Echo=      "var": {
  Echo=        "showName": "Example %n:~-2%",
  Echo=        "targetName": "TBD"
  Echo=      },
  Echo=      "type": {
  Echo=        "showName": "Example %m:~-2%",
  Echo=        "typeName": "[Test]",
  Echo=      }
  Echo=    },
  Echo=    {
  Echo=      "var": {
  Echo=        "showName": "Test %T%",
  Echo=        "varName": "[Test2]"
  Echo=      },
  Echo=      "type": {
  Echo=        "showName": "Sampletext",
  Echo=        "typeName": "TBD",
  Echo=      }
  Echo=    }
  Echo=  ]
  Echo=}
) >"%JSONSCRIPT%"

And creates several files in one run:
│   MakeJson.cmd
│
└───script
        JSON1.json
        JSON3.json
        JSON5.json
        JSON7.json
        JSON9.json

With content like this:
> type script\JSON5.json
{
  "list": [
    {
      "var": {
        "showName": "Example 05",
        "targetName": "TBD"
      },
      "type": {
        "showName": "Example 06",
        "typeName": "[Test]",
      }
    },
    {
      "var": {
        "showName": "Test 6",
        "varName": "[Test2]"
      },
      "type": {
        "showName": "Sampletext",
        "typeName": "TBD",
      }
    }
  ]
}

A: After some digging, I came across this question on Stack Overflow that has an answer (by grawity) that I modified to work in the manner I was looking for. ECHO must still be declared at the beginning of each line you want to insert into your text-based document/script for this to work. Begin the code block with a single left parenthesis on it's own line, and end with a right parenthesis on a new line followed by > "%JSONFILE%". Here is the code block I used that achieves this:
:MAKEJSON
BREAK>"Scripts\JSON1.json"
(
ECHO {
ECHO   "list": [
ECHO     {
ECHO       "var": {
ECHO         "showName": "Example 01",
ECHO         "targetName": "TBD"
ECHO       },
ECHO       "type": {
ECHO         "showName": "Example 02",
ECHO         "typeName": "[Test]",
ECHO       }
ECHO     },
ECHO     {
ECHO       "var": {
ECHO         "showName": "Test 2",
ECHO         "varName": "[Test2]"
ECHO       },
ECHO       "type": {
ECHO         "showName": "Sampletext",
ECHO         "typeName": "TBD",
ECHO       }
ECHO     }
ECHO   ]
ECHO }
) > "%JSONFILE%"


text:
Q: Where do I put this conditional comment for a gradient background on IE? Ok I have been searching for hours and have found answers but none that seem to work for me. I am trying to use a gradient background that I generated on colorzilla.com. Below is my code. To "complete" the ie 9 support colorzilla says: Support for full multi-stop gradients with IE9 (using SVG).
Add a "gradient" class to all your elements that have a gradient, and add the following override to your HTML to complete the IE9 support:

But I cannot for the life of me figure out where to put the comment or where I should be putting the "gradient" class
I have to have this turned in tomorrow morning (AH!) please help!
code (without the comment):
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<META content="text/html; charset=utf-8" http-equiv=Content-Type>

<META name=GENERATOR content="MSHTML 8.00.6001.18975">

Sorry for the inconvenience, but the Transcender website will be
    unavailable Saturday, April 21st for routine
    maintenance. Please come back and visit us again on Sunday, April 22nd and get
    10% off your next order*. Use promo code: MANDOWN12.

    *Offer expires 4/23/12, excludes cd & voucher purchase option

A: It looks like you're applying the gradient to the HTML tag, so you'd use this for your conditional block:

And you'd place it after the  block in the code you listed above (between </style> and <meta>).
Hope this helps!

A: You would place the code inside of your  tags like so.


text:
Q: Laravel Eloquent: I cannot get the id I want, instead I get another one from a joined table This is my first question here, so I hope I don't mess anything up on my first try.
Okay, to the topic in hand: I am trying to do a function in my controller which allows me to both fetch some data from my database in a template and then generate a downloadable PDF file with the data I was passing to it. I managed to do so, and it works perfectly fine.
What's wrong is, I am using a database where all my identifiers are named 'id', and when I try to access the one I want, I get another from the joined tables. The obvious solution would be changing the name of the identifiers, so there are no duplicated names, but due to some external factors, I cannot do that thing, at least for now. That is something programming cannot do.
So, I was wondering if there is a way I can retrieve the id I want, without changing the database.
This is my function:
public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        // These are filters I had to apply before fetching data to my PDF file, they work fine.
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }

And this is my blade template:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>PDF</title>

                Código
                Nombre
                Email
                Empresa
                Requerimiento
                Estado

            @foreach($tickets as $value)

                {{ $value->id }}
                {{ $value->name }}
                {{ $value->email }}
                {{ $value->empresa }}
                {{ $value->nombre }}
                {{ $value->estado }}

            @endforeach

Thanks in advance for your help! Have a nice day :)

A: You can specify just the fields you need:
 $tickets = DB::table('tickets')
    ->select('tickets.id as id', 'tickets.name as name', '...')
    -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
    -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
    -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
    -> where('tickets.estado' ,'=', $categoria)
    -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
    -> get();

To get more information, use xdebug or write dd($tickets);  to see what's inside the variable.

A: So, it seems all I needed were aliases:
public function descargarPDF(Request $request)
    {
        $fecha1 = $request->get('fecha1');
        $fecha2 = $request->get('fecha2');
        $categoria = $request->get('categoria');
        $tickets = DB::table('tickets')
        -> join('detalle_tickets', 'tickets.detalle_ticket_id', '=', 'detalle_tickets.id')
        -> join('users', 'detalle_tickets.user_id', '=', 'users.id')
        -> join('areas', 'detalle_tickets.area_id', '=', 'areas.id')
        -> select ('tickets.id as id_ticket',
                   'users.name as nombre',
                   'users.email as email',
                   'users.empresa as empresa',
                   'areas.nombre as requerimiento',
                   'tickets.estado as estado')
        -> where('tickets.estado' ,'=', $categoria)
        -> whereBetween('tickets.created_at', [$fecha1, $fecha2])
        -> get();
        $pdf = PDF::loadView('/admin/pdf', compact('tickets'));
        return $pdf->download('tickets.pdf');
    }

Cheers to Felipe for solving that in the comments!


text:
Q: Raster stops process with-out error I am currently making a painting application and am currently implementing the rubber tool. Due to the reason that the canvas (JPanel) I am using has a transparent background (intended), I could not just call g2d.fillOval(x,y,x,y) as it would draw a transparent circle, thus the drawing that was there before would remain. Conscquently, I have decided to use WritableRaster and it's setPixel method in two for loops that shape the overall 'shape' that the pixels draw into a circle (r is the same on every tangent). Yet, I am having problem with calling the setPixel method, as it does not draw anything. I have even set the color to black just to test it, and nothing. I have been tampering it and inserting print statetments and narrowed it down into the most inner for block, as the print method would not output into the console.
Here is my code
WritableRaster raster = (WritableRaster) bi.getData();
Integer[] arrayw = al.get(i);

Point p1 = new Point(arrayw[0], arrayw[1]);
Point p2 = new Point(arrayw[2], arrayw[3]);
int[] black = new int[]{0, 0, 0};
int r = tl.get(i);

for (int y = p1.y - r; y < r; y++) {
    int bound = (int) (Math.sqrt(r * r - y * y) + 0.5);
    for (int x = p1.x - bound; x < bound; x++) {
        raster.setPixel(x, y, black);
        gc.drawLine(x, y, x, y);
        System.out.println(y + "\t" + x + "\t" + tl.get(i));

    }
}
for (int y = p2.y - r; y < r; y++) {
    int bound = (int) (Math.sqrt(r * r - y * y) + 0.5);
    System.out.print("test");

    for (int x = p2.x - bound; x < bound; x++) {
        raster.setPixel(x, y, black);
        gc.drawLine(x, y, x, y);
        System.out.println(y + "\t" + x + "\t" + tl.get(i));
    }
}

System.out.print("raster");
bi.setData(raster);

As I said before, the code prints raster, but does not print inside the inner for block. I have no idea what I am doing wrong. Thanks for you help!

A: Have you verified that the condition of the inner block is ever met?
For instance, is it ever true that x < bound if x is always greater than or equal to p1.x - bound? If p1.x > 2 * bound, your inner loop will never get called.


text:
Q: Using subjunctive following it is intended that As far as I know, there are some specific verbs, nouns, and adjectives that subjunctive can only be used with. Wanted to know is this a fix rule, that is, really isn't it possible to use other things in the form of subjunctive? My question concerns "It is intended that":

It is intended that the new method be able to address the previously mentioned shortcomings.

Many thanks

A: The verb "intend", (here in the form "It is intended that...") is one of the (rare) cases that can trigger the subjunctive.
With other verbs (It is aimed ... or It is attempted ...)  don't licence a content clause "that ...", and you can't use the subjunctive.
More generally, avoid the subjunctive, if possible. It usually isn't the clearest way to express an idea.

We intend for the new method to be able to address the shortcomings of the old method.


text:
Q: Prove that the bound is sharp. Theorem: Let $G$ be a graph of order $n\geq 3.$ If $$\deg u+\deg v\geq n$$ for each pair $u ,v$ of nonadjacent vertices of $G$ then $G$ is Hamiltonian.
I have to show that this bound is sharp. I tried to consider $\deg u+\deg v= n-1$ to get some insights, but couldn't find anything useful. Frankly, I don't even know how to approach such problems so I would be grateful if someone could share his/her thoughts on how to approach problems of such kind and also give hints regarding this problem.

A: Note that all Hamiltonian graphs are connected, since given any two vertices we can walk along the Hamiltonian cycle to get from one to the other. So this tells us that if a graph is not connected, it can't possibly be Hamiltonian. In fact more is true; for any two distinct vertices $u,v$ in a Hamiltonian graph, there exists two paths $P,Q$ from $u$ to $v$ which only meet at $u$ and $v$. To see this just imagine the Hamiltoian cycle is a circle, $u,v$ are points on the circle. Then there are two paths from $u$ to $v$, going clockwise around the circle and going anticlockwise. These give the two required paths.
This property of having two disjoint paths between any two vertices is much easier to work with than the Hamiltonian property.
Applying this to your problem, consider an $m$-regular graph $H$ on $m+1$ vertices (can you think of such a graph?). By definition every vertex in $H$ has degree $m$. Now let $H'$ be an identical copy of $H$ and take the graph $K$ to be the disjoint union of $H$ and $H'$. Given any two non-adjacent vertices $u,v$ in $G$, one can show that: $$\deg u+\deg v= 2m$$
We are not quite done, since we would like to change $2m$ to $2m+1$ to solve your problem. There are two cases.
Suppose $n$ is even and let $n=2m+2$. As mentioned, the graph $K$ does not quite meet the requirements on the degree. Let's pick a vertex $w$ in $H$ and add an edge between $w$ and every vertex of $H'$ to form a new graph $G$. We see that $G$ satisfies the degree requirement (why?) and because every path between a vertex in $H$ and a vertex in $H'$ must pass through $w$, we see that $G$ is not Hamiltonian (why?).
For $n=4$, this graph $G$ is a lone vertex connected by exactly one edge to a triangle (the point of the triangle it is connected to is $w$).
Now suppose $n$ is odd and let $n=2m+3$. The graph $K$ previously constructed only has $2m+2$ vertices, so let's add a new vertex $w$ and add an edge between $w$ and every other vertex in $K$. Call this new graph $G$. We see that $G$ satisfies the required condition on the degrees of non-adjacent vertices (why?). Now note that any path from a vertex in $H$ to a vertex in $H'$ must pass through $w$. So as in the previous case, $G$ can't be Hamiltonian (why?).
For $n=3$, this graph $G$ is a triangle with one of its edges removed (the vertex of degree $2$ is $w$).

A: HINT:-
Let the length of longest path in the graph be $k\le n$, and P be a longest path with endpoints $u$ and $v$. All neighbours of $u$ and $v$ must lie in P otherwise P can be extended. Since $\deg u+\deg v\geq n$, $u$ and $v$ must have at least two neighbours in common.


text:
Q: There is a duplicate line showed when calling a __init__ in Python script I saw a very strange phenomenon when calling a class in Python:
    I want to see "Base created now" on the screen. However I saw two lines,  which are exactly the same. This is very strange to me.
class Base(object):
    def __init__(self):
        print "Base created now"

test1=Base()
test1.__init__()

The result on the screen:
Base created now
Base created now

So I did another experiment: I changed the "init" to "print_test":
class Base(object):
    def print_test(self):
        print "Base created now"

test1=Base()
test1.print_test()

The result on the screen:
Base created now

Do you know why the 1st script has two same lines, and the 2nd only has one line?  Thanks!

A: __init__() is your constructor method, it always gets called when creating new instances
class Base(object):
    def __init__(self):
        print "Base created now"

test1=Base()   # this creates a new instance and calls __init__()


text:
Q: undefined control sequence \OT when ß appears in TOC I use the command \addtocontents
\documentclass[a5paper, 11pt]{scrbook}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage{helvet}

\usepackage{tocloft}
\usepackage{scrpage2}

\begin{document}
\addtocontents{toc}{\textbf{Laßt, ihr buntbemützten Scharen}\vspace*{2.5pt}

}
\tableofcontents
\end{document}

which writes the following gibberish to the toc
\textbf {La\OT 1\ss t, ihr buntbem\unhbox \voidb@x \bgroup \let \unhbox \voidb@x \setbox \@tempboxa \hbox {u\global \mathchardef \accent@spacefactor \spacefactor }\accent 127 u\egroup \spacefactor \accent@spacefactor tzten Scharen\unhbox \voidb@x \hbox {}}\vspace *{2.5pt} \par

The \OT 1 causes an error. If I remove it, I get the desired output. The question is: How can I remove it? I suspect, it is inserted by a bug, which means, I need a workaround. I can not replace ß by \ss, since Laßt, ihr..... itself is a result in an edef.
Is this a known bug/error. I couldn't find any similar problems.
I suspect helvet, tocloft, scrpage2 and scrbook as the "bad guys". Commenting them out is either impossible (because essential) or causes other errors, but no solution.

A: Imho your example doesn't tell the truth. You are probably having an \edef involved. Something like this would give your output and your error (after the second compilation):
\documentclass[a5paper, 11pt]{scrbook}
\usepackage[ngerman]{babel}
\usepackage[utf8]{inputenc}
\usepackage{helvet}

\usepackage{tocloft}
\usepackage{scrpage2}

\begin{document}
\edef\test{Laßt, ihr buntbemützten Scharen}

\addtocontents{toc}{\textbf{\test}\vspace*{2.5pt}}
\tableofcontents
\end{document}

If your real code contains such an \edef: Use \protected@edef instead. This here would work in my example (delete the old toc first):
\makeatletter
\protected@edef\test{Laßt, ihr buntbemützten Scharen}
\makeatother

A: In my problem ß changed to \OT 1\ss, which expanded to <ucs-error> 1\ss expanded to 1ß instead of ß.
I couldn't solve the main problem, but just in case, someone stumbles across this problem:
\def\OT#11{} % for understanding: \OT{#1}1 => {}

is a workaround. The principle is simple:
\OT 1 is defined with #1 = SPACE and 1 = delimiter

it expands to nothing.


text:
Q: How to use a local domain socket in Objective-C Objective-C makes it very easy to use network sockets with streams doing something like this:
// Setup comms with the server, assumed to be running on the local host
NSHost* host = [NSHost hostWithAddress:@"127.0.0.1"];

NSInputStream *iStream;
NSOutputStream *oStream;

[NSStream getStreamsToHost:host port:_PORT inputStream: &iStream outputStream: &oStream];

However, is it possible to create and or connect to a local domain socket this way, or does Objective-C provide other classes for this?
If I can still use NSStream and getStreamsToHost, how would I specify the file and what would I put for the port number?
My research on this, so far, shows many examples working with TCP/IP or UDP, but not local domain sockets.

A: You can't use -getStreamsToHost:port:inputStream:outputStream: for a UNIX domain socket, no.  You can, however, create your own NSInputStream and NSOutputStream instances; the easiest way is to take advantage of toll-free bridging between CF(Read|Write)Stream and NS(Input|Output)Stream; for instance:
struct sockaddr_un sun;

sun.sun_family = AF_UNIX;
strcpy (sun.sun_path, "/path/to/my/socket");
sun.sun_len = SUN_LEN(&sun);

// Server side (naive)
int server_sock = socket (SOCK_UNIX, SOCK_STREAM, 0);
int ret = bind (server_sock, (struct sockaddr *)&sun, sun.sun_len);

listen (server_sock, 1);               // In practice you'd specify more than 1

s = accept (server_sock, NULL, NULL);  // In practice you want to keep calling this

// Client side
int s = socket (SOCK_UNIX, SOCK_STREAM, 0);

int ret = connect (s, (struct sockaddr *)&sun, sun.sun_len);

CFReadStreamRef readStream;
CFWriteStreamRef writeStream;

CFStreamCreatePairWithSocket (kCFAllocatorDefault, s, &readStream, &writeStream);

Then to get an NSInputStream and NSOutputStream you can just do
NSInputStream *inputStream = (__bridge_transfer NSInputStream *)readStream;
NSOutputStream *outputStream = (__bridge_transfer NSOutputSteram *)outputStream;

Obviously in practice you may want to wrap all of the above in a function or method in your own code.  Also, take care with sockaddr_un; the sun_path member was probably supposed to have 1024 characters, but in the headers it seems to only have 104 (this is a long-standing problem and apparently goes way back to BSD4.4; some systems have other character counts here too).  This is nowhere near PATH_MAX, so in practice you may wish to write something more like
struct sockaddr_un *new_unix_addr (const char *path) {
  size_t len = strlen (path);
  size_t bytes = sizeof (struct sockaddr_un) + len + 1
                 - sizeof (((struct sockaddr_un *)0)->sun_path);
  struct sockaddr_un *pun = (struct sockaddr_un *)malloc (bytes);

  pun->sun_family = AF_UNIX;
  pun->sun_len = bytes;
  memcpy (pun->sun_path, path, len + 1);
  return pun;
}

remembering later to free() it.


text:
Q: Socket Programming TCP . Server programming looping continuously Following is the server.c program. When i connect a client to the server, the server starts looping infinitely in receive message part
Server.c
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/socket.h>

int main()
{
    int sid,sid1,bin,lis,n,p,port, pid;
    struct sockaddr_in sin,c;
    socklen_t len;
    char buffer[40]="";
    char buffer1[20]="";
    char ip[30]="192.168.65.241";
    // printf("\nEnter the IP Address :");
    // scanf("%s",ip);
    printf("\nEnter the Port no.:");
    scanf("%d",&port);
    sid=socket(AF_INET,SOCK_STREAM,0);//END POINT CONN,
    if(sid<0)
    {
            perror("Socket : ");
            exit(0);
    }
    printf("\nSocket created successfully...");
    sin.sin_family=AF_INET;
    sin.sin_port=htons(port);
    inet_aton(ip,&sin.sin_addr);//SERVER ADDRESS
    bin=bind(sid,(struct sockaddr*)&sin,sizeof(sin));//BIND ADDRESS WITH SOCKET
    if(bin<0)
    {
            perror("\nBind : ");
            exit(0);
    }
    printf("\nBinding has been done successfully...");
    lis=listen(sid,10);//LISTEN TO THE CLIENT
    if(lis<0)
    {
            perror("\nListen : ");
            exit(0);
    }
    len=sizeof(c);

     while(1){

        printf("A Client is connected to the server.....");
        sid1=accept(sid,(struct sockaddr*)&sin,&len);//ACCEPT CONN.FROM CLIENT
        if(sid1<1)
        {
            perror("\nAccept : ");
            exit(0);
        }
        pid=fork();//CREATE PARENT AND CHILD PROCESS

        if(pid<0){

            perror("ERROR on fork");
            exit(1);
        }
        if(pid==0){

            lis=listen(sid,10);
            printf("\nEnter message...(Type END to terminate):\n");
            scanf("%s",buffer);
            while(strcmp(buffer,"END")!=0)
            {
                send(sid,buffer,30,0);//SEND TO SERVER
                scanf("%s",buffer);
            }
            send(sid,"END",5,0);
            printf("\nTerminating the server...\n");
            exit(0);
        }
        else{

            n=recv(sid,buffer1,30,0);//RECEIVE FROM CLIENT
            buffer[n]='\0';
            n=strcmp(buffer1,"END");
            while(strcmp(buffer1,"END")!=0)
            {
                **printf("\nClient: %s\n",buffer1);** // Infinite Looping
                n=recv(sid,buffer1,30,0);
            }
            printf("\nA client has been disconnected from the server...\n");
            exit(0);
        }
                            close(sid); //CLOSE CONNECTIONS
                                                                        close(sid1);    //CLOSE CONNECTIONS

     }
    shutdown(sid,2);    //SHUTDOWN READ AND WRITE
    close(sid); //CLOSE CONNECTIONS
}

Client.c
Client program isn't a problem.. Added the code for your reference.
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <errno.h>
int main()
{
    int sid,bi,con,n,p,port;
    char buffer[50],ip[30];
    sid=socket(AF_INET,SOCK_STREAM,0);//END POINT CONN.
    if(sid==-1)
    {
            perror("\nSocket :");
        exit(0);
    }
    printf("A Socket created successfully....");
    struct sockaddr_in sin;
    sin.sin_family = AF_INET;
    printf("\nEnter the IP Address :");
    scanf("%s",ip);
    printf("\nEnter the Port no. :");
    scanf("%d",&port);
    sin.sin_port = htons(port);
    inet_aton(ip,&sin.sin_addr);
    con=connect(sid,(struct sockaddr*)&sin,sizeof(sin));//CONNECT TO SERVER
    if(con == -1)
    {
        perror("Connection : ");
            exit(0);
    }
    printf("\nConnection is successfull to the server(%s)....\n",ip);
    p=fork();
    if(p)
        {
            printf("\nEnter message...(Type END to terminate):\n");
            scanf("%s",buffer);
            while(strcmp(buffer,"END")!=0)
            {
                    send(sid,buffer,30,0);//SEND TO THE SERVER
                    scanf("%s",buffer);
            }
            send(sid,"END",4,0);
        printf("\nTerminating the client...\n");
        exit(0);
        }
        else
        {
                n=recv(sid,buffer,30,0);//RECV.FROM SERVER
        printf("%d",n);
        buffer[n+1]='\0';
            while(strcmp(buffer,"END")!=0)
            {
                    printf("\nServer: %s\n",buffer);
                    n=recv(sid,buffer,30,0);
            }
            send(sid,"END",4,0);
        exit(0);
        }
    printf("\nClient is terminated...\n");
    shutdown(sid,2);//SHUTDOWN READ AND WRITE
    close(sid); //CLOSE CONNECTIONS
}

Please let me know the Solution ASAP.

A: The main problem, i.e. the infinite loop is simply because recv() is being called on the server's main socket (sid), not the socket returned by accept() - sid1. Change this:
n=recv(sid,buffer1,30,0);//RECEIVE FROM CLIENT

to
n=recv(sid1,buffer1,30,0);//RECEIVE FROM CLIENT

and
n=recv(sid,buffer1,30,0);

to
n=recv(sid1,buffer1,30,0);

and you will be in business.
There are other problems with the server code:

*

*recv() is being told to read up to 30 bytes into buffer1,
however, buffer1 is only 20 bytes in size - you have a buffer
overrun there.

*If the client closes the connection without sending "END" and
infinite loop will occur in the receive loop. You need to detect
connection closure which is indicated by recv() returning 0.

*listen() is being unnecessarily called in the server on line 64.

The above list is probably not exhaustive.

A: You are using the wrong socket in the calls to read/write in server.c.
Right now, all calls to read/write fail, with errno indicating that the socket isn't connected.
You should use sid1, the connected socket, instead of sid.
You should also check the return values so you can detect and handle errors.


text:
Q: TCL vs Lua - scripting a mmo server I have a c++ server side project that I need to embed some sort of scripting into. It is part of an online MMO type of server. I have significant experience using TCL, and it seems like the natural fit. I've done a minimal amount of Lua in my game dev days, and I wonder if this might be a better language for embedded scripting. It is also nice to learn a new language. What are the relative strengths and weaknesses of TCL vs Lua? Thanks!

A: The Lua C API is extremely easy to integrate into an application. From C you have complete access to the Lua state, and to its native data types. I've recommended using Lua just to get the hash table implementation even with no need for scripting, for instance.
Lua functions written in C can be injected as global names, collected in a table like most of the standard library functions, or implemented in DLLs and dynamically loaded at runtime. That permits the application to provide a stable API, as well as to support plugins written in either Lua or C.
Lua as a language is surprisingly powerful, with support for both functional and object oriented programming styles. It is also surprisingly lightweight: the complete source kit and full documentation fits in well under 1 MB, and the whole VM, compiler, and standard libraries in a DLL is only 164KB on Windows.
I haven't seriously examined TCL since version 2 or so... I won't try to compare them in a concrete way. I believe that they both were invented to fit the same niche, and at about the same time. They certainly are both mature languages with avid user communities.

A: I suspect that Tcl will have more libraries that you might find necessary or convenient along the way.

A: As others have stated, both languages would work very well.  A third option that would also likely work about as well is JavaScript, since it fits in about the same the same niche.  Instead of trying to Woo you to one or the other (As I like both languages very much) I'll try to focus on some of the objective differences, and point out where I think one is ahead of the other.
The most important issue in a game server is likely to be raw performance.  Both languages are mature and well optimized, but both also recognize that some issues are best optimized by deferring to compiled code.  Both languages use basically the same mechanism for performing this.  From the point of view of the languages themselves, It looks like Lua is just a bit faster. link
From the point of view of Libraries, which is the next big factor, Neither language requires the use of any libraries to be useful; that is both languages are very compact, as compared to languages such as Java which require large runtime libraries to be useful;  Again, this is a consequence of their original designs requirements.  Both languages have plentiful add-on libraries to choose from, But It's my impression at least that TCL has somewhat more variety in this category.  tcl:( Tcl Extension Archive / Tcl Extension Repository ) lua: ( LuaForge )
Another difference is between the core languages themselves.  Both languages value simplicity over style, but that's where the similarity ends.  Lua uses what might be familiar syntax to most programmers, with a very simple context free grammar.  TCL syntax is also simple, but doesn't really have anything in common with other existing languages, although it looks superficially a bit like unix shell language.  Tcl is probably only easier on non-programmers because its line oriented command syntax is pretty clear, but programmers experienced in other languages usually object to its arcane syntax.  Neither one is terribly forgiving in terms of code generation, but both have strong metaprogramming facilities (comparable, but perhaps not as robust as CLISP macros).

A: Honestly, they're both extremely well suited to the task. Both are easy to embed in an application and have a fairly simple syntax. I know for a fact that it's extremely simple to add new commands (to interact with the application) in Tcl, and I'm told Lua is very good at this type of thing, too.
My recommendation would be to play around with Lua for a while to see how you like it (since you already know Tcl)... and then pick the one that feels most comfortable to you. If you're writing much of the code, you'll wind up working with it a lot, so you'll need something you can use, too. In the end, both language choices should be fairly easy for your end users to script in.
My personal preference is Tcl, both because I don't like Lua (I've done a reasonable amount of programming in it for Warcraft addsons) and because I love Tcl (I've done a LOT of programming in it for both professional and private work).
Edit: Added the note about both being easy for end users. Got 2 down votes and couldn't think of anything else that it might be for other than not clarifying the why part of my statement.

A: I guess I'm the opposite of RHSeeger there. I've used both Lua and TCL embedded in games (online games, incidentally) and I wouldn't touch TCL again with a 10' bargepole if I had the choice. My very subjective opinion is that Lua is a sane language and TCL isn't. Relative to the other options for scripting languages, TCL syntax is very obscure to most people, with all the set and expr and dollar signs and lots of brackets etc. The only objective benefit it has is ease of embedding - but Lua is no slouch in that department either.
If this scripting interface is purely for you then you may as well go with TCL because Lua won't offer you anything new (unless object orientation is your thing). In the hands of a skilled user TCL is a reasonable tool. If, however, you expect less experienced users to use the system then go with Lua - the simpler syntax will buy them a lot of productivity.

A: Lua has LuaJIT, which is a JIT compiler that reaches C speeds on tight loops and is used for projects like Snabb Switch, where performance is critical (Snabb can handle gigabits per second, all processed through LuaJIT).  LuaJIT also has an easy-to-use FFI which allows one to access C functions without writing C stub code.
PUC-Lua (the standard implementation) supports recovering from running out of memory.  Neither LuaJIT nor TCL do.


text:
Q: Game Development in AIR suggested frameworks? I'm trying to expedite development for several iPad targeted mobile games I am developing. All will be coded using AS3 and Adobe AIR. I am familiar with several MVC frameworks, which may or may not be more than what I need. I have also heard of a dedicated framework called pushbutton engine, though the site is no longer live.
Can anyone share their recommendations on gameing frameworks for use with AIR?

A: For starters, make sure you're using Starling to maximise the rendering performance of your game.
Outside of that, I'm not a fan of any particular framework, mainly because I like the challenge and reward of developing as much of a game as I can from scratch. With that said, there is a good answer detailing a few frameworks here. Regarding MVC, I am not a fan of using that pattern in game development. It's a little too overkill for my liking.

A: Thanks
Also came across Ash an entity based framework
http://ashframework.org/

A: I you are comfortable with classic AS3 display list and want the best performance (compared to regular display list) you can get on the mobile devices, Starling is the way to go (though, there may be some other frameworks like Genome2D, that could possibly offer you more features, but also could lack some that Starling has). As for MVC, I agree with Marty that using MCV framework in whole game logic can be an overkill, but it can come very handy when you need to manage your ingame GUI and that`s what MVC frameworks are mostly used for. I use a combination of Feathers, a GUI framework based on Starling and Robotlegs along with Robotlegs-Starling extension and I feel pretty comfortable with that.
You probably will also need some other frameworks for physics, animation etc. I'd recommend to use Box2D or Nape to handle physics and if you don't mind additional layer of logic between your engine and physics lib you can use something like PhysInjector for easier physics handling. It works well with Starling and Box2D. As for skeletal animation, I didn't find anything better as Dragonbones - it comes bundled with Flash Pro IDE extension and that enables a really smooth workflow.


text:
Q: How to access table's last column in pure javascript or typescript Tried to access last column for each row in pure javascript not in jquery but not working.Anyone know please help to find the solution.
app.component.html:

    Company
    Contact
    Country

    Alfreds Futterkiste
    Maria Anders
    <select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select>

    Centro comercial Moctezuma
    Francisco Chang
    <select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select>

    Ernst Handel
    Roland Mendel
    <select><option>Select</option><option value="test1">Test 1</option><option value="test2">Test 2</option></select>

Demo: https://stackblitz.com/edit/amexio-breadcrumb-demo-jyxytf?file=src/app/app.component.ts

A: I am not sure why you want it in pure javascript way while you use angular,
Anyhow I am able to make a solution for you in pure javascript way with dom querySelector() methods ..
ngOnInit(){

  const gettable = document.getElementById("contentId").querySelector('table');
  const rows = gettable.getElementsByTagName('tr');

  for (let i=0; i<rows.length; i++)
  {
    const columns = rows[i].getElementsByTagName("td");
    const lastColumn = columns[columns.length - 1];
    const select = lastColumn.querySelector('select');
    select.addEventListener('change', this.getEvent.bind(this, select))
  }

}

getEvent(selectedItem){
  console.log(selectedItem.value);
  return event;
}

I have made a solution to retrieve each select box value at last of each row on selection..
Forked Stackblitz here ...
Update:
If you are using primeng table and if you need to retrieve the value from the table (p-table), You can use angular elementRef and get the value using,
const table = this.elementRef.nativeElement.querySelectorAll('p-table table');

And the table will gets initialized completely inside ngAfterviewInit lifecycle hook hence changed from ngOnInit() hook.
Also added ChangeDetectionStrategy to detect changes on select box value(s)..
Updated stackblitz with primeng: https://stackblitz.com/edit/primeng-tables-ubgkcm

A: Assuming you want to install an event change listener on the select element contained in the last td element of each row, you could do the following:
ngOnInit(){
    const table: HTMLTableElement = document.getElementById("contentId").querySelector('table');
    Array.from(table.getElementsByTagName('tr')).map(tr => tr.querySelector('td:last-of-type').querySelector('select').addEventListener('change', event => this.getEvent(event)));
}

Please have a look at the forked StackBlitz


text:
Q: Can I implement Active Directory when my application is hosted another place. I am using C# and Asp.net for developing the application and host same into some hosting service provider.
I need to authenticate users from Active Directory from different location.
Say for example my application is hosted on Asphost.com and the url of app is test.abc.co.in.The said sub domain is for Test client.
So how to use Test client Active directory users from my app.
Please suggest.

A: If I understand it correctly, this is not a C# or Asp.net problem, but a networking issue.
The Active directory is within the client's internal network and protected by firewalls that are not reachable from the location where you deploy the application.


text:
Q: Computing the socle of the ring $\langle \lbrace 1, \mathbb{Z}_{2}^{\mathbb{(N)}} \rbrace \rangle$ Consider the ring $\mathbb{Z}_{2}^{\mathbb{N}}$ and then consider the ring $R$ generated by $\mathbb{Z}_{2}^{\mathbb{(N)}}$ and $1$, that is $R= \langle \lbrace 1, \mathbb{Z}_{2}^{\mathbb{(N)}} \rbrace \rangle$, if I'm not wrong $R$ is seen as a sequence of all eventually $0's$ and $1's$ isn't? I aim to found the socle of $R$, that is, the sum of all simple modules of $R$ or the intersection of all essential modules of $R$. My guess is that $soc(R)$ is $\mathbb{Z}_{2}^{\mathbb{(N)}}$ itself, but in order to prove this I need to show that $\mathbb{Z}_{2}^{\mathbb{(N)}}$ is a simple submodule and is the only ideal of $R$ right? But I cannot prove neither of those.
Well my atempt to prove $\mathbb{Z}_{2}^{\mathbb{(N)}}$ is simple is because every $\mathbb{Z}_{2}$ is  simple. Also, wondering if $R$ is a $V-$ ring ? That is a ring where every simple module over that ring is also injective. Thanks!


text:
Q: Cannot load SQLite DLL on Windows 7 32bit PC I've currently used the System.Data.SQLite DLL in a .NET 4.0 x86 WinForms app. This is causing an issue on one of my client's PCs although I cannot reproduce this bug on my system. Both systems are 32bit Windows 7. How do I solve this? Things I've tried:

*

*Installing .NET 4.0 (the app is .NET 4)

*Installing all possible VC++ Runtime versions from 2005 to 2012

*Installing this particular VC++ Runtime that SQLite needs (fixed a similar issue on my PC)

*Adding the useLegacyRuntime attribute in the app.config XML

The error looks wierd because my app is obfuscated. The app works on my 32-bit PC and on my 64-bit development PC. It fails on a client machine. What can I do to solve this error?

A: In your project, solution explorer expands the Reference section and right click System.Data.SQLite then open properties, in the properties window, make sure copy local is set true . After that rebuild your project and run your client machine again

A: Turns out my SQLite DLL was outdated. I downloaded the latest from here and rebuilt my app with it. It worked on my PC as well as the client's. I had to install VC++ Runtime 2005 x32 on the Client Machine as well.


text:
Q: ¿Cómo obtener cadena enviada mediante método POST? Tengo una aplicación donde envió una cadena mediante un método POST a una un controlador genérico (.ashx ), lo que necesitó hacer es obtener esta cadena y asignarla a una variable
Mi código es el siguiente en la página desde donde envió:
protected async void Button4_Click(object sender, EventArgs e)
        {
            string respuesta = string.Empty;
            HttpClient client = new HttpClient();
            System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
            client.DefaultRequestHeaders.Accept.Clear();
            string miCadena = CadenaPost();
            StringContent contenido = new StringContent(miCadena, Encoding.UTF8, "application/json");
            HttpResponseMessage response = await client.PostAsync("http://localhost:50449/CallBackUrlApp.ashx", contenido);
            if (response.IsSuccessStatusCode)
            {
               respuesta = response.Content.ReadAsStringAsync().Result;
            }
            else
            {
                respuesta = response.IsSuccessStatusCode.ToString();
            }

        }

        private string CadenaPost()
        {
         string miCadena = "{ \"clave\":\"50611031800310140886100100001010000000019137761544\",\"fecha\":" +
                "\"20180311T15:19:5606:00\",\"indestado\":\"aceptado\",\"respuestaxml\":" +
                "\"PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4KPE1lbnNhamVIYWNpZW5kYSB4bWxucz0iaHR0cHM6Ly9\" }";
            return miCadena;
        }

Y aquí recibo la cadena pero no se como asignarla a una variable de tipo string :
 public void ProcessRequest(HttpContext context)
        {

            if (context.Request.RequestType.Equals("POST") )
            {
                string miCadena = string.Empty;
                //AQUI CODIGO QUE NESCITO PARA ASIGNAR EL CONTENIDO A LA VARIABLE miCadena
            }

        }

A: Tienes que leer el Request.InputStream
var stream = new StreamReader(HttpContext.Current.Request.InputStream);
stream.BaseStream.Seek(0, SeekOrigin.Begin);
var miCadena = stream.ReadToEnd();


text:
Q: use of superlatives What would be correct: Youngest and oldest soldier cut the cake or youngest and oldest soldiers cut the cake, knowing that we are referring to only one youngest and one oldest?

A: Either is possible, but I think soldiers is preferable.
Either way, you need the:

The youngest and the oldest soldiers cut the cake.

Both choices are possibly ambiguous: soldiers doesn't make it completely clear that there are exactly two; whereas soldier might in principle mean one single person who was both extremes (though in the real world that can't happen if there is more than one soldier).


text:
Q: nginx proxy_set_header isn't working Background
A docker container running a supervisord process with 2 processes started - nginx and uwsgi (yes I understand this may be doing docker 'wrong'. That's not the question)
The uwsgi hits a python flask app. This has a logger connected, and prints the headers dictionary to the info log.
I have a postman request that tests from my local box, hits the docker container, routes via nginx and hits the python app, with the info log appended.
Custom headers sent by postman are being logged (thanks to ignore_invalid_headers off;)
The Problem
I'd like to use nginx to decorate incoming requests with some further headers. No matter what I try I can't get it to work. None of the headers I add in the nginx conf seems to make it through to the flask app.
I've tried proxy_set_header or uwgi_param. No variant seems to work.
Please note - I want a request header. I believe add_header is for response headers.
nginx.conf:
user nginx;
worker_processes auto;
pid /run/nginx.pid;

events {
        worker_connections 768;
    }

http {
        include /etc/nginx/mime.types;

        access_log /var/log/nginx/access.log;
        error_log /var/log/nginx/error.log;

        include /etc/nginx/conf.d/*.conf;
        include /etc/nginx/sites-enabled/*;

        underscores_in_headers      off;
        ignore_invalid_headers      off;

        upstream myapp {
            server unix:/run/myapp.sock;
        }

        server {
            listen 80;
            location / {
                include                     uwsgi_params;

                uwsgi_pass                  myapp;

                proxy_set_header            x-proxy-set-header x-proxy-set-header-value;
                proxy_set_header            sampl-header ONE;
                uwsgi_param                 X-add-uwsgi-param x-added-uwsfi-param-value;
            }
        }
}

daemon off;

Any help would be hugely appreciated!!

A: So. Solved. As Richard Smith also found- proxy_pass doesn't work as I'm using uwsgi_pass for the custom protocol.
SO. this works:
location / {
            include                     uwsgi_params;

            uwsgi_pass                  myapp;
            uwsgi_pass_request_headers on;
            uwsgi_param HTTP_X_TESTING 'bar';
        }

And we're cooking on gas...
Air Punch


text:
Q: 'var' parameters are deprecated and will be removed in Swift 3 Alright so I just update Xcode to 7.3 and now I get this warning:

'var' parameters are deprecated and will be removed in Swift 3

How to fix this when I need to use the var in this function:
public func getQuestionList(var language: String) -> NSArray {
    if self.data.count > 0 {
        if (language.isEmpty) {
            language = "NL"
        }
        return self.data.objectForKey("questionList" + language) as! NSArray
    }

    return NSArray()
}

A: Have you tried to assign to a new var
public func getQuestionList(language: String) -> NSArray {
    var lang = language
    if self.data.count > 0 {
        if (lang.isEmpty) {
            lang = "NL"
        }
        return self.data.objectForKey("questionList" + lang) as! NSArray
    }

    return NSArray()
}

A: Just add this one line at the beginning of the function:
var language = language

and the rest of your code can stay unchanged, like this:
public func getQuestionList(language: String) -> NSArray {
    var language = language
    if self.data.count > 0 {
        if (language.isEmpty) {
            language = "NL"
        }
        return self.data.objectForKey("questionList" + language) as! NSArray
    }

    return NSArray()
}

A: public func getQuestionList(language: inout String) -> NSArray {
if self.data.count > 0 {
    if (language.isEmpty) {
        language = "NL"
    }
    return self.data.objectForKey("questionList" + language) as! NSArray
}

return NSArray()

}

A: A lot of people are suggesting an inout parameter, but that's really not what they're designed for. Besides, it doesn't allow calling the function with a let constant, nor with a string literal. Why don't you simply add the default value to the function signature?
public func getQuestionList(language language: String = "NL") -> NSArray {
    if data.count > 0 {
        return data.objectForKey("questionList" + language) as! NSArray
    } else {
        return NSArray()
    }
}

Just make sure to not call getQuestionList with the empty string in case you want the default language, but just leave out the parameter:
let list = getQuestionList() // uses the default "NL" language

A: The discussion of the removal of Var from a function parameter is fully documented within this submission on GitHub: Remove Var Parameters
In that document you will find that people often confuse var parameters with inout parameters.  A var parameter simply means that the parameter is mutable within the context of the function, while with an inout parameter the value of the parameter at the point of return will be copied out of the function and into the caller's context.
The correct way to solve this problem is to remove var from the parameter and introduce a local var variable.  At the top of the routine copy the parameter's value into that variable.

A: I think @Harris and @garanda answers are the best approach.
Anyway in your case, there isn't need of a var, you can do:
public func getQuestionList(language: String) -> NSArray {
    if self.data.count > 0 {
        return self.data.objectForKey("questionList" + (language.isEmpty ? "NL" : language)) as! NSArray
    }
    return NSArray()
}

A: https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html
In-Out Parameters
Function parameters are constants by default. Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can't change the value of a parameter by mistake. If you want a function to modify a parameter's value, and you want those changes to persist after the function call has ended, define that parameter as an in-out parameter instead.
You write an in-out parameter by placing the inout keyword right before a parameter's type. An in-out parameter has a value that is passed in to the function, is modified by the function, and is passed back out of the function to replace the original value. For a detailed discussion of the behavior of in-out parameters and associated compiler optimizations, see In-Out Parameters.
You can only pass a variable as the argument for an in-out parameter. You cannot pass a constant or a literal value as the argument, because constants and literals cannot be modified. You place an ampersand (&) directly before a variable's name when you pass it as an argument to an in-out parameter, to indicate that it can be modified by the function.
NOTE
In-out parameters cannot have default values, and variadic parameters cannot be marked as inout.
Here's an example of a function called swapTwoInts(::), which has two in-out integer parameters called a and b:
func swapTwoInts(_ a: inout Int, _ b: inout Int) {
    let temporaryA = a
    a = b
    b = temporaryA
}

The swapTwoInts(::) function simply swaps the value of b into a, and the value of a into b. The function performs this swap by storing the value of a in a temporary constant called temporaryA, assigning the value of b to a, and then assigning temporaryA to b.
You can call the swapTwoInts(::) function with two variables of type Int to swap their values. Note that the names of someInt and anotherInt are prefixed with an ampersand when they are passed to the swapTwoInts(::) function:
var someInt = 3
var anotherInt = 107
swapTwoInts(&someInt, &anotherInt)
print("someInt is now \(someInt), and anotherInt is now \(anotherInt)")
// Prints "someInt is now 107, and anotherInt is now 3"

The example above shows that the original values of someInt and anotherInt are modified by the swapTwoInts(::) function, even though they were originally defined outside of the function.
NOTE
In-out parameters are not the same as returning a value from a function. The swapTwoInts example above does not define a return type or return a value, but it still modifies the values of someInt and anotherInt. In-out parameters are an alternative way for a function to have an effect outside of the scope of its function body.

A: Here is another idea. My use case was to pass around a string array to append to it, for which the array must be passed in mutably. I did not want to have state in my class for this either. So I made a class that holds the array and pass that. Depending on your use case it may seem silly to have a class that holds just that one variable.
private class StringBuilder {
    var buffer: [String] = []

    func append(_ str: String) {
        buffer.append(str)
    }

    func toString() -> String {
        return buffer.joined()
    }
}

I only use append and joined methods on the array so it was easy to change the type with minimal other changes to my code.
Some example usage:
private func writeMap(map: LevelMap, url: URL) -> Bool {
    let buffer = StringBuilder()

    if !writeHeader(map: map, buffer: buffer) {
        return false
    }
    if !writeFloors(map: map, buffer: buffer) {
        return false
    }

    let content = buffer.toString()
    do {
        try content.write(to: url, atomically: true, encoding: .utf8)
        return true
    } catch {}
    return false
}

private func writeHeader(map: LevelMap, buffer: StringBuilder) -> Bool {
    buffer.append("something here ...\n")
    return true
}


text:
Q: Monogame - Sprite class I have a sprite sheet that contains a character walk cycle, and I have made a player class that allows the player to move and cycle through the walk animation, however the animation only works whilst walking to the right. I use the arrow keys to move up, down, left and right, meaning when I press any key, my player moves in the correct direction, but only performs the animation of walking to the right.
The current animation that works, has been called like this in the LoadContent() function:
spritesheet = Content.Load<Texture2D>("sprites2");

player = new Player(spritesheet, new Rectangle(0, 96, 32, 48),
new Vector2(100, 100), 4);

This does its job, as it calls each 4 sprites to complete the walking animation to the right, and new Rectangle(0,96,32,48) is the location cut out from the sprite sheet. However I need (for example) new Rectangle(30, 101, 65, 52) to be used also, which will correctly animate my character when the left arrow key has been pressed.
My question is, how would I get another location of the sprite sheet loaded, and then actually work when I press the correct key?
This is a very difficult question to ask and I very much apologize if it was difficult to understand. Accepting all edits to my question, and thank you in advanced.

A: I think a better way would be to pass the entire sprite sheet (or the entire section of the sprite sheet that contains the player's sprite) to the Player class and have a separate animation class handle how to select rectangles from the sheet. This is easier if you have frames that are all the same size, but it's doable if you don't.
In the animation class, you can set up a List<Rectangle> for each animation, MoveUp, MoveDown, MoveLeft, MoveRight, etc. and then call a method PlayAnimation() from your Player class whenever your player is performing one of those actions.
If you need each frame to have more information than just which Rectangle to display (for example, if frames have varying times), you can create a Frame class to hold that info.


text:
Q: Can one use 'subset' on data from .csv files of known structure but varying details? I'm trying to work on data from .csv files of known general format but varying group and measure names. I can get a data.frame using:
mydata=read.csv(file.choose(),header=T)
mydata

    GroupNames  Measure1    Measure2    Measure3  etc
1   group1      value1      value1
2   group1      value2      value2
3   group2      value3      value3
4   group2      value4      value4
5   group2      value5      value5
6   group3      value6      value6
7   group3      value7      value7

etc

Is there a way to subset the data and do the required tests if I don't know the numbers of groups or Measures (or their names) ahead of time?
I can get the first row using:
names(mydata)
[1] "GroupNames" "Measure1" "Measure2" "Measure3"

I can get the groups using:
Groups<-levels(factor(mydata[[1]]))
Groups
[1] "group1" "group2"  "group3"

I can create a subset using:
g1<-subset(mydata, GroupNames %in% Groups[1])
g1
    GroupNames  Measure1    Measure2    Measure3  etc
1   group1      value1      value1
2   group1      value2      value2

but how do I automatically put "GroupNames" in the above subset command without knowing it ahead of time? Current experiments using:
Titles<-names(mydata)

then
g1<-subset(mydata, Titles[1] %in% Groups[1])

fail, and return:
[1] GroupNames Measure1 Measure2 Measure3
<0 rows> (or 0-length row.names)

Sorry, but I am a beginner...

A: You're not far off, actually. You just need to pass an object instead of a character string when using subset. It should work if you skip the Titles business and just do this:
g1<-subset(mydata, mydata[[1]] %in% Groups[1])


text:
Q: Use a value from a subclass in my main class if a property in main class is set to false The sub class isn't derived from the main class, I'm just trying to differentiate them.
Even as I type this I can see it being impossible but I have some classes:
public class TransferServiceInformation {
    public int ProviderId { get; set; }
    public string PrePurchaseOverride { get; set; }
    public bool PrePurchaseOverrideEnabled { get; set; }
}

and
public class TransferServiceProviderInformation {
    public int ProviderId { get; set; }
    public string PrePurchaseInfo { get; set; }

And I want it so that if I ever try to access myTransferServiceInformation.PrePurchaseOverride and PrePurchaseOverrideEnabled == false it should return PrePurchaseInfo from the TransferServiceProviderInformation with the same ID.
Is something like that even possible?
I'm just having a thought that a getter that requires a TransferServiceProviderInformation passed as an argument might work, and throw an exception if the IDs don't match. Is that the only solution? The thing is, I'd rather not have to dig through all the (thousands of lines of) code to change all the places were I (or someone else) has called this property.

A: This is just an idea:
Make a static list with instances inside your class and auto-fill it with using the constructor. Then you can check this list from outside for instances with the same id.
public class TransferServiceInformation
{
    public int ProviderId { get; set; }

    private string prePurchaseOverride;
    public string PrePurchaseOverride
    {
        get
        {
            if(!PrePurchaseOverrideEnabled)
            {
                // Get instances from the other class where providerID matches
                var instance = TransferServiceProviderInformation.Instances.Where(i => i.ProviderId == this.ProviderId).FirstOrDefault();
                if(instance != null)
                return (instance).PrePurchaseInfo;
            }
            return null; // If no match found
        }
        set
        {
            prePurchaseOverride = value;
        }
    }

    private bool prePurchaseOverrideEnabled;
    public bool PrePurchaseOverrideEnabled { get; set; }
}

public class TransferServiceProviderInformation
{
    // Store your instances static
    public static List<TransferServiceProviderInformation> Instances { get; set; }

    public TransferServiceProviderInformation()
    {
        // Add every new instance to the list
        Instances.Add(this);
    }

    public int ProviderId { get; set; }
    public string PrePurchaseInfo { get; set; }
}

To-do's:
If an instance gets disposed, delete it from the list of instances.


text:
Q: gRPC in Java - How to recieve file content as response I'm new to gRPC programming. I need to write a gRPC client which receives file content sent from the gRPC server and send this content to web-page. As the file content is huge, I've set it as a stream.
Below is my .proto file
service LogService {
    rpc fetchLogContent(LogRequest) returns (stream LogResponse);
}

message LogRequest {
    string ip = 1;
    string fileName = 2;
}

message LogResponse {
    string ip = 1;
    string logContent = 2;
}

Now, in the client, when I use the blockingStub to access fetchLogContent, it returns an Iterator . I understand from the examples provided grpc.io - java, if there are list of response objects, (list of Feature objects in the example provided in link), an Iterator will be valid. But in my case, I need a single LogResponse which was sent as a stream. Please provide any suggestions/alternatives for this. Thanks in advance. :)

A: In your Method definition:
rpc fetchLogContent(LogRequest) returns (stream LogResponse);

The stream keyword means that you will get 0 or more LogResponse messages.  If the content is very large, what you can do is read chunks of the file (like 4kb) and send multiple LogResponse messages each with a part of the file.  The client side can read the chunks repeatedly, and piece it back together.
Since the ip field will likely not be changing each time, you can make you server only set ip on the first message.  On the client, just use the very first ip received.


text:
Q: sklean MLPClassifier: how to find relation/equation between output and input features I am still in learning phase of sklearn and need some help in understanding how to come with a relation between output and input. Using data I was able to train sklearn MLPClassifier.
clf = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes = (7,), random_state = 1)
#Print Coef
print clf.coefs_.shape
print clf.coefs_

The output looks like this:
Output print
Any help will be useful. Thanks!!

A: First of all, clf.coefs_ is a list with length n_layers - 1.
In your case, the length is 7-1 = 6.
The ith element in the list represents the weight matrix corresponding to layer i.
So if you type: clf.coefs_[0] this will return the weight matrix of the first layer.
More details here.

EDIT
The clf.coefs_ contains the weights that you need. Make sure that you understand how MLP works (see HERE ! )
A MLP looks like this:


text:
Q: Using Oracle SQL to generate nested XML Friends,
I am using Oracle 10g and I need to generate the results from a table using SQL in the following xml format:
<RESULTS>
    <ROW>
        <EMPNO>7839</EMPNO>
        <ENAME>KING</EMPNO>
        <SUBROWS>
            <ROW>
                <EMPNO>7369</EMPNO>
                <ENAME>SMITH</EMPNO>
                ... Rest of the EMP table records
                excluding KING
            </ROW>
        </SUBROWS>
    </ROW>
</RESULTS>

The rule is to show the record selected in the outer row and the subrows should contain all the other records excluding the one shown in the outer row. There is no hierarchy to the records.
In the example above King is selected in the outer row so the subrows should contain all the records from emp excluding King.
This query gives me the result set I need:
select e.empno,
       e.ename,
       cursor(select empno,
                     ename
              from emp where empno <> 7839)
from emp e
where empno = 7839

However when I try to generate XML from this using the following:
select xmlelement("RESULTS",
           xmlagg(xmlelement("ROW",
                      xmlelement("EMPNO", empno),
                      xmlelement("ENAME", ename),
                          cursor(SELECT xmlagg(xmlelement("SUBROWS",  xmlelement("ROW",
                                                     xmlelement("EMPNO", empno),
                                                     xmlelement("ENAME", ename)
                                                                                )
                                                           )
                                               )
                                  FROM emp
                                  WHERE empno <> 7839
                                  )
                            )

                 )
                 )
from emp
where empno = 7839

I get the following error:
ORA-22902: CURSOR expression not allowed
22902. 00000 -  "CURSOR expression not allowed"
*Cause:    CURSOR on a subquery is allowed only in the top-level
           SELECT list of a query.

I have tried using DBMS_XMLGEN:
SELECT DBMS_XMLGEN.getXML('select empno,
                                  ename,
                                  cursor(select empno,
                                                ename
                                         from emp
                                         where empno <> 7839) as SUBROWS
                            from emp
                            where empno = 7839')
FROM dual

Whist this outputs XML in the expected format it is doesn't show the correct element names.
Any help in solving this would be very much appreciated.
Thanks in advance

A: This does not work?
select xmlelement("RESULTS",
       xmlagg(xmlelement("ROW",
                  xmlelement("EMPNO", empno),
                  xmlelement("ENAME", ename),
                      (SELECT xmlagg(xmlelement("SUBROWS",  xmlelement("ROW",
                                                 xmlelement("EMPNO", empno),
                                                 xmlelement("ENAME", ename)
                                                                            )
                                                       )
                                           )
                              FROM emp
                              WHERE empno <> 7839
                              )
                        )

             )
             )
from emp
where empno = 7839


text:
Q: The selector of my NSTimer does not run. Why? My code is:
-(void) timerRun{...}

-(void) createTimer
{
   NSTimer *timer;
   timer = [NSTimer timerWithTimeInterval:1.0
                                   target:self
                                 selector:@selector(timerRun)
                                 userInfo:nil
                                  repeats:YES];
}

viewDidLoad
{
   [NSThread detachNewThreadSelector:@selector(createTimmer)
                            toTarget:self withObject:nil];
   ...

}

When I debug, the method createTimer runs ok, but the method does timerRun not run?

A: You have to schedule a timer for it to run. They get attached to a run loop, which in turn updates the timer as necessary.
You can either change createTimer to
[NSTimer scheduledTimerWithTimeInterval:1.0
                                   target:self
                                 selector:@selector(timerRun)
                                 userInfo:nil
                                  repeats:YES];

or add
[[NSRunLoop currentRunLoop] addTimer:timer forModes:NSRunLoopCommonModes];

A: The method signature that you use in scheduledTimerWithTimeInterval:target:selector:userInfo:repeats: must have an argument for the NSTimer as it passes itself as an argument.
You should change your message signature to:
(void)timerRun:(NSTimer *)timer;

You don't need to do anything with the argument, but it should be there. Also in createTimer the selector will become @selector(timerRun:) as it now accepts an argument:
timer = [NSTimer timerWithTimeInterval:1.0
                              target:self
                            selector:@selector(timerRun:)
                            userInfo:nil
                             repeats:YES];

A: Just creating a timer doesn't start it running. You need to both create it and schedule it.
You're actually going to have to do slightly more work than that if you want it to run on a background thread. NSTimers attach to NSRunloops, which are the Cocoa form of an event loop. Each NSThread inherently has a a run loop but you have to tell it to run explicitly.
A run loop with a timer attached can run itself indefinitely but you probably don't want it to because it won't be managing autorelease pools for you.
So, in summary, you probably want to (i) create the timer; (ii) attach it to that thread's run loop; (iii) enter a loop that creates an autorelease pool, runs the run loop for a bit and then drains the autorelease pool.
Code will probably look like:
// create timer
timer = [NSTimer timerWithTimeInterval:1.0
                                target:self
                              selector:@selector(timerRun)
                              userInfo:nil
                               repeats:YES];

// attach the timer to this thread's run loop
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];

// pump the run loop until someone tells us to stop
while(!someQuitCondition)
{
    // create a autorelease pool
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    // allow the run loop to run for, arbitrarily, 2 seconds
    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:2.0]];

    // drain the pool
    [pool drain];
}

// clean up after the timer
[timer invalidate];