Business Weeks within a date range

Question: I need a function in php that will calculate the business week in a specific format within a given date range.
Example:
startDate = 02-03-2009
endDate = 31-12-2010
Mar 2-6
Mar 9-13
Mar 16-20
Mar 23-27
Mar 30 - Apr 3
Apr 6 - 10
and so on...
Comment: -1 for being a duplicate question.
Comment: I don't think it's duplicate.
OP: Do you need the business working week or the official week? In other words, how do you want to handle shorter workweeks?
Comment: It should consider mon - fri, holidays don't matter and obviously sat and sun should be excluded. I looked at the recommended url that GregD mentions but it returns days i need the weekly range in the format specified in my original post
Comment: Then please update your original post, don't post a new question.
Comment: Also, this is not rentacoder - you might have to do some work to figure out how to adapt the code yourself.
Comment: @ricbax - I won't get into an edit war with you (since you rolled back my revision).  This question is close enough to several others on SO to be considered a dupe.
Comment: Is the input the two strings?  Are the dots present in the input but absent in the output?  What's the required output if the range starts on a Sunday?  On a Saturday?  What's the output if the range ends on a Sunday, or a Saturday?  What about starting on a Friday, or ending on a Monday?
Comment: List the 7 other questions please so i can examine the code, i am looking for an answer not statements and personal opinions. Thank you.
Comment: @GregD: I don't think this is an exact dup of http://stackoverflow.com/questions/336127/calculate-business-days-in-php; it is close, but not a duplicate.
Comment: @ricbax: be careful with your comments - that sort of attitude starts to get close to unreasonable expectations.  Although the questions pointed to are not exact duplicates, they are definitely pointers in the right general direction.
Comment: @Jonathan Leffler: No the periods should not be there and the format for the start/end dates can be a unix timestamp. The format below is what i need. The range is month day - fri and if the month changes in mid business week the format would be month day - next month day. oes that make sense?
Comment: I think your answer exists between this post: [Calculating days of week given a week number](http://stackoverflow.com/questions/186431/calculating-days-of-week-given-a-week-number) and this post: [Calculate business days in PHP](http://stackoverflow.com/questions/336127/calculate-business-days-in-php)
Answer: This isn't the direct answer - it's written in Perl (and Perl has some quirks of its own in this area).  However, it does, I think, produce the required output.
<code>#!/bin/perl -w
#
# Given two Unix-style timestamps (smaller, larger), produce a range of weeks.
# SO 613337

use strict;
use POSIX;

my($t1) = $ARGV[0];
my($t2) = $ARGV[1];

# Split given times into pieces
my($sec1,$min1,$hour1,$mday1,$mon1,$year1,$wday1) = localtime($t1);
my($sec2,$min2,$hour2,$mday2,$mon2,$year2,$wday2) = localtime($t2);

# Determine midday on Monday for starting week.
# Determine midday on Friday for ending week.
# Saturday rounds backwards; Sunday rounds upwards.
my($t3) = mktime(0, 0, 12, $mday1 - ($wday1 - 1) + 0, $mon1, $year1);
my($t4) = mktime(0, 0, 12, $mday2 - ($wday2 - 1) + 5, $mon2, $year2);

my($sec3,$min3,$hour3,$mday3,$mon3,$year3,$wday3) = localtime($t3);
my($sec4,$min4,$hour4,$mday4,$mon4,$year4,$wday4) = localtime($t4);

print "t1 = %10d; %04d-%02d-%02d (%d)\n", $t1+1900, $year1, $mon1+1, $mday1, $wday1;
print "t2 = %10d; %04d-%02d-%02d (%d)\n", $t2+1900, $year2, $mon2+1, $mday2, $wday2;
print "t3 = %10d; %04d-%02d-%02d (%d)\n", $t3+1900, $year3, $mon3+1, $mday3, $wday3;
print "t4 = %10d; %04d-%02d-%02d (%d)\n", $t4+1900, $year4, $mon4+1, $mday4, $wday4;

use constant secs_per_week  => 24 * 3600 * 7;
use constant secs_to_friday => 24 * 3600 * 4;

for (my($t) = $t3; $t < $t4; $t += secs_per_week)
{
    my($mon) = strftime("%b %e", localtime($t));
    my($fri) = strftime("%b %e", localtime($t + secs_to_friday));
    my($ans) = "$mon - $fri";
    $ans =~ s/^(\w\w\w)\s+(\d+) - (\1)\s+(\d+)$/$1 $2-$4/;
    $ans =~ s/  +/ /g;
    print "$ans\n";
}
</code>
Edited: fix month numbers in range 0..11 printed as 01..12.  Change handling of years, too.
Using midday on Monday and Friday and otherwise dealing only with days, I can ignore issues to do with switching between winter and summer (standard and daylight saving) time.
For example:
<code>$ perl weekdays.pl 1234567890 1324567890
t1 = 1234567890; 2009-02-13 (5)
t2 = 1324567890; 2011-12-22 (4)
t3 = 1234209600; 2009-02-09 (1)
t4 = 1324756800; 2011-12-24 (6)
Feb 9-13
Feb 16-20
Feb 23-27
Mar 2-6
Mar 9-13
Mar 16-20
Mar 23-27
Mar 30 - Apr 3
Apr 6-10
Apr 13-17
Apr 20-24
Apr 27 - May 1
May 4-8
May 11-15
May 18-22
May 25-29
Jun 1-5
Jun 8-12
Jun 15-19
Jun 22-26
Jun 29 - Jul 3
Jul 6-10
Jul 13-17
Jul 20-24
Jul 27-31
Aug 3-7
Aug 10-14
Aug 17-21
Aug 24-28
Aug 31 - Sep 4
Sep 7-11
Sep 14-18
Sep 21-25
Sep 28 - Oct 2
Oct 5-9
Oct 12-16
Oct 19-23
Oct 26-30
Nov 2-6
Nov 9-13
Nov 16-20
Nov 23-27
Nov 30 - Dec 4
Dec 7-11
Dec 14-18
Dec 21-25
Dec 28 - Jan 1
Jan 4-8
Jan 11-15
Jan 18-22
Jan 25-29
Feb 1-5
Feb 8-12
Feb 15-19
Feb 22-26
Mar 1-5
Mar 8-12
Mar 15-19
Mar 22-26
Mar 29 - Apr 2
Apr 5-9
Apr 12-16
Apr 19-23
Apr 26-30
May 3-7
May 10-14
May 17-21
May 24-28
May 31 - Jun 4
Jun 7-11
Jun 14-18
Jun 21-25
Jun 28 - Jul 2
Jul 5-9
Jul 12-16
Jul 19-23
Jul 26-30
Aug 2-6
Aug 9-13
Aug 16-20
Aug 23-27
Aug 30 - Sep 3
Sep 6-10
Sep 13-17
Sep 20-24
Sep 27 - Oct 1
Oct 4-8
Oct 11-15
Oct 18-22
Oct 25-29
Nov 1-5
Nov 8-12
Nov 15-19
Nov 22-26
Nov 29 - Dec 3
Dec 6-10
Dec 13-17
Dec 20-24
Dec 27-31
Jan 3-7
Jan 10-14
Jan 17-21
Jan 24-28
Jan 31 - Feb 4
Feb 7-11
Feb 14-18
Feb 21-25
Feb 28 - Mar 4
Mar 7-11
Mar 14-18
Mar 21-25
Mar 28 - Apr 1
Apr 4-8
Apr 11-15
Apr 18-22
Apr 25-29
May 2-6
May 9-13
May 16-20
May 23-27
May 30 - Jun 3
Jun 6-10
Jun 13-17
Jun 20-24
Jun 27 - Jul 1
Jul 4-8
Jul 11-15
Jul 18-22
Jul 25-29
Aug 1-5
Aug 8-12
Aug 15-19
Aug 22-26
Aug 29 - Sep 2
Sep 5-9
Sep 12-16
Sep 19-23
Sep 26-30
Oct 3-7
Oct 10-14
Oct 17-21
Oct 24-28
Oct 31 - Nov 4
Nov 7-11
Nov 14-18
Nov 21-25
Nov 28 - Dec 2
Dec 5-9
Dec 12-16
Dec 19-23
$
</code>
Comment: This looks great, thanks for your time and effort. I will try to port this to php.

Business Weeks within a date range


undefined method `new' for nil:NilClass - what's wrong with has_one nested association in rails 3.1.0?

Question: There are quote and test_plan in our app. The relationship is quote has_one test_plan and test_plan belongs_to a quote. In routes file it is:
<code>  resources :test_plans, :only => [:index]
  resources :quotes do
    resources :test_plans
  end
</code>
The problem is that @quote.test_plan returns nil (instead of an object) and @quote.test_plan.new() causes error saying undefined method new(). Any thoughts about the problem? Thanks so much.
Answer: <code>@test_plan = @quote.build_test_plan
</code>
creates a @test_plan object with foreign key set by @quote. This solves the problem.
Comment: There you go! I'm deleting my answer because you answered it better yourself. I'd use the singular form in the nested resource, though (resource :test_plan). That eliminates unnecessary ids from your routes. You go from /quotes/1/test_plans/1 to /quotes/1/test_plan.


Drop Down Menu in swift error

Question: I'm currently attempting to re-work this navigation dropdown menu
https://github.com/PhamBaTho/BTNavigationDropdownMenu
When I tried it, I'm getting an error
**fatal error: unexpectedly found nil while unwrapping an Optional value ( in the below line.)
var frame = CGRectMake(0, 0, titleSize.width + (self.configuration.arrowPadding + self.configuration.arrowImage.size.width)*2, self.navigationController!.navigationBar.frame.height)

I don't know how to make changes in storyboard for this set of code. I'm working on Xcode 7 beta 4 in swift.
any help is much appreciated.
Comment: This is similar to the question asked yesterday  http://stackoverflow.com/questions/33114651/attempting-to-get-reference-to-container-view-controller, I tried to copy the images too as said in the solution, even after that I'm getting the error. I don't know how to make changes in storyboard @jvolen2
Comment: @Sunny Shah I didn't get the changes u edited, all I find is the same code
Comment: When I use the Entry point in Navigation Controller, it works, but I'm using a Menu option of sidebar type. that doesn't work when I set the entry point to navigation controller.
Answer: I had the same problem but i fixed it
In your view Controller
 let menuView = BTNavigationDropdownMenu(title: "Sort By", items: items,navigation: self.navigationController!)

Then change in BTNavigationDropdownMenu class
 public init(title: String, items: [AnyObject])

To
public init(title: String, items: [AnyObject], navigation : UINavigationController)

And for navigationController variable change to
self.navigationController = navigation

Drop Down Menu in swift error


unable to connect the remote server with very simple httpWebRequest class app

Question: I used visual2010 to write a simple app with httpWebRequest class. The very first time of running the app, it'd work but after some successes, it was stuck with warning
"unable to connect the remote server".
I have read a lot in net but not much clues could done, almost said because the anti virus soft or firewall cause the problem, but when i'd turn off both, it still does not work. I also reinstall visual2010 but the problem still
<code>using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;

namespace new_httpWebRequest
{
class Program
{
    static void Main(string[] args)
    {
        string result ="";
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://my-favor.net");
        // line code problem below:
        `HttpWebResponse response = (HttpWebResponse)request.GetResponse();`
        var sr = new StreamReader(response.GetResponseStream() ?? System.IO.Stream.Null, Encoding.UTF8);
        result = sr.ReadToEnd();
        sr.Close();
        Console.Write(result);
        Console.ReadLine();

    }
}
</code>
}
Answer: finally, i find the solution just by adding this line:
request.Proxy = null;
I don't know why it work, just do it by god bless.
Comment: We encountered this issue when trying to make WebRequest from a web application which had a default proxy in web.config. This helped into getting to the web.config and adjusting the proxy.


Adding multiple values to a dictionary based on a key

Question: I want to create a graph of all the destinations from a point a to b
For this i wrote the code
from sys import stdin
starting,ending=input().split()
startnodes=set()
flights=[]
for line in stdin:
    x,y,z=line.split()
    flights.append([x,y,int(z)])
    startnodes.add(x)
    startnodes.add(y)
graph={}

for i in startnodes:
    for j in flights:
        if i==j[0]:
            graph.update({i:{j[1]:j[2]}})
print(graph)

Input:
Bangalore Hyderabad
Bangalore Mangalore 50
Mangalore Hydrabad 40
Bangalore Hyderabad 10000
Bangalore Chennai 4000
Chennai Hyderabad 4000

Output:
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000}, 'Chennai': {'Hyderabad': 4000}}

Expected Output
{'Mangalore': {'Hydrabad': 40}, 'Bangalore': {'Chennai': 4000,'Mangalore': 50}, 'Chennai': {'Hyderabad': 4000}}

The problem here is that i am expecting multiple Entries for the key 'Bangalore, but that isn't happening
Comment: `update()` only updates the outer dictionary by overwriting the value of a key with a new value for same key (and creating new keys). You have to check if the key exists already in outer dictionary and update the inner dictionary then.
Answer: Use this:
graph.setdefault(i, {}).update({j[1]: j[2]})

instead of this:
graph.update({i: {j[1]: j[2]}})


How to test a RxJs callback in jasmine

Question: I'm using NgbTypeAhead in my component where the callback must be a (text: Observable<string>) => Observable<any[]> . Now, I want to test the side effects of the search but I'm struggling to write that test in jasmine.
Can anybody help ? Thanks in advance.
component.ts
search = (text$: Observable<string>) =>
        text$
            .debounceTime(200)
            .distinctUntilChanged()
            .do((term: string) => {
                console.log("do 1", term)
                this.isSearching = true && term !== "";
                this.cd.markForCheck();
            })
            .map(term => {
                console.log("map", term)
                return term === ""
                    ? this.list
                    : this.filter(term)
            })
            .do(list => {
                console.log("do 2", list)
                this.searchResultsCount = list.length;
                this.cd.markForCheck();
            });

component.html
<input #initiativeSearch type="text" id="initiativeSearch"
    [ngbTypeahead]="search"/>

component.spec.ts
 it("should update searching flags", () => {
       // how do I test this ? here is what I tried
        let spyObj = jasmine.createSpyObj<Observable<string>>("text$", ["debounceTime", "distinctUntilChanged", "do", "map"]);

        spyObj.debounceTime.and.returnValue(spyObj)
        spyObj.distinctUntilChanged.and.returnValue(spyObj)
        spyObj.do.and.returnValues(Observable.of("blabla"), Observable.of([]))
        spyObj.map.and.returnValue(Observable.of([]))
        component.searchInitiatives(spyObj);

        expect(spyObj.debounceTime).toHaveBeenCalledWith(200);
        expect(spyObj.distinctUntilChanged).toHaveBeenCalledTimes(1);
        expect(spyObj.do).toHaveBeenCalledTimes(2);
    });

This logs spy text$.do to have been called 2 times. It was called 1 times. in the console and doesn't show any of the console.log
Comment: I dont think so, my function is a callback , it doesn't return any value itself,
Answer: It sounds like you are testing in the wrong direction. If you are unit testing, all you need to do is test a single component at a time.
You just need to test your search component directly. You can do something like this:
let observableSpy = {
  debounceTime: observableSpy,
  distinctUntilChanged: observableSpy,
  // ... repeat for all properties
};
let spyObj = jasmine.createSpyObj(observableSpy);

Then pass spyObj to your search function:
search(spyObj)

Finally, run some assertions:
expect(spyObj.debounceTime).toHaveBeenCalledWith(...);
// ... test all calls.

Doing it this way would be more of a unit test.
Comment: Thanks for the tip, I tried your suggestion but it still doesn't work (updated post). I think the issue now is that to correctly test the chaining of `Observable` methods, I have to mock these methods with their correct return values which is still not working for me.
I dont understand how I'm supposed to test the chaining in jasmine, any other idea?
Comment: In order to stub chaining methods, you always need to return the spyObj. I see that you're not doing this in your example above. Could that be your problem? Instead of `spyObj.do.and.returnValues(Observable.of("blabla"), Observable.of([]))`, do `spyObj.do.and.returnValue(spyObj)`.
Comment: Thanks. So, this works indeed and this way I can make sure that my chain  is correct. ... but I want also to check that the right callbacks are called by the `do` and `map`, any idea how to go about that ?
Answer: You can test this functionality but you will want to test it outside of Angular's "home zone" with the fakeAsync decorator.
That said I HIGHLY recommend against this. To me it seems you are trying to test ReactiveX operators which is not in scope for your unit test. When using these libraries it should be assumed that the library has it's own unit tests. You may want to test that the correct value in milliseconds is being passed in, but you don't actually need or want to test the debounceTime operator.
Please let us know if this makes sense, if not we can find other better ways to find coverage for your assertion, but testing the RXJS framework is really not something I'd recommend focusing your energy on.
Comment: I don't want to test the framework. Just make sure that the RxJs functions are called in the right order and that the `map` and `do` call the correct dependencies.

How to test a RxJs callback in jasmine


Grub not detected after Kubuntu install

Question: I have a pc with an MSI B550 Gaming Plus motherboard, with Windows 10 on it.
After trying to install Kubuntu with different ways to partition the SSD (install windows using the whole disc and have Kubuntu resize it, install windows on part of the disc and manually make a new partition for Kubuntu, etc.), none of these seems to install grub2 in a way that is detected.
I've tried boot loader installation to /dev/sda as well as /dev/sda1 (the ESP used by windows), but it does not seem to put grub2 there.
When I run BCDedit in Windows, it only shows the windows boot manager and the windows boot loader.
As the Kubuntu installation completes without errors I assume that grub2 is placed somewhere, but not not where the motherboard setup 'MSI click' can find it.
Is there a way to change this without reinstalling Kubuntu or windows?
EDIT: using a usb flash drive with boot-repair and the advanced option 'backup and rename Windows EFI files' I can boot into grub2, but then the Windows boot option does not do anything, it returns to the menu.
Maybe something is wrong with the menu option? It now reads:
<code>setparams 'Windows Boot Manager (on /dev/sda1)'
insmod part_gpt
insmod fat
set root='hd0,gpt1'
if [ x$feature_platform_search_hint == xy ]; then
  search --no-floppy --fs-uuid --set=root --hint-bios=hd0,gpt1 --hint-efi=hd0,gpt1 --hint-baremetal=ahci0,gpt1  409C-954a
else
  search --no-floppy --fs-uuid --set=root 409C-954a
fi
chainloader /EFI/Microsoft/Boot/bootmgfw.efi
</code>
What I understand of this makes sense. But then there seems to be a choice between moving the Windows files, getting grub2 but no Windows, and using boot-repair without moving the files and not getting grub2?
Comment: Boot-Repair looks like it is just reinstalling grub. But you have ubuntu entry in UEFI, and /EFI/ubuntu folder in ESP. Not sure why your UEFI should not see another UEFI boot option. What is MSI click. You should have an UEFI key for boot menu. Same key you use to select USB flash drive installer.
Comment: Are both installs UEFI? Please copy & paste the pastebin link to the BootInfo summary report ( do not post report), do not run the auto fix till reviewed. Use often updated ppa version with your USB installer or any working install over somewhat older ISO.
https://help.ubuntu.com/community/Boot-Repair &
https://sourceforge.net/p/boot-repair/home/Home/
Comment: Is UEFI most current firmware version and if SSD does that have latest firmware? Asus ROG Strix B450 E motherboard UEFI update worked
https://askubuntu.com/questions/1174679/cant-dual-boot-ubuntu-with-windows-10-in-ryzen-3600?noredirect=1#comment1960921_1174679
Asus Rog Strix B550 Disable IOMMU
https://askubuntu.com/questions/1265397/unable-to-install-ubuntu-20-04-lts-via-live-usb-ryzen-5-3600?noredirect=1#comment2141726_1265397
Comment: This is the boot report: http://sprunge.us/dffU9B -- so according to the first section something has definitely been put onto /efi but only /efi/Microsoft is found? I'm not sure what /dev/sda2 and /dev/sda4 are -- they were made automatically by windows.
Comment: You have GRUB_TIMEOUT=10, so ten seconds. If you want grub menu to always show you can change GRUB_TIMEOUT_STYLE=hidden to `GRUB_TIMEOUT_STYLE=menu` you may need to change UEFI settings (not UEFI menu)  to have ubuntu entry as first in boot order and make sure default boot mode is UEFI.
Comment: Only 10  years ago we had issues with too many entries. And it was a vendor's UEFI that said filled up when only 50% full. You can have many entries in UEFI, but grub typically overwrites a previous "ubuntu" entry on reinstall. Users can get confused as "ubuntu" UEFI entry used by other official flavors of Ubuntu and also many unofficial flavors based on Ubuntu. Others may have "grub" or name of distribution.
Comment: Thanks! But which of the two cases does this describe: the one that boots to grub2 but Windows does not start, or the one where grub is ignored by the windows bootloader?
Comment: Windows is not designed to be multiBoot capable except for multiple Windows. It does not do other operating systems. Grub will boot other systems, but Windows cannot be hibernated, fast startup on, nor encrypted (bitlocker).
Comment: Thanks @oldfred, there was an option to select grub instead of windows bootloader, it was somewhere else than the boot order. This means I can undo the boot-repair changes and choose windows from grub! If you type your comment as an answer then I can mark it as solved!
Answer: Windows is not designed to be multiBoot capable except for multiple Windows.
It does not do other operating systems.
Grub will boot other systems, but Windows cannot be hibernated, fast startup on, nor encrypted (bitlocker).
Both systems have to be in same boot mode or now almost all systems are UEFI, so both systems need to be installed in UEFI boot mode to gpt partitioned drives.
One advantage of UEFI, is that you should always be able to boot from UEFI boot menu. But always have good backups and both an Ubuntu live installer and windows repair/recovery drive to make repairs, if needed.
Comment: Thanks! In the end i would not have needed to do all the boot-repair stuff. I was confused by the UEFI boot order as it listed the main drive as 'windows' only. But there is a separate menu where you can select which boot manager to use (widows or grub). So the Ubuntu install would have worked out of the box with just that...

Grub not detected after Kubuntu install


SweetAlert not working with single quotes

Question: When using SweetAlert i'm having problems when using single quotes for example the code below works

But when using this with single quotes (within php echo) - it will not work
text: "You won't be able to revert this!", = ok
text: 'You won't be able to revert this!', = not ok.
is there a answer to this puzzle.
Answer: You have an unescaped quote in the word won't. If you wish to use single quotes to define your string, you should escape it, like so: 'You won\'t be able to revert this!'
Comment: Can't believe it. Been looking at that code for days.  Thanks


Is Firewall required in North Florida 2005 single story home?

Question: Is Firewall required?
 Home inspector; Inspecting a single story 2005 home in Northern Florida.  Garage panel attic access. I noticed the lack of firewall separating the garage from living space.
Note: Garage not insulated and attic cooler than outside temperature.
Thermal imaging read several degrees cooler than outside. "Attic felt cool"
Is Firewall required? and how would AC be leaking into attic?
Comment: I won't post this as an answer because this would be state-specific, and I'm in Va. The initial major code change was 2003. Not sure if Fl took it then or not, but we did.
Comment: Leaking AC has to be physically investigated. Could one, or a combination of a hundred things. Joints, lack of insulated duct, diy duct, lack of insulation, etc.
Answer: The only requirement for a firewall that I am aware of, between the garage and living space was a layer of 5/8" fire code sheetrock over the whole wall that separates the garage from the living space. If there is a living space above the garage, then the ceiling needed it too. Although I think the latter statement is state specific. I believe in WA state it is not needed on the ceiling, at least in a new home I was working on, but in Maryland it was required.
The door into the garage from the house needed to be rated to withstand a 20 minute fire exposure.
Answer: Face it: ducts leak
Unless you go to the work of mastic'ing the snot out of your ducts, they'll leak in the tens of % -- it doesn't matter whether they were put in by a DIYer or a pro, or whether they were left bare or smothered in insulation.
The common Florida habit of putting the air handler in the attic just makes the matter worse.
As to the fire separation? In general (straight 2015 IRC), a 20-min door and regular 1/2" drywall suffice, unless there's habitable space above (which requires the 5/8" type X stuff on the garage ceiling).


A-Frame: How to detect that the user has quit AR mode

Question: In the A-Frame project I have been developing, the user is first prompted whether or not they want to play the game in an AR mode or in a traditional non-AR 3D mode.
When the user unexpectedly exits AR mode (by pressing back and exiting fullscreen, for example), we need to be able to detect for this as we need to reconfigure the camera for traditional 3D again.
Is there an event in A-Frame we can subscribe to (or a property we can check) that is fired when the user exits AR mode?
Answer: You can listen to the exit-vr event


Trying to fix Docker "cgroup doesn't match target mode" with adding kernel boot parameter

Question: I have problem with running certain Docker images:
docker: Error response from daemon: failed to create shim: OCI runtime create failed:
container_linux.go:380: starting container process caused: process_linux.go:545:
container init caused: process_linux.go:508:
setting cgroup config for procHooks process caused: resulting devices cgroup doesn't match target mode: unknown.

So, after searching I found this solution
I don't know can this solution help me to solve Docker error,
but all I need is to add a kernel boot parameter.
"... systemd.unified_cgroup_hierarchy=0"

The problem is how to do that?
I found many tutorials with boot grub edit, but I can't find which file I need to edit?
I have Ubuntu 18.04.3 LTS (GNU/Linux 4.15.0 x86_64), with a terminal only. No GUI.
This is a VPS server and I only can use the terminal to edit.
Can anybody help me how and where to add this kernel parameter?
Answer: You have Grub tagged so I assume you are using Grub. Kernel commands are usually set in the /etc/default/grub file.
Edit the file:
sudo nano /etc/default/grub

and edit the following line:
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"

to say this instead:
GRUB_CMDLINE_LINUX_DEFAULT="systemd.unified_cgroup_hierarchy=0 quiet splash"

Press CTRL+o to save the changes and press CTRL+x to exit nano.
Then, run the following command to update grub:
sudo update-grub

It should be noted that adding this to GRUB_CMDLINE_LINUX_DEFAULT will allow you to boot without this option using recovery mode. This way, if the argument messes things up, you'll still have the ability to boot without the kernel command.
Comment: When I use: ''sudo nano /etc/default/grub', I see a completely blank file.
I am not sure If I have the grub. How can I check this?
Comment: @Aleksandar That's strange. You should update the question and specify which type of VPS server you are using and maybe someone else can help here. It looks like there may be a different type of grub used here or something else. I'll leave this answer here for others who might be using grub.


How to add a custom event tracking with Google Analytics

Question: Google Analytics custom event not working, as it is not tracked on Google Analytics statistic View. I written code for onclick, but it is not tracked. Here is my code:

Click Here

Answer: This is because you are using the old syntax gaq.push, which is for the Classic Analytics. You have actually implemented the newer version of GA called Universal Analytics, which uses a different syntax for sending events.
The correct code to use, according to the Google Developer information, it should be written like this:
ga('send', 'event', 'category', 'action', 'label', value);

So, using your example, I'd write it something like this:
ga('send', 'event', 'Popup', 'Click','Step1');

Event, category and action are mandatory, while label and value are optional.
Comment: The link appears to be dead
Comment: Appears to be working for me when I clicked it just now.
Comment: Still dead for me, but it works on incognito window somehow


How do I run a standalone program in OpsWorks?

Question: I'm sure there's a simple answer. Our program is an executable jar file, and we have a shell script wrapper for it.

OpsWorks grabs the distribution zip file from S3
We're trying to unzip that and run the script file located in bin/run_server.sh

I'm currently down the path of writing a custom deploy recipe for it, running on a layer of type "Other".
Here is my attempt :
include_recipe 'deploy'

node[:deploy].each do |application, deploy|

    # assume the zip file has been extracted at this point,
    # and the CWD is the extracted contents
    execute "run the server" do
        command 'bash bin/run_server.sh'
        action :run
    end
end

This fails claiming that it cannot find bin/run_server.sh.
Thanks in advance.
Answer: Have you tried setting cwd explicitly?
execute "run the server" do
    command 'bash bin/run_server.sh'
    cwd "/path/to/your/stuff"
end

Comment: I don't know where the zip file is downloaded. I've ssh-ed into the instance and couldn't find any trace of it, or its contents.
Comment: It should be in node[:deploy][application][:deploy_to], but maybe you're missing a deployment step since you're using a custom layer. Can you share more details about your custom recipe setup and app configuration?
Comment: I think what's happening is that setup includes the deployment step, but the app has yet to be deployed. I think to achieve the desired effect I need to add a deploy hook to my app itself, so that chef runs it as soon as it receives application code, not on setup.


Is there anyway to make the AI defend or evade?

Question: I'm finding the special attacks from bosses to be very difficult to deal with since the AI doesn't seem smart enough to actually block or evade these attacks. I can manage against a single-target special by switching to the AI and forcing them to block, but special attacks which hit the entire party seem to be impossible to deal with. I have a hard time believing there is no way for me to defend my party against these attacks, which leads me to believe I'm doing something wrong.
Is there some way to force the AI to block or evade?
Answer: You can use the "All Out Defense" command (this is a story reward) this makes your AI party members focus on using the Defend/Evade commands and will also focus on healing, but it really burns through MP.
Like other commands there's a timer, so you'll have to select it again if you need it, when it run out.


Spring Flux Reactor async consumer on complete

Question: I'm investigating how Spring Reactor flow works and have some scenario which can't handle.
I want to perform async action when Mono is completed and ready to return result, so I don't block request thread anymore. I don't care about exeption or result in that async action, that's consumer.
In example below I want image procesing to happen in async way after result is returned:
log.debug("Creating image for quote: [{}]", quoteId);
return Mono.fromFuture(quoteRepository.findById(quoteId)
                       .flatMap(original -> {
                           log.debug("Saving image meta for quote: [{}]", quoteId);
                           original.setImageUrl(imageMeta.getImageUrl());
                           return quoteRepository.save(original);
                       })
                       .toFuture()
                       .whenCompleteAsync((quote, ex) -> {
                           log.debug("Processing image meta for quote: [{}]", quoteId);
                           imageService.processImage(quote.getImageUrl());
                       }, taskExecutor))
            .doOnSuccess(quote -> log.debug("Image meta is saved: [{}]", quote.getId()));

But from log statements I gotresult isn't returned until image processing is finished.
23:32:04.974 DEBUG [reactor-http-nio-2] Creating image for quote: [32]
23:32:05.319 DEBUG [reactor-tcp-nio-1] Saving image meta for quote: [32]
23:32:05.340 DEBUG [task-executor-thread1] Processing image meta for quote: [32]
23:32:07.337 DEBUG [task-executor-thread1] Image meta is saved for quote [32]

I also heard something about using schedulers, but this hasn't helped, maybe I'm using incorrectly that:
return quoteRepository.findById(quoteId)
                       .flatMap(original -> {
                           log.debug("Saving image meta for quote: [{}]", quoteId);
                           original.setImageUrl(imageMeta.getImageUrl());
                           return quoteRepository.save(original);
                       })
                       .subscribeOn(Schedulers.elastic())
                       .doOnNext(quote -> {
                           log.debug("Processing image meta for quote: [{}]", quoteId);
                           imageService.processImage(quote.getImageUrl());
                       })
                       .doOnSuccess(quote -> log.debug("Image meta is saved: [{}]", quote.getId()));

Result still isn't returned before image is processed.
23:32:04.974 DEBUG [reactor-http-nio-2] Creating image for quote: [32]
23:32:05.319 DEBUG [reactor-tcp-nio-1] Saving image meta for quote: [32]
23:32:05.340 DEBUG [reactor-tcp-nio-1] Processing image meta for quote: [32]
23:32:07.337 DEBUG [reactor-tcp-nio-1] Image meta is saved for quote [32]

Spring Boot: 2.3.5
Reactor core: 3.3.11
Answer: I've accomplished what I wanted to do in a way:
return quoteRepository.findById(quoteId)
                              .flatMap(original -> {
                                  log.debug("Saving image meta for quote: [{}]", quoteId);
                                  original.setImageUrl(imageMeta.getImageUrl());
                                  return quoteRepository.save(original);
                              })
                              .doOnSuccess(quote ->
                                                   taskExecutor.execute(() -> {
                                                       log.debug("Processing image meta for quote: [{}]", quoteId);
                                                       imageService.processImage(quote.getImageUrl());
                                                   })
                              )
                              .doOnSuccess(quote -> log.debug("Image meta is saved: [{}]", quote.getId()));

But don't we have something native to Spring Flux/Reactor to do the thing equal for taskExecutor?


Terminal emulator that has "code folding"

Question: Sometimes I regret running ls in a directory containing a lot of files because it produces too many lines in my terminal. So I'd like to be able to collapse & expand the output of each command whenever I like. This is for better readability and would (potentially) happen after the command is run.
I am not looking for suppressing / hiding the output in advance (e.g. either using redirection like &> /dev/null or simply putting | less at the end of my command).
I feel this could be a feature of the terminal, as it is for some text editors or IDEs. Is there one solution where I can toggle the visibility in this way?
Edit: I mean something like this:
In the wxMaxima software, the outputs are printed on the screen like this.

However, when you click on the small triangle on the left of a line, you can collapse the output temporarily and you only see the input.
Comment: collapse and expand how ? can you clarify ? you want to limit output to only x number of lines ?
Comment: This feature request is already filed: https://bugzilla.gnome.org/show_bug.cgi?id=769420. I don't think it will be implemented in gnome-terminal in the foreseeable future, though.
Comment: I see now, the screenshot does help to clarify.  In that case, you're looking for a terminal emulator with that feature. You may or may not know that there's many terminal emulators, and up to now I've not heard of the one that has this feature. The default one in Ubuntu, the `gnome-terminal` is fairly simplistic and is purposely build so. You could create a feature request (https://bugs.launchpad.net/ubuntu/+source/gnome-terminal/+filebug) but I guarantee they won't implement it.
Comment: collapse so that I don't see the output at all, only the command I typed (see update)
Comment: I found http://superuser.com/questions/649884/clear-terminal-output-of-last-command-only which mentions Final Term, but that seems dead
Answer: I have being looking for this feature for years as but I am afraid to say that at this moment there is no usable terminal that implements this feature.
I read that there were plans to add it to iTerm2 but that moment is still on wishlist.
Comment: [Warp](https://www.warp.dev/) has a feature similar to this, but it only ships for macOS at the moment.


Extract substring starting with the comma, moving right, until you hit a space

Question: I have a series of addresses in one column.  I am trying to extract each component (Street Address, City, State, and Zip Code) into a separate columns.
I was able to extract the zip codes rather easily with `=RIGHT(A1, 5)'.  However, I am having a hard time extracting the city.  All of the rows follow the same format below.  My idea is to find the comma, and extract the substring from right to left until getting a space.  How do I do this?
Here is an example of what the data looks like:
<code>2209 Fake Street Arlington, TX 76015
3100 Fake Street Bedford, TX 76021
3558 Fake Street Flower Mound, TX 75028
4230 Fake Street Fort Worth, TX 76119
2662 Fake Street Bedford, TX 76021
</code>
Comment: That will only work with cities that have one word.  And looking for the type of address (road, street, etc) for the start of the city name, won't work when there is no type.  I think if your layout has no unique separator between street and city, you'll probably need a zip code lookup table to get the city.
Comment: Thanks, Ron.  I used your idea and it worked perfectly.
Answer: That will only work with cities that have one word. And looking for the type of address (road, street, etc) for the start of the city name, won't work when there is no type. I think if your layout has no unique separator between street and city, you'll probably need a zip code lookup table to get the city.
In addition, you will need code to resolve issues where two different cities have the same zip code.  For example, in Texas, 76119 could refer to FORT WORTH, FOREST HILL, or FT WORTH.  And you may need code to handle misspellings.
It might be that these are few enough to allow manual correction.


In a struct with 2 Vecs, how can one Vec's elements hold immutable borrows of the other's?

Question: The code goes something like this:
struct Model {
    // This is Vec #1.
    recorded_curves: Vec<Curve>,
    // This is the Vec whose elements hold references to #1's.
    ongoing_comparisons: Vec<Comparison>,
}

struct Comparison {
   // `recording` references an element in `Model.recorded_curves`.
   recording: &Curve,
   // ...
}

And later, inside a function called event(), I have this:
for recording in model.recorded_curves.iter() {
    model.ongoing_comparisons.push(Comparison {
        recording,
        // ...
    });
}

Rust demands I add lifetimes to Comparison, but to do that, I have to (as far as I know) use the same lifetime for Model. Afterward, the structs looked like this:
struct Comparison<'a> {
    recording: &'a Curve,
    // ...
}

struct Model<'a> {
    recorded_curves: Vec<Curve>,
    ongoing_comparisons: Vec<Comparison<'a>>,
}

fn event<'a>(_app: &App, model: &'a mut Model<'a>, event: Event) { /* ... */ }

Unfortunately, this brings its own problem. I'm using nannou, where I register event() as a callback, and it doesn't let me use my custom lifetime ('a):
error[E0308]: mismatched types
  --> src/main.rs:17:30
   |
17 |     nannou::app(model).event(event).simple_window(view).run();
   |                              ^^^^^ one type is more general than the other
   |
   = note: expected fn pointer `for<'r, 's> fn(&'r nannou::App, &'s mut Model<'_>, nannou::Event)`
              found fn pointer `for<'a, 'r> fn(&'r nannou::App, &'a mut Model<'a>, nannou::Event)`

Is there a way to accomplish this without using lifetime annotations? Otherwise, could I somehow make the program work with the annotations?
Comment: Does this answer your question? [Why can't I store a value and a reference to that value in the same struct?](https://stackoverflow.com/questions/32300132/why-cant-i-store-a-value-and-a-reference-to-that-value-in-the-same-struct)
Comment: @ChayimFriedman What a fantastic answer! However, I'm not so sure it solves my problem (though I'll have to reread it a few times to fully grasp it). The most obvious fixes they suggest are crates that don't work on mutating vectors, which are exactly what I have. Otherwise, they recommend using reference counting. It's great to have a lead, but I wouldn't say it answers my question.
Comment: If you need to mutate the vectors, and you cannot use reference counting/redesign your code, then you have to use `unsafe`.
Comment: @ChayimFriedman I'll use reference counting if I have to—and if I can—but I think it's fair to say the question, "Is there a way to accomplish this without using lifetime annotations?" means the answer, "Take a look at reference counting," counts as a comment more than an actual answer.
Comment: If that's the question then the answer is "No". But I do think the duplicate covers that.
Comment: @ChayimFriedman Does it? "There is a special case where the lifetime tracking is overzealous: when you have something placed on the heap. ...Some crates provide ways of representing this case, but they require that the base address never move. This rules out mutating vectors, which may cause a reallocation and a move of the heap-allocated values. ...In other cases, you may wish to move to some type of reference-counting, such as by using `Rc` or `Arc`." I'll reread the answer, but this is what relevant (to this) information I was able to pull out.
Comment: OK, maybe it does not. I will not close this as a duplicate, but anyway the answer is "No".
Comment: The answer to 'Is there a way to accomplish this without using lifetime annotations?" is: Well, you can't even accomplish this with lifetime annotations. You can only accomplish this with `unsafe` code. This is sadly what happens to most programmers that switch from other languages to Rust: you have to learn new programming paradigms, because many of them aren't considered safe in Rust. For the your specific problem, a two common solutions exist: *Reference Counted Smart Pointers* and *Indices* (meaning: store the position in the array of the item you mean)
Comment: @Finomnis Could you point me to a "Rusty" alternative to this, then? I don't mind learning a new, safer paradigm. If you need more context, you need only ask.
Comment: As I said, either *Reference Counted Smart Pointers* (`Rc`/`Arc`) or *indices* (as, normal `usize` that store the position of the actual item in the array
Comment: But if you want to stick to the code layout you have on hand, I'd use `Rc`. The overhead is really not big enough to seriously worry about it.
Answer: There are multiple solutions to this problem, but in your case I would probably use Reference Counting Smart Pointers.
Depending on your usecase, there are several options for the members of your recorded_curves vector:

Rc<Curve> - single threaded, immutable
Rc<RefCell<Curve>> - single threaded, but mutable. Fails at runtime if you want to borrow it twice simultaneously.
Arc<Curve> - multi threaded, immutable
Arc<Mutex<Curve>> - multi threaded, mutable, synchronized via mutex

My educated guess is that you probably have a single threaded, but mutable situation, so I'd do:
struct Model {
    // This is Vec #1.
    recorded_curves: Vec<Rc<RefCell<Curve>>>,
    // This is the Vec whose elements hold references to #1's.
    ongoing_comparisons: Vec<Comparison>,
}

struct Comparison {
   // `recording` references an element in `Model.recorded_curves`.
   recording: Rc<RefCell<Curve>>,
   // ...
}

If you had two different structs, one holding the data and one holding the references, and the compiler can prove that the data definitely outlives the references, then it's absolutely no problem to hold references to vector elements.
Here is an example to demonstrate that. It has two structs, DataVec and RefVec, one holding the data and the other one holding mutable references. Then, the RefVec gets passed into a function that sorts it and then stores the sorted positions in the RefVec. You can see that this modifies the original DataVec, so that every element now holds the position it would be in after sorting.
#[derive(Debug)]
struct Data(usize);

#[derive(Debug)]
struct DataVec {
    elements: Vec<Data>,
}

#[derive(Debug)]
struct RefVec<'a> {
    elements: Vec<&'a mut Data>,
}

fn convert_to_order(data: &mut RefVec) {
    data.elements.sort_by_key(|el| el.0);
    for (pos, element) in data.elements.iter_mut().enumerate() {
        element.0 = pos;
    }
}

fn main() {
    let mut datavec = DataVec {
        elements: [5, 8, 3, 7, 9, 4].into_iter().map(|e| Data(e)).collect(),
    };

    println!("Data before: {:?}", datavec);

    let mut refvec = RefVec {
        elements: datavec.elements.iter_mut().collect(),
    };

    println!("Reference Vector: {:?}", refvec);

    convert_to_order(&mut refvec);

    println!("Reference Vector after sorting and labeling: {:?}", refvec);
    println!("Data after: {:?}", datavec);
}

Data before: DataVec { elements: [Data(5), Data(8), Data(3), Data(7), Data(9), Data(4)] }
Reference Vector: RefVec { elements: [Data(5), Data(8), Data(3), Data(7), Data(9), Data(4)] }
Reference Vector after sorting and labeling: RefVec { elements: [Data(0), Data(1), Data(2), Data(3), Data(4), Data(5)] }
Data after: DataVec { elements: [Data(2), Data(4), Data(0), Data(3), Data(5), Data(1)] }

Note that if you'd switch the last two println!()s, you would get an error. You can only read datavec after refvec was dropped, which automatically happens between the two prints. The reason is that once a value is borrowed mutably, you can't access the original value at all until that borrow is returned.
Comment: Don't change `recorded_curves` to an array. Arrays are stored on the stack and serve a very specific purpose. For everthing even remotely more general-purpose, use vecs instead, as they live on the heap.
Comment: @verified_tinker Added an example to demonstrate how it would work if you split your struct in two.
Comment: I finally understand how I'd use `Rc` in this case. I'll probably go with that for now and switch to `Arc` once I incorporate multi-threading. This is supposed to be a performance-critical section, so I'm a little worried about the reference counting, but it probably won't become a problem (and I'd probably need to use `Arc` once I added multi-threading anyway). I suppose I'll cross that bridge if or when this bottlenecks the program. Thank you.
Comment: Well, two annotations for what you just said: 1) don't assume, benchmark ;) and 2) if this is too slow, you probably want to refactor your code in general and avoid the necessity to store things in the `ongoing_comparisons` vector. It's no problem keeping a vector of references, as long as you don't store it in the same struct, but instead in a temporary struct that proveably lives shorter than the struct with the original values. But hard to say without knowing your actual code and project.
Comment: I'll benchmark it for sure. The problem with keeping the two vectors in different structs is that Nannou forces you to use only one struct—`Model` in my case—for your data. At least, I don't know how to change that behavior. Neat separation of concerns, but evidently also limiting. I'm also considering converting `recorded_curves` into an array, but I don't know if that's possible, since its size is determined at runtime and depends on the number of files in a directory (which it reads and stores in memory).
Comment: As I don't think Nannou is geared towards maximum performance, I don't think the use of `Rc` will be much of a problem.
Comment: That's true. I'm only prototyping for now. Most likely, once I'm done and integrate the code into a game engine, I'll be free to refactor it.


Knockd listen to a specific IP address

Question: In Knockd how do I listen to a specific IP address from an interface that has multiple IP addresses?
Knockd only has the option to listen by interface but not an IP address.
Example
Interface eth0 has 3 IPs

126.96.36.199
22.214.171.124
126.96.36.199

My target listen IP is 220.127.116.11 but if I start knockd with eth0 interface it will listen to the first ip 220.127.116.11.
Comment: What is knockd ?
Comment: @SorenA https://linux.die.net/man/1/knockd a port-knock server
Answer: Knockd listens to the link layer, in the OSI model, this is layer 2.  Layer 3 is where ip addresses live.  Therefore, you will not be able to listen to only a single ip address.
The work around would be to create a MACVTAP, therefore creating a new layer2 device.  Move the IP address of 220.127.116.11 to that interface, and running Knockd on the new interface eg macvtap0.
ip link add link eth0 macvtap0 type macvtap
ip address del 184.108.40.206/<insert the subnet> dev eth0
ip address add 18.104.22.168/<insert the subnet> dev macvtap0

Note: creating a macvtap, creates an interface with a new mac address, depending on your ISP/Upstream provider this may create an issue.  If this occurs, add a route for outbound traffic from 22.214.171.124, to route through one of your other external IP address. So your upstream provider will see the mac address of the physical device. (this is the easiest way, I know there are other ways to have outbound traffic use the main mac address)
Comment: I found out the issue is knockd that comes in ubuntu 20 is v7.0 which only binds to the first IP of the interface and not all of it, the latest v8.0 binds to all of the interface IPs which solves my issue. Your method and idea is still valid for v7 and was similar to what I was trying to figure out ideas on how to implement it.

Knockd listen to a specific IP address


What is the role of if statements in this code can somebody explain?

Question: Please explain the meaning of the second if statement.
What i am asking is that meaning of if([self.delegate textFieldShouldClear:self]) <-- This line
 SEL clearselector = @selector(textFieldShouldClear:);

 if([self.delegate respondsToSelector:clearselector]){
     if([self.delegate textFieldShouldClear:self]){// (Explain This If please)?
         NSLog(@"Delegate Methods");
         self.txtRef.text = @"";
     }
 }

Thanks in advance.
Comment: The method in question is https://developer.apple.com/reference/uikit/uitextfielddelegate/1619594-textfieldshouldclear but I'm not sure what sort of explanation you are looking for.
Comment: Possible duplicate of [when to use respondsToSelector in objective-c](http://stackoverflow.com/questions/3697058/when-to-use-respondstoselector-in-objective-c)
Comment: The `If` says `textFieldShouldClear` is set to return YES or, not, if `YES` it will clear the textfield, else no.
Comment: Thanks guys for the answers
Answer: Generally this method return BOOL value which indicates that this class has implemented or inherited provided delegated method and by this BOOL value YES or NO we will call it to notify or update data.
Its generally use to prevent from crash if that class has not implemented that method will not crash our app.
In your case your checking UITextField Delegate method is implemented by that class or not if YES than you will call that method through delegate object.
EDIT:
As per your question update textFieldShouldClear method is to check that user has override textFieldShouldClear this method and ask user that textFiled should clear or not.
Apple Source :

Asks the delegate if the text field's current contents should be
  removed.

Reference Link : https://developer.apple.com/reference/uikit/uitextfielddelegate/1619594-textfieldshouldclear
Hope this will help to understand this method.
Answer: That delegate method return true only then if contain will execute.
{
    NSLog(@"Delegate Methods");
     self.txtRef.text = @"";

}

User may return false if he don't want to clear textfield for some particular case.


Error while installing Nokia Suite

Question: Dependency is not satisfiable gambas2-runtime (>=1.9.48) error while installing Nokia Suite. What should I do?
I am using Ubuntu 13.10. Please recommend me a software application similar to Nokia PC Suite for connecting my PC through Nokia Mobile.
Comment: Which version of Ubuntu are you using ?
Answer: gambas2-runtime is in the Ubuntu Software Center for Ubuntu 12.04. For later versions of Ubuntu Gambas2 has been updated to (superseded by) Gambas3. If this doesn't work, you could try installing Nokia Suite on a Windows PC if you have one. Nokia Support Discussions for Nokia Suite is mainly for Windows users.
You can connect your Nokia phone in Ubuntu using wvdial from the Ubuntu Software Center. For information about how to connect your Nokia phone using  wvdial see this step-by-step tutorial: Connect your Nokia phone with Linux without PC Suite.
All of the steps in the tutorial have to be run from the terminal. To open the terminal use the keyboard combination Ctrl+Alt+T. The terminal commands in the tutorial are highlighted in red letters. For example to run the first command in the tutorial, connect your Nokia phone to your computer via data cable, open the terminal and type:
lsusb

This command will list all USB devices that are connected to your computer. You can identify your Nokia phone by looking for a line in the output of lsusb that has something like the string Nokia Mobile in it.
The third command in the tutorial is:
wvdialconf create

If you have already installed wvdial then you can run the preceding command without installing anything else, but this command will not run properly in Ubuntu 13.10, so substitute the following command for it instead:
sudo wvdialconf /etc/wvdial.conf

This will create a file named wvdial.conf in your /etc directory.
The last command in the tutorial is:
sudo gedit /etc/wvdial.conf

This command will not run properly in Ubuntu 13.10, so you have to run the following two commands instead, which will allow you to use Gedit for editing the wvdial.conf file in Ubuntu 13.10:
sudo apt-get install gksu
gksudo gedit /etc/wvdial.conf

It is basically the same command as in the tutorial, only you have to substitute gksudo for sudo to open Gedit from the terminal, because Gedit is a graphical application.
In Ubuntu 18.04 and later gksu has been discontinued so use this command instead:
sudo -H gedit /etc/apt/sources.list &>/dev/null

Answer: I am listing out some apps to manage Mobile Phones in Ubuntu below. Hope these help you in connecting your phone to your PC.
Gammu/Wammu - Wammu is a program to manage data in your cell phone such as contacts, calendar or messages.

List of supported phones: http://wammu.eu/phones/
Homepage: http://wammu.eu/wammu/
Ubuntu App: https://apps.ubuntu.com/cat/applications/wammu/

gMobileMedia - gMobileMedia is a simple gtk application used to browse and handle a mobile phone filesystem, it can handle phones with more than one memory area.

Homepage: http://gmobilebrowser.sourceforge.net/
Ubuntu App: https://apps.ubuntu.com/cat/applications/gmobilemedia/

Series60-Remote - Series60-Remote is an application to manage your mobile phone. You can send and receive SMS messages directly on your computer. It also provides a complex contact and file management.

Homepage: http://sourceforge.net/projects/series60-remote/
Ubuntu App: https://apps.ubuntu.com/cat/applications/series60-remote/

Gnokii/Gnocky - Gnocky is a mobile phone manager that let's you edit your cellphone addressbook, send SMS and draw a new logo.

Supported hardware and configurations known to work - http://wiki.gnokii.org/index.php/Config
Homepage: http://wiki.gnokii.org/index.php/Gnocky
Ubuntu App: http://www.getdeb.net/software/Gnocky

AirDroid - Manage your Android from a web browser, all over the air.

Homepage: http://www.airdroid.com/
Review: http://www.dedoimedo.com/computers/android-airdroid-wireless.html

Error while installing Nokia Suite


Button at the slide image is not moving automatically.

Question: I have created images with automatic slides. As well as button/indicators at the below of the image. These automatic slides are working perfectly, but not the buttons. While slide1 moves to the next slide2 automatically, the button should show that it's on second image. The below code is under w3.css

<title>Hotel</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial scale=1">
<link rel="stylesheet" type="text/css" href="<?php echo base_url(); ?>css/w3.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

Slideshow

  <img class="mySlides" src="<?php echo base_url();?>/images/burger.jpg" style="width:100%">
  <img class="mySlides" src="<?php echo base_url();?>/images/piz.jpg" style="width:100%">
  <img class="mySlides" src="<?php echo base_url();?>/images/prawns.jpg" style="width:100%">

❮

❯

Answer:

<!DOCTYPE html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">


Invisible mounting hardware for a particular kind of wall unit

Question: I'm looking to build my own version of this wall unit: https://retrorenovation.com/2012/05/10/barzilay-multispan-vertical-storage-system-valuable-scandinavian-modern-wall-unit-design/
I think I know how I'm going to do the cabinets and the shelving, but the one thing that I can't figure out is how to mount the top of the large wood L-shaped beams flush to the wall with no hardware showing, and no pocket holes.
Well, that's not accurate. I'd like to use a mount kind of like how the rear view mirror of your car mounts to the windshield: that sort of U shaped one where the mirror slides down onto another U shaped piece, but I have no idea what that kind of mount is called. I feel like this would be the best solution to prevent lateral movement of the brackets.
So if you know what that kind of mount is called or if you know of a better way to mount this thing, let me know.
Comment: there could be a threaded stud screwed to the wall ... the mounting nut could be accessible from the top
Comment: In that particular structure, the tops of the L-beams do not need to be anchored to the wall at all. The geometry is such that the center of gravity of the cabinets is behind the bottom legs, and the whole structure is simply leaning against the wall. Just put some slip-resistant pads there.
Comment: @DaveTweed The cabinets are not hard-fastened to the beams, so if a young child (say my 3 year old daughter) were to somehow manage to kick the beam hard enough to cause it to dislodge from the cabinet, the whole thing would, indeed, come crashing down. Anchoring it to the wall wouldn't prevent this entirely (a hard and dedicated enough kick would probably still do the trick) but it would prevent it on accident.
Answer: I think what you may be referencing is called a French Cleat:
Comment: But note that the cleat allows horizontal movement, something that the OP seems to want to prevent. I've used this method to mount some fairly heavy wall cabinets, and the advantage is that you can be sure that the wall cleat is anchored directly to the wall studs without worrying about how they align with the cabinet itself. Note that the angle on the cleat in your diagram is rather extreme -- 10 to 20 degrees would be more typical.
Comment: Correct, @DaveTweed , I am definitely wary of lateral movement in this particular case. In my initial research, though, I did happen across French cleats, which is something I'll definitely remember for future projects.
Comment: You can -very- easily and simply tweak this fitting to your needs by adding stops on the cleats. For example, a dowel in one and a hole in the other
Comment: Yes, but the beam would not be flush with the wall anyway, so the point is moot.
Answer: Keyhole bracket
They come in different shapes and sizes, you should be able to find the shape and size you need
Comment: Is there a keyhole bracket that has a bespoke "male/female" setup? (rather than utilizing a screw or nail or some such standard fastener). I"m looking for a very tight fit
Comment: I'm not sure how that would help. You can recess a round keyhole fitting so that it is flush or slightly inside the piece that will attach to the wall, then use a standard fastener at the wall
Comment: A tight, secure fit is paramount here. It should allow no movement once secured. I don't believe using hardware that isn't designed to fit tightly together would be sufficient. These are primary support beams for shelving.
Comment: Fair enough but consider you criteria that has severally limited your options, you might have to give something somewhere. Note that the bevel of a flat head screw is a wedge that provides the secure fit into these fittings, it can be very finely tuned by screwing in or out to adjust the depth.
Comment: That is true, and certainly worth the consideration! Thanks for the idea!
Answer: The type of fasteners that you want are not common, so you're going to need to do a little digging, and focus on brackets used in furniture manufacture.  One idea I had are bed rail brackets.  Some might be too large, but this will give you a starting point for more research:

Bed rail bracket
There is another style here at Rockler.
Now, these are sold in wholesale quantities, so I don't expect this link to directly help you, but this is another style of bracket you can find with some more looking:

AliExpress bracket
Comment: Great ideas! The bed rail brackets is _very_ smart. Thanks for the direction


Flutter: FutureBuilder no list shown

Question: I have a list that comes in the form of future
  Future<List<String>> _future;
  List<String> showList = [];
  String showCode;

  Future<List<String>> getCode() async {
    final show = await SharedPreferences.getInstance();
    setState(() {
      showList = show.getStringList('companyName');
    });
    print('here ${showList.toString()}');
    return showList;
  }

and when I print, my console will output like this

[Friends,Scrubs]

I'm trying to show this list to user by using  Futurebuilder but my value is not show. I added it as a column in the container to be centered on the bottom.but only the CircularProgressIndicator() part is visible Any idea?
  ? Container(
                  child: Padding(
                    padding: const EdgeInsets.all(16.0),
                    child: Column(
                      children: [
                        Column(
                          children: [
                            IconButton(
                                icon: Icon(Icons.close),
                                onPressed: () {
                                  Navigator.pushNamed(
                                      context, ShowScreen.routeName);
                                }),
                            Text(
                              'Please Select Show',

                          ],
                        ),
                        FutureBuilder(
                        future: _future,
                        builder: (context,
                            AsyncSnapshot<List<String>> snapshot) {
                          if (snapshot.hasData) {
                            return ListView.builder(
                                itemCount: snapshot.data.length,
                                itemBuilder: (context, index) {
                                  return Card(
                                      elevation: 6.0,
                                      child: Padding(
                                        padding: const EdgeInsets.all(8.0),
                                        child: Row(
                                          crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                          children: <Widget>[
                                            Text(snapshot.data[index]),
                                          ],
                                        ),
                                      ));
                                });
                          }  else{
                            return CircularProgressIndicator();
                          }

                        }),
                      ],
                    ),
                  ),
                )

looks like this, but its not show items

I set my data like this
else{

        _showData = !_showData;
       shows.forEach((element) {
               showCode = element.showName;
               showList.add(element.showName);
                show.setStringList(
              'showName', showList);
                getCode();

                                            })

Comment: Is this `ListView` nested in a `Column` ?
Comment: I edit my post.
Answer: Set shrinkWrap property of the ListView to true:
I added a demo using your code as an example:
  return ListView.builder(
      itemCount: snapshot.data.length,
      shrinkWrap: true, // new line
      itemBuilder: (context, index) {
        return Card(
            elevation: 6.0,
            child: Padding(
              padding: const EdgeInsets.all(8.0),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(snapshot.data[index]),
                ],
              ),
            ));
      },
    );

Comment: I added but there was no change
Comment: Check the console for any warnings or errors. It worked when I tried the fix I posted.
Comment: Does the `progress indicator` show ? Does it stop ? What happens immediately after it stops ?
Comment: keeps spinning, does not stop. I added a visual above to understand better
Comment: Can i see the `future` you are passing to the `FutureBuilder` widget ?
Comment: Where are you calling the `getCode` method ? You should have something like `_future = getCode()` in your `initState`.
Comment: yes when I add it to initState the loading screen disappears and there is a blank space (again no error)
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/221151/discussion-between-void-and-kimsoo).

Flutter: FutureBuilder no list shown


Dask: Would storage network speed cause a worker to die

Question: I am running a process that writes large files across the storage network. I can run the process using a simple loop and I get no failures. I can run using distributed and jobqueue during off peak hours and no workers fail. However when I run the same command during peak hours, I get worker killing themselves.
I have ample memory for the task and plenty of workers, so I am not sitting in a queue.
The error logs usually has a bunch of over garbage collection limits followed by a Worker killed with Signal 9
Answer: Signal 9 suggests that the process has violated some system limit, not that Dask has decided for the worker to die. Since this only happens on high disk IO at busy times, indeed I agree that the network storage is the likely culprit, e.g., a lot of writes have been buffered, but are not being cleared through the relatively low bandwidth.
Dask also uses local storage for temporary files, and "local" might be the network storage. If you have real local disks on the nodes, you should use that, or if not, maybe turn off disk-spilling altogether. https://docs.dask.org/en/latest/setup/hpc.html#local-storage
Comment: Do I need to increase the memory if I turn of disk spilling m?
Comment: *maybe*, or maybe a given worker will stop accepting new tasks until memory has been freed.
Comment: That seemed to be the magic. distributed:
  worker:
    memory:
      target: false  # don't spill to disk
      spill: false  # don't spill to disk
Comment: Is there a way to find out the parameters off the job that failed ?
Comment: I assume the task is lost when workers die
Comment: They should come back as cancelled tasks, I think - the scheduler will refuse to retry tasks that have been associated with a worker crash more than a certain number of times.
Comment: i see how to cancel a job but not how to retrieve a cancelled job.
Comment: I referred to "tasks", not sure what you mean by "job". The scheduler is doing the cancelling, not you. Doing `.compute()` or other execute action on a collection, or getting the results of a Future will give you the latest error, including anything cancelled.


Converting a local image to base64 using JavaScript

Question: Iam doing a project in html, javascript only.
I have a function that convert image to base64, see the code below.
function getBase64Image()
{
    p = document.getElementById("picField").value;
    img.setAttribute('src', p);
    var canvas = document.createElement("canvas");
    canvas.width = img.width;
    canvas.height = img.height;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(img, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    var r = dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
    base64 = r;
    alert(base64);
}

but the problem is when I deployed my website,
means when I placed my html file on iis, its not working, means in local file system it is showing complete base 64 format like iVb....,
 but on iis it giving base64 code as just "base,".
so why it is not working on iis i dont know, so please help me and send me html file that will work on iis too.
Comment: This is client side code and shouldn't have anything to do with IIS. You probably have a Same Origin Policy problem. What kind of a field is `document.getElementById("picField")` and what does the URL look like that is in it?
Comment: ofcourse, same html file showing base64 string clearly , but when placed on iis , its not showing, why?
Comment:
Comment: That will not work I'm afraid. I'm surprised it works locally. What browser are you using?
Comment: possible duplicate of [base64 javascript not running on iis, in some browsers too, why?](http://stackoverflow.com/questions/9544814/base64-javascript-not-running-on-iis-in-some-browsers-too-why)
Answer: I'm fairly sure you have a Same Origin Policy problem.
When you run your page on IIS, it runs in a different context than locally: Instead of a file:// URL, it runs on a http:// one.
What you are trying to do is fetch a local image file and load it into a canvas on a remote site. That is not possible using traditional JavaScript for security reasons.  (I'm not sure how this works even locally - in my understanding, it shouldn't. But anyway.)
You will need to use the HTML 5 file API which allows JavaScript direct access to local files. I'll look whether I can dig up some related SO questions.
Update: this should help:

How can I draw an image from the HTML5 File API on Canvas?
Comment: HOW CAN WE RESOLVE OUR ISSUE? PLEASE HELP ME
Comment: @Raja see the link in the answer. You'll need to use a slightly different concept here.
Comment: iam sorry, i unable to do, and its for mozilla, not working on IE
Comment: @Raja yeah, it won't work in IE yet. Maybe in IE10... You'd have to serve one version in IE, and the other in Firefox/Chrome. I don't have any hands-on experience with this so I can't help any further, I don't have the time to try this out myself right now


MySQL Select box Duplicate - Duplicating one field option but not the other (Queries Identical)

Question: I am currently creating a database for an upload system - I am using a select box to limit the number of categories added to the database.
<select name="category">
<?php
$conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");

mysqli_select_db($conn, "UPLOAD") or die("db will not open");

$query = "SELECT category FROM details GROUP BY category";

$result = mysqli_query($conn, $query) or die("Invalid query");

while($row = mysqli_fetch_array($result)) {
                echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
                }
             mysqli_close($conn);
            ?>
     </select>

    <select name="reaction">
            <?php
            $conn = mysqli_connect("localhost", "blah", "blah") or die ("No connection");

            mysqli_select_db($conn, "UPLOAD") or die("db will not open");

            $query = "SELECT reaction FROM details GROUP BY reaction";

            $result = mysqli_query($conn, $query) or die("Invalid query");

            while($row = mysqli_fetch_array($result)) {
                echo "<option value=\"" . $row[0] . "\">" . $row[0] . "</option>";
                }
             mysqli_close($conn);
            ?>

While the two queries are the same - Only the Category (The top query) is stopping form repeating multiple data from my db. When I look into my database - This is what I am finding (Which I have a hunch may be the problem).
INSERT INTO `details` (`name`, `category`, `reaction`, `photo`, `date_added`) VALUES
('Mase Laughing', 'Funny', 'Laugh\n', 'mase-laugh.gif', '2013-05-01 07:16:26'),
('Movie Wink', 'Cheeky', 'Wink\n', 'movie-wink.gif', '2013-05-02 12:33:12'),
('Tarzan Giggle', 'Funny', 'Wink\r\n', 'tarzan-laugh.gif', '2013-05-02 01:33:00');

Beside the reactions I am getting these strange \r\n letters -
Anyone have any Ideas?
Thanks in advance.
Comment: Why you're establishing and disconnecting DB connection multiple times?
Comment: I am Kind of new to all this
Comment: You want to add multiple reaction but it fails? Like the selext box has 'funny', 'shocked', 'boo' reactions. And I can select boo and funny and those two reaction will be stored on the database?
Comment: It all works fine - Its only that the select boxes get populated with multiple results of say Wink or Laugh. Kind of like Laugh-Wink-Wink instead of just Laugh and Wink.
Comment: When I REMOVED both `Wink` values (completely) from `reaction` field and then executed query it shows me two values (laugh,Wink) in Select box. Problem might be because of `Wink\n` and `Wink\r\n`
Answer: These are "Carriage Return" (\r) and "Newline" (\n) characters. These are commands telling your computer to go the end of the line and to a new line.
To stop your page from showing duplicate categories, change this:
$query = "SELECT category FROM details GROUP BY category";

into this:
$query = "SELECT distinct category FROM details GROUP BY category";

It will not prevent your database from storing duplicate categories (which you do no want, otherwise you would only be able to save 1 (one) line of details per categorie, but it will prevent your dropdown (select) from showing the duplicates. So, with the details you showed, it will give you a dropdown with the values 'Funny' and 'Cheecky', both of them showing only once.
Add "distinct" to your other SQL statement too to have the reactions de-duplicated too:
$query = "SELECT DISTINCT reaction FROM details GROUP BY reaction";

Comment: Ah - nothing to be alarmed about then?
Comment: Not at all my friend :-) It just means they pressed "enter". And depending on their system (windows/linux/mac/...), that enter is translated in \n or \r\n.
Comment: Ah- Thanks That makes sence
Comment: It's not fixed yet tho - My select box for reaction is still duplicating options :(
Comment: Thats the code I input buddy it could be something to do with how its being uploaded
Comment: Because wink\n and Wink\n\r are two different values to your database. Remove these, and it should work.
Answer: Here I am updating original question by reducing redundant code
<?php
    $conn = mysqli_connect("localhost", "root", "") or die ("No connection");
    mysqli_select_db($conn, "test") or die("db will not open");
?>
<select name="category">
<?php

    $query = "SELECT category FROM details GROUP BY category";
    $result = mysqli_query($conn, $query) or die("Invalid query");
    while($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
    }
?>
</select>

<select name="reaction">
<?php
    $query = "SELECT reaction FROM details GROUP BY reaction";
    $result = mysqli_query($conn, $query) or die("Invalid query");

    while($row = mysqli_fetch_array($result)) {
        echo "<option value='" . $row[0] . "'>" . $row[0] . "</option>";
    }
    mysqli_close($conn);
?>
</select>

Comment: Even you could do one thing that whenever you allow entry in text fields replace combination of `\r\n` to `\n` so that no mismatched will be occured.


MIPS move command

Question: I am new to MIPS so wanted to know if the move command removes the value from the original register in which it was stored?
For eg. move $t1, $v0
Value in $vo will be copied or entirely moved to $t1?
Comment: A MIPS instruction-set reference specifies every effect each instruction has on the architectural state.  That doesn't include modifying the source register, for fairly obvious reasons.  (It would be extra work, an extra register write, and normally undesirable for programmers / compilers.)
Answer: The mips move instructions are more accurately copy instructions. The source register is untouched by move
Note that move is a pseudo-instruction, provided by the assembler. It's not present in the hardware.
See https://www.dsi.unive.it/~gasparetto/materials/MIPS_Instruction_Set.pdf

MIPS move command


Can you help me identify these glowing gold and black patterned wheels in Rocket League?

Question: Can someone help me identify the following wheel?

I've gone over the list of all the wheels listed at Rocket League Insider repeatedly, but they don't seem to be listed there. They could be from DLC, but the DLC don't enumerate their contents specifically. They could also be some kind of reward, but it wasn't one I was able to find.
Answer: This wheel was awarded at the end of Season 9 to those who earned the competitive Gold tier rewards.

I don't know their specific name, but that's not going to help you if you were trying to obtain a set. As prizes to competitive events, these can't be traded.
In addition to the sources listed in the question, these are other locations to search to identify Rocket League items:

Season 9 rewards
Season 8 rewards
Season 7 rewards
Season 6 rewards
Season 5 rewards
Season 4 rewards
Season 3 rewards
Season 2 rewards
Season 1 rewards
Comment: Commentators / editors: If you disagree with the content of the answer then please downvote it, but please refrain from editing it any further. Thank you.


Fetching inner style attribute using jQuery

Question: I have this part of html, I need to fetch only the inner style tag attribute. but the structure can change for next part of html.

Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object's state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.

I tried using element.attr("style"), but i get the outer  tags style attribute.
can i use child to find this? any suggestions?
Comment: It should be `element.attr("style")` without the final 's'
Comment: Which inner style are you referring to. Your question is quite ambiguous.
Comment: You forgot to post the approaches that failed.
Comment: @BlackMamba the one with span.
Comment: @Martial made the correction. The thing is i need to find the style that gets finally applied to the text.
Answer: you can use getComputedStyle but it is javascript not jquery methood.
var data = getComputedStyle($('span')[0]).background;
  console.log(data);

Answer: You can get css off inner element check here
HTML:

    Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object's state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.

Jquery Code:
var element= $('p').children().attr('style');
alert(element);

Answer: I'm giving a number of options you can use according to your situation as follow:
If you want style tag of first span child only
    console.log($('p').children('span').eq(0).attr('style'));

If you want inner style of each child
$('p').children().each(function() {
  console.log($(this).attr('style'));
 })

If you want inner style of span child
 $('p').children('span').each(function() {
    console.log($(this).attr('style'));
 })

Here's a runnable with working example of each case:

$(document).ready(() => {
 $('p').children().each(function() {
  // if you want inner style of each child
  console.log($(this).attr('style'));
 })
  $('p').children('span').each(function() {
   // if you want inner style of span child
   console.log($(this).attr('style'));
  })
  // if you want style tag of first span child only
    console.log($('p').children('span').eq(0).attr('style'));
})

Serialization is required for a variety of reasons. It is required to send across the state of an object over a network by means of a socket. One can also store an object's state in a file. Additionally, manipulation of the state of an object as streams of bytes is required. The core of Java Serialization is the Serializable interface. When Serializable interface is implemented by your class it provides an indication to the compiler that java Serialization mechanism needs to be used to serialize the object.

Comment: I've explained different situations which might be one of your required case


Future-like MMO, engine choice?

Question: We are a small group of developers and we want to create a Future-like MMO which will combine  City building, RTS, Economic and Political type of games.
We are unsure if we should develop a DirectX9 engine from scratch or use tools like XNA, DXstudio.(we have experience creating a simple FPS-like engine using DirectX)
Another question is if engines like UnrealEngine/ UDK, Unity are really an option for a complex game like ours(most games developed with these engines are FP/3rdP Shooters)?
Any idea for where to start with the engine will be helpful.
Comment: I guess most of the modern big engines can be used for much more than FPS (or variants). I know of one isometric RPG that will be developed using Unity for example. One bit "pro" point for some engines is that they are cross-platform, so using e.g. Unity you get OSX and Linux basically for free.
Comment: What does "future-like" mean in this context? A sci-fi setting? Or that it will be years ahead of the competition? Or something else?
Comment: But for the record, MMOs have been made in Unity (Battlestar Galactica Online comes to mind), and the Unreal engine was used for Mass Effect, so I'd say both are usable for "complex games".
Comment: I meant sci-fi setting. We also believe that the game will be little similar to other games and will not be somehow included in a typical genre.
Answer: You allways endup with engine that prefectly fits your needs if you build it your self. but this takes time and is costy.
On the other hand picking a engine like UDK/CryEngine, you will save some time but probably need to give time to be able to do exactly what you want.
If i would suggest a start is to nail down every technical aspect of the game.
For example, things like this :
Graphics, Content handling/pipeline, SocialSupport(Facebook, Twitter), Target platform, How to solve most of your programming problems (How to use the economy system, building systems etc)
And when all that is done, just try this out in a easy alpha in all the engines you would like to test. (including writing a own, but with limited stuff to just make it prototype)
from there, pick what feelt best and hope that it will work out, :)
hope that helps some!

Future-like MMO, engine choice?


How to change the toolbar text size?

Question: I want to change the size of text in Toolbar. Because in my application, Toolbar text has different sizes both for landscape and portrait mode.
Is it possible to change the text size of text in Toolbar?
Answer: Use app:titleTextAppearance:
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="?actionBarSize"
    android:id="@+id/toolbar"
    app:titleTextAppearance="@style/Toolbar.TitleText" />

and override the default title size in a custom style:

Result:
Comment: It works, thank you for the solution! Saved much of my time!
Answer: for example this your toolbar
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:gravity="center"
    android:minHeight="?attr/actionBarSize"
    app:theme="@style/ThemeOverlay.AppCompat.ActionBar" />

you can simple add this view this
    app:titleTextAppearance="@style/yourstyle"

style.xml

like that...
Comment: for some reason `android:gravity="center"` doesn't set the centered alignment for me....:-/
Answer: You can add a TextView to your toolbar and customize as you want:
<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_height="wrap_content"
    android:layout_width="match_parent">
    <TextView
        android:id="@+id/toolbar_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/app_name"
        android:textSize="25sp"/>
</android.support.v7.widget.Toolbar>

Comment: This seems to be an answer that suits apps that support API < 21. the titleTextAppearance is a nice solution but only works API 21 and above.

However, there are a few intricacies that we need to deal with going with this solution. If you are using  SearchView, then the expanded version of the view will not stretch till the left end. Instead it will only stretch till the right edge of the newly added title text view. So you will have to do some customization there but again this is a specific case. In a general sense this is a good solution for any platform version.
Answer: [Optional steps 1 & 2)

Place your font file in "Project/app/src/main/assets/fonts/" folder.

Then create a Typeface object from the font file as:
Typeface typeFace = Typeface.createFromAsset(getAssets(), "fonts/font_name.ttf");

Now, get the child item (toolbar title textview) from the existing toolbar, the default toolbar and pass the typeface object we created above.

((TextView) toolbar.getChildAt(0)).setTypeface(typeFace); // set custom typeface - font

Finally, change the text size of toolbar's title text view

((TextView) toolbar.getChildAt(0)).setTextSize(30); // set title font size

Comment: Welcome to SO! Please add some description to support your answer.
Comment: this answer came in Low Quality posts in SO.... Could you add any commentary to your answer? Explain your logic, and give a little commentary on what your code is intended to do. This will help the OP, but it will also serve as commentary for future users
Comment: If you have navigation icon, you should use getChildAt(1) :)
Answer: Try this in onCreate:
android.support.v7.app.ActionBar actionbar = getSupportActionBar();
TextView textview = new TextView(MainActivity.this);
RelativeLayout.LayoutParams layoutparams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);

textview.setLayoutParams(layoutparams);
textview.setText(getString(R.string.your_string));
textview.setTextColor(Color.WHITE);
textview.setTextSize(18);

actionbar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
actionbar.setCustomView(textview);

This is taken from Android-Examples.com.

How to change the toolbar text size?


vs15 profiling shows only app name

Question: I'm new in visual studio, and use before only codeblocks with gcc-mingw.
The problem is: when i try to profile my application, i want to see list of functions but i get application name instead :
screenshot
how fix it ?

linker command line :
/OUT:"{projects}\bin_vs14\Debug\NovaEngine.exe" /MANIFEST /PROFILE /NXCOMPAT /PDB:"{projects}\bin_vs14\Debug\NovaEngine.pdb" /DYNAMICBASE {manylibs} /MACHINE:X86 /INCREMENTAL:NO /PGD:"{projects}\bin_vs14\Debug\NovaEngine.pgd" /SUBSYSTEM:CONSOLE /MANIFESTUAC:"level='asInvoker' uiAccess='false'" /ManifestFile:"{projects}\bin_vs14\obj\Debug\NovaEngine.exe.intermediate.manifest" /ERRORREPORT:PROMPT /NOLOGO /TLBID:1
Answer: Module names are shown instead of function names if symbols cannot be resolved e.g. due to missing or out-of-date pdbs. Please ensure that you have up-to-date pdbs e.g. by running your app under debugger.
Also from your screenshot I suppose you have VS 2015 RTM, but not Update 1. Please try to upgrade to VS 2015 Update 1. It has a number of fixes in profiler related to symbol resolution.
Comment: Hm, yes Update 1 fix this and now prof works fine, thank you.

vs15 profiling shows only app name


Consolidate Jenkins Email Notifications

Question: I have a Jenkins project consisting of 3 simple free-style jobs, each with their own build slave.  Each job is tied to a separate platform: linux, mac, or windows.  When a developer commits their code, Jenkins soon after polls the repo, builds the project on each of the build slaves, and each of those projects sends an email to the developer describing whether or not the build failed or succeeded.  Problem: Three separate emails per scm change really spams developers' inboxes, especially those belonging to people who like to commit small changes frequently.  They are therefore likely to ignore the emails entirely.
Question: Is there a way (via plug-in or project restructuring) to consolidate the three success/failure emails into one email?  I have looked into the Email-ext plugin, the MultiJob plugin and the Build a multi-configuration project  option and can't seem to find a way to change the project structure so that only one email is sent to a developer describing which jobs failed or succeeded.  I suspect you have to combine the jobs into a single MultiJob project and check results from building on each platform before sending, but I don't know.  There's a lot about Jenkins I haven't figured out yet.
Any advice you guys can give me would be greatly appreciated.
Answer: The "Editable Email Notification" publisher (from email-ext) has a setting to decide how it deals with matrix (multi-configration) projects.
You can configure the "Trigger for matrix projects" to "Trigger only the parent job", which should achieve what you want.
Likewise you can also configure it to "Trigger for each configuration" to get the result you have now, or "Trigger for parent and each configuration" for both.
Comment: Thank you for your response!  I'll give it a shot and get back to you.
Comment: Can you please share the entire configuration of multiconfiguration job as well as normal jobs, screenshots would be helpful, because we are not able to achieve this. Thanks!
Answer: if you have 'n' freestyle jobs and you have to get one single email notification then go for Multijob plugin of jenkins.This is one of the approach.
Here you can run your jobs sequential or parallel. To consolidate the result to one email you need additional plugins like Copy Artifact , Groovy .
Below I am giving an example where I need to get the result of 2 freestyle jobs 'Job A' and 'Job B' in 1 single email
(Pre requisite :- Multijob, Artifact , Groovy plugins are installed in jenkins
 The node in which you run the Jobs should have atleast 2 executors )
Steps to follow.

Create a multijob project (named it as 'Master')
In Add Build Step ----> MultiJob Phase
a. 'In phase 1' I added 'Job A' and in 'phase 2' added 'Job B' (Since I wanted my jobs to run sequential)
b. If you want to execute your jobs parallel add 'Job A' and 'Job B' in 'phase 1'
'Job A' and 'Job B' should check Permission to Copy Artifact and add Projects to allow copy artifacts as 'Master' (This would give the permission for the 'Master' to iterate through the subjob results)
Now for the 'Master' you need to add Groovy Script in Groovy post build (Add post-build action ---> Groovy Postbuild)

Below given is the groovy script I used to iterate through my subjobs result and then get the pass pertcentage to decide whether I need to set the status of the master as success or failed.Here  my jobs results are nunit result.
<code>        import hudson.model.*
        import com.tikal.jenkins.plugins.multijob.*

        void log(msg) {
        manager.listener.logger.println(msg)
        }

        def boolean findpercent(int pass,int total)
        {
        log 'Entered the function find percent'
        def float percent = 0.0
        log percent
        percent = (pass/total) * 100
        log percent
        if(percent >= 90.0)
        {
            return true
        }else
        {
            return false
        }
        }

        threshold = Result.SUCCESS

        void aggregate_results() {
        def failed = false
        def  int totalTestCases = 0
        def  int  failedTestCases = 0
        def  int  passedTestcases = 0
        def  int skipTestcases = 0
        mainJob = manager.build.getProject().getName()
        job = hudson.model.Hudson.instance.getItem(mainJob)

        log '-------------------------------------------------------------------------------------'
        log 'Aggregated status report'
        log '-------------------------------------------------------------------------------------'

        log mainJob
        log job
        log manager.build.getNumber()
        log manager.build.getResult()

        job.getLastBuild().getSubBuilds().each { subBuild->
        subJob = subBuild.getJobName()
        subJobNumber = subBuild.getBuildNumber()
        job1 = hudson.model.Hudson.instance.getItem(subBuild.getJobName())
        build = job1.getBuildByNumber(subJobNumber)
        log build
        log job1.getLastCompletedBuild().getResult()
        log job1.getLastCompletedBuild().getTestResultAction()
        log build.getResult()
        log subJobNumber
        log subJob
        log job1
        log subBuild
        log build.getAllActions()
        log '-------------------------------------------------------------------------------------'
        log 'build.getTestResultAction()'
        log '-------------------------------------------------------------------------------------'
        log build.getTestResultAction()
        testResult = build.getTestResultAction()
        log testResult
        if (testResult != null) {
                total = testResult.getTotalCount()
                log total
                log totalTestCases
                totalTestCases += total
        log  totalTestCases
                             failures = testResult.getFailCount()
        log  failures
        log failedTestCases
                failedTestCases  +=    failures
        log failedTestCases
                            skip = testResult.getSkipCount()
        log skip
        log skipTestcases
                skipTestcases +=  skip
                pass = total - (failures  + skip )
                log pass
        passedTestcases += pass
        log pass
        log passedTestcases
                }
        }
        log 'Total testcases run'
        log totalTestCases
        log 'Total failedTestCases'
        log failedTestCases
        log 'Total skipTestcases'
        log skipTestcases
        log 'Total passedTestcases'
        log passedTestcases
        log 'End Result'
        if(findpercent(passedTestcases,totalTestCases)) {
                   log 'success'
            manager.build.setResult(hudson.model.Result.SUCCESS)
        }else
           {
                    log 'failure'
            manager.build.setResult(hudson.model.Result.FAILURE)
        }

         log 'time taken'
         log manager.build.getTimestampString()
         log 'Time End'

        }

        try
        {
        aggregate_results()
        }
        catch(Exception e) {
        log('ERROR: ${e.message}')
        log('ERROR: Failed Status report aggregation')

        }
</code>

Now in editable email notification I used the BUILD_LOG_EXCERPT to get the desired values. For example
${BUILD_LOG_EXCERPT, start = "Total passedTestcases", end="End Result"}
This will return the value of the variable passedTestcases since it is present in between the log Total passedTestcases and End Result
Note :- The slave node on which you run the jobs should have atleast 2 executors . Because here master will be running until all your subjobs run. So If its run sequentially you will need two executors. IF you need to run parallel you need n executors (n-1 subjobs and 1 master job).

Consolidate Jenkins Email Notifications


Using D3.js in my python program

Question: for a math project I am looking into the collatz conjecture, In my report I would like to alter the algorithm a little and have the tree as an image.
I have the code for the graph here
http://bl.ocks.org/mbostock/4063550#flare.json
and the code for the algorithm is here (last line should have parenthesis)
https://en.wikipedia.org/wiki/File:Collatz-graph-20-iterations.svg
I am truly stuck, because I have no idea how to put the output onto the tree.
Any help would be appreciated.
Answer: If you need to use D3js (or any other JavaScript library), at the minimum, you will have to create a simple HTML file which includes D3.js and any additional JS code for plotting your output.
You can use this as a starting point. If you're very new to JavaScript and need more information on how to proceed, let me know and I'll try to provide a more detailed explanation.
Comment: I have no experience with HTML or D3.js. I'm just looking for a way to stick my algorithm into a graph/tree.

Using D3.js in my python program