text:
Q: Setting an array's size to the value of a const derived from the division of another constant I have these two supposed constants:
int const MATRIX_SIZE = 1000;

int const LONGEST_LR_LINK = (int)floor(MATRIX_SIZE/2);

I am attempting to declare an array:
int lrLinkArray [LONGEST_LR_LINK];

I get the error:

error: array bound is not an integer constant before ']' token

It would not be that much trouble to manually plug in whatever half MATRIX_SIZE is for LONGEST_LR_LINK, but I am curious as to what a solution to this would be.  Is it bad practice to do any kind of calculation for a const?

A: Integer division in C++ automatically rounds down. So if you have the definition
int const LONGEST_LR_LINK = MATRIX_SIZE/2;

then LONGEST_LR_LINK will indeed be a constant expression, and
int lrLinkArray [LONGEST_LR_LINK];

should be fine. Besides, floor(MATRIX_SIZE/2) doesn't do what you think it does, anyway; you'd have to write floor(MATRIX_SIZE/2.0) in order to force non-integer division.

A: int const LONGEST_LR_LINK = MATRIX_SIZE/2;

Integer division already rounds down.

A: Integer division should do what you want, we can see this from the draft C++ standard, in section 5.6 Multiplicative operators it says:

[...]For integral operands the / operator yields the algebraic quotient
  with any fractional part discarded;81[...]

To understand why it does not you have to realized that even though you initialize MATRIX_SIZE with a literal which makes it a constant expression std::floor is not a constexpr function and therefore LONGEST_LR_LINK is also not a constant expression and can not be used for array bounds which require an integral constant expression.
Also, as far I understand old style C casts are also not allowed in constant expressions either.


text:
Q: Two things; console app run without .exe and args (C# console app) Hi I would like to make my self able to maybe define my app into CMD by that I can type program instead of program.exe kind of like how ping works for example.
I also need help with arguments.
The point of my app is to send a get request to a local server evaling PHP fetching a result from it so I can easy quick debug things and calculate things ect from CMD.
So for example I have to do.
W:\Users\example>e.exe
echo "example";
.....

example

W:\Users\example>

Tow things with the above are very annoying. I need to enter e.exe and THAN I need to enter the code to eval :-/
How could I make it so I could just do
W:\Users\example>e echo "example";
.....

example

W:\Users\example

I really would like to get this working to make use faster + more simple ! this is a programmers way to calculating math :P
EDIT:
Below is the code;
static void Main(string[] args)
{
    WebClient client = new WebClient();
    Console.WriteLine("...");
    string input = Console.ReadLine();
    string php = client.DownloadString("http://192.168.1.50/test.php?exec="+input);
    Console.WriteLine(".....");
    Console.WriteLine("");
    Console.WriteLine(php);
    Console.WriteLine("");
}

I've tried to do "+arg[0] but does nothing at start :?

A: Don't type ".exe" as you don't need to type it... You may want to put your e.exe some place listed in PATH environment variable (or add path to the executable to the PATH).
Main(string[] args) are arguments passed to your program - use them whatever way you want. Note that they will be split on spaces, so you may need to String.Join them back if you need all arguments as one.
You can also use Environment.CommandLine if you need access to comple not parsed command line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can i send my inputvalue of  to a async function through a onSubmitEditing? I want to save the value of the input of a field in react native. How can I send the value to an async function by using the onSubmitediting event?
I tried this:
<TextInput onSubmitEditing={ (text) => this.Store(text)}></TextInput>

and this is the function I'm using
Store = async() =>
{
    var textvalue = "here the value of the <TextInput>";
    try
    {
        await AsyncStorage.setItem('@Temp:city', textvalue );
    }
    catch (error)
    {
        console.log(error)
    }
}

A: Please try this:
   <TextInput
     onSubmitEditing={ event => {
      const text = event.nativeEvent.text;
      this.Store(text);
    }} >
   </TextInput>

And save like this:
Store = async(text) => {
     try
     {
     await AsyncStorage.setItem('@Temp:city', text );

     }
     catch (error)
     {
      console.log(error)
     }
 }


text:
Q: Embedding a large .flv into Adobe Flash results in noise-y results I'm trying to import a rather large .flv into my otherwise empty Flash file in Adobe Animate CC.
The .flv in question

Importing it (1)

Importing it (2)

After clicking Next and Finish, the video imports in about a second, very quickly for a huge video. The video appears on the stage much smaller than its actual size (160x120 pixels). The video itself looks nothing like what it's supposed to - in fact it looks like noise from a TV with bad reception.
My library window after importing


text:
Q: Memento pattern issues in c# I'm struggling to figure out an issue with the Memento pattern. Although I understand it and I'm able to implement it, I must be missing something because it seems to me that if fails when applied to an object that has List type properties.
Consider the following classes:
public class LEDTV
{
    public string Size { get; set; }
    public List<Input> Inputs { get; set; }
    public Manufacturer Manufacturer { get; set; }

    public LEDTV(string size, List<Input> inputs, Manufacturer manufacturer)
    {
        Size = size;
        Inputs = inputs;
        Manufacturer = manufacturer;
    }

    public void AddInput(Input input)
    {
        Inputs.Add(input);
    }

    public string GetDetails()
    {
        string inputs = string.Join(";", Inputs);

        return "LEDTV [Size=" + Size + ", Inputs=[" + inputs + "], Manufacturer=" + Manufacturer + "]";
    }

    public Memento SaveState()
    {
        return new Memento(this);
    }

    public void RestoreState(Memento memento)
    {
        Size = memento.Size;
        Inputs = memento.Inputs;
        Manufacturer = memento.Manufacturer;
    }
}

public class Memento
{
    public string Size { get; set; }
    public List<Input> Inputs { get; set; }
    public Manufacturer Manufacturer { get; set; }

    public Memento(LEDTV ledTV)
    {
        Size = ledTV.Size;
        Inputs = ledTV.Inputs;
        Manufacturer = ledTV.Manufacturer;
    }

    public string GetDetails()
    {
        return "Memento [Size=" + Size + ", Inputs=[" + Inputs + "], Manufacturer=" + Manufacturer + "]";
    }
}

Now consider the following piece of code:
LEDTV ledTV;
Stack<Memento> mementos = new Stack<Memento>();

// Led TV #1
ledTV = new LEDTV("42 inch", new List<Input>() { new Input("VGA", "") }, new Manufacturer("Samsung"));
mementos.Push(new Memento(ledTV));
Console.WriteLine("\nCurrent LedTV : " + ledTV.GetDetails());

// Make changes to Led TV #1
ledTV.Size = "36 inch";
ledTV.Manufacturer = new Manufacturer("Sony");
ledTV.AddInput(new Input("Digital Audio", ""));

// Led TV #2
ledTV = new LEDTV("46 inch", new List<Input>() { new Input("SCART", "") }, new Manufacturer("LG"));
mementos.Push(new Memento(ledTV));
Console.WriteLine("\nCurrent LedTV : " + ledTV.GetDetails());

// Ledt TV #3
ledTV = new LEDTV("50 inch", new List<Input>() { new Input("HDMI", "") }, new Manufacturer("Toshiba"));
Console.WriteLine("\nCurrent LedTV : " + ledTV.GetDetails());

while (mementos.Any())
{
    Console.WriteLine("\nRestoring to previous LED TV");

    ledTV.RestoreState(mementos.Pop());

    Console.WriteLine("\nCurrent LedTV : " + ledTV.GetDetails());
}

So, in a nutshell, I have a LEDTV type that has a ValueType for the Size, a List of available Inputs and a non ValueType for the Manufacturer. The Memento object accepts a LEDTV to save its state. The code snippet sets a LEDTV, saves its state, then does some changes to it, sets it again and saves its state, sets it and again, and finally rollback all saved states, producing the following output:
Current LedTV : LEDTV [Size=42 inch, Inputs=[VGA], Manufacturer=Samsung]

Current LedTV : LEDTV [Size=46 inch, Inputs=[SCART], Manufacturer=LG]

Current LedTV : LEDTV [Size=50 inch, Inputs=[HDMI], Manufacturer=Toshiba]

Restoring to previous LED TV

Current LedTV : LEDTV [Size=46 inch, Inputs=[SCART], Manufacturer=LG]

Restoring to previous LED TV

Current LedTV : LEDTV [Size=42 inch, Inputs=[VGA;Digital Audio], Manufacturer=Samsung]

Everything works as expected, except for the List property, and I can obviously understand why: the list is not a ValueType, so it's passed along by reference. Any change made to it is reflected both in the LEDTV and Memento, because it's the same list in both objects. Surely I can copy the list content into another list, thus creating a new list object but keeping all the references of the object composing the list, but that seems so hacky. Besides, it doesn't seem doable to me to basically have a duplicate class of all the classes that I want to track states, because that's basically what a Memento is. A desirable solution would be a generic Memento implementation that lists the properties of a type and saves each one, but then I would have to overcome the List issue generically, which doesn't seem possible at first glance.
Any help would be appreciated, either in the form of a concrete solution or just pointing out the way, or simply telling me I misunderstood the entire concept.

A: One of the advantages of the Memento pattern is that the originator object encapsulation is preserved.  But your object is not well encapsulated to begin with since it's exposing it's own internal state in the form of the List of inputs.
I think the real value of this pattern shines in situations where the objects state can be represented by a subset of the exposed data or where the creating the object is expensive.
For example if  your LEDTV where sourced out of a database the Memento might only consist of a record ID which could be used to restore the data from the database.  And on the other end of the spectrum the LEDT might require some set of expensive queries to a database to create and you can then avoid re-creating it by storing the data in the Memento.
Memento certainly can be done generically but I'm not sure that's always ideal.  In the few instances I've seen it used it was tailored to a specific class because there was a single higher level class that needed to be manipulated rather than the small classes aggregated into that higher level class.
So used appropriately it's a cool pattern, and you may have found a use for it.  But I would make sure you're design as a whole is SOLID and then think about where to use the pattern in your design.
For something simple just implementing clonable objects might suffice...


text:
Q: Identify element requesting sound chip to sleep Since a few months the sound is suddenly stopping on my laptop after some time. My computer is a Toshiba Satellite L755 with a Conexant CX20585 sound chip, running Ubuntu 17.04.
I found out that this is caused by the sound chip being put to sleep, as explained here.
When the sound is working, reading /proc/asound/card0/codec\#0 shows:
Codec: Conexant CX20585
Address: 0
AFG Function Id: 0x1 (unsol 1)
Vendor Id: 0x14f15069
Subsystem Id: 0x1179fc50
Revision Id: 0x100302
[...]
Node 0x1f [Pin Complex] wcaps 0x400501: Stereo
  Pincap 0x00000010: OUT
  Pin Default 0x92170110: [Fixed] Speaker at Int Front
    Conn = Analog, Color = Unknown
    DefAssociation = 0x1, Sequence = 0x0
    Misc = NO_PRESENCE
  Pin-ctls: 0x40: OUT
  Power states:  D0 D1 D2 D3 D3cold EPSS
  Power: setting=D0, actual=D0

And when the sound is not working, it shows:
Node 0x1f [Pin Complex] wcaps 0x400501: Stereo
  Pincap 0x00000010: OUT
  Pin Default 0x92170110: [Fixed] Speaker at Int Front
    Conn = Analog, Color = Unknown
    DefAssociation = 0x1, Sequence = 0x0
    Misc = NO_PRESENCE
  Pin-ctls: 0x40: OUT
  Power states:  D0 D1 D2 D3 D3cold EPSS
  Power: setting=D3, actual=D3

The node 0x1f being set in the power state D3 is therefore the issue. As I found out in the previous link, I can put it back to the power state D0 with the command sudo hda-verb /dev/snd/hwC0D0 0x1f SET_POWER_STATE 0. The sound is then back, but only for a few minutes.
Tracking the hda events with echo 1 > /sys/kernel/debug/tracing/events/hda/enable shows that no hda event is sent by the sound driver when the sound cuts:
cat /sys/kernel/debug/tracing/trace
# tracer: nop
#
# entries-in-buffer/entries-written: 20/20   #P:4
#
#                              _-----=> irqs-off
#                             / _----=> need-resched
#                            | / _---=> hardirq/softirq
#                            || / _--=> preempt-depth
#                            ||| /     delay
#           TASK-PID   CPU#  ||||    TIMESTAMP  FUNCTION
#              | |       |   ||||       |         |
 alsa-sink-CX205-2584  [001] d...   240.469929: snd_hdac_stream_stop: stream_tag: 5
        hda-verb-3617  [003] ....   257.329599: hda_send_cmd: [0000:00:1b.0:0] val=0x01f70500
        hda-verb-3617  [003] ....   257.329672: hda_get_response: [0000:00:1b.0:0] val=0x00000000
 alsa-sink-CX205-2584  [001] ....   279.844834: hda_send_cmd: [0000:00:1b.0:0] val=0x010a0000
 alsa-sink-CX205-2584  [001] ....   279.844888: hda_get_response: [0000:00:1b.0:0] val=0x00004011
 alsa-sink-CX205-2584  [001] ....   279.855672: hda_send_cmd: [0000:00:1b.0:0] val=0x01020011
 alsa-sink-CX205-2584  [001] ....   279.855722: hda_get_response: [0000:00:1b.0:0] val=0x00000000
 alsa-sink-CX205-2584  [001] ....   279.855725: hda_send_cmd: [0000:00:1b.0:0] val=0x011a0000
 alsa-sink-CX205-2584  [001] ....   279.855758: hda_get_response: [0000:00:1b.0:0] val=0x00004011
 alsa-sink-CX205-2584  [001] ....   279.867648: hda_send_cmd: [0000:00:1b.0:0] val=0x01120011
 alsa-sink-CX205-2584  [001] ....   279.867701: hda_get_response: [0000:00:1b.0:0] val=0x00000000
 alsa-sink-CX205-2584  [001] d...   279.867829: snd_hdac_stream_start: stream_tag: 5
 alsa-sink-CX205-2584  [001] d...   297.821668: snd_hdac_stream_stop: stream_tag: 5
[Set sound on with hda-verb]
        hda-verb-3649  [002] ....   300.602038: hda_send_cmd: [0000:00:1b.0:0] val=0x01f70500
        hda-verb-3649  [002] ....   300.602087: hda_get_response: [0000:00:1b.0:0] val=0x00000000
[Start/stop a Youtube video]
 alsa-sink-CX205-2584  [001] d...   312.264676: snd_hdac_stream_start: stream_tag: 5
 alsa-sink-CX205-2584  [001] d...   376.447668: snd_hdac_stream_stop: stream_tag: 5
 alsa-sink-CX205-2584  [001] d...   389.212522: snd_hdac_stream_start: stream_tag: 5
 alsa-sink-CX205-2584  [001] d...   405.072648: snd_hdac_stream_stop: stream_tag: 5
 alsa-sink-CX205-2584  [001] d...   410.938035: snd_hdac_stream_start: stream_tag: 5
[Sound cuts]

I tried to boot with the kernel option "acpi=off" in order to check if ACPI had a role in this issue, as this bug suggested that it might be caused by an over-aggressive power management. But the sound still cuts after some time without ACPI.
The sound chip is therefore put to sleep by another element that I'm not able to find, only by changing the power state of a pin.
Any idea how I could identify it? Could it be the BIOS?

A: This is actually because the sound chip overheats.
A proper hardware fix would attach a small heat sink to the sound chip.
There is a software poke for the chip that delays the overheating. I put the command into my sister's Toshiba Satellite's /etc/rc.local. I'll have to contact her to get the command as I don't recall it from memory. I'll update this answer as soon as I have the details.
Update:
# turn on power management for audio codec
# to solve loosing sound after a few minutes
echo "1" > /sys/module/snd_hda_intel/parameters/power_save


text:
Q: CSS minifier choice I'm looking into upgrading to a newer CSS minifier which can minify CSS in PHP. I'm currently using an older version of https://github.com/mrclay/minify
However, I've also found http://code.google.com/p/cssmin/ which seems to update a little more frequently and is mentioned often.
What are your experiences with both libraries when it comes to speed and compatibility also with newer CSS3 rules and htc files?
I've already found that Minify has to be edited in my situation to work in my websites as the including doesn't seem to work very well when placed in another directory, which makes easy updates by replacing files more work.
The minified CSS will be stored in a CSS file once until the original CSS file is updated, so the minifier will not run too often. However, I don't want visitors to have to wait too long when they are the first to visit a site after the CSS has been updated.
Thanks in advance!

A: I also normally use my own minifier:
<?php
function compress ($code) {
    $code = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $code);
    $code = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $code);
    $code = str_replace('{ ', '{', $code);
    $code = str_replace(' }', '}', $code);
    $code = str_replace('; ', ';', $code);

    return $code;
}

But have switched to SASS recently so now I use its --style=compressed.
I've also tried CSSTidy which does more than just minify and works fine with PHP:
<?php
include DOCROOT . 'Lib/CSSTidy/class.csstidy.php';

$cssTidy = new csstidy();

$cssTidy->parse($CSSCode);
$cssTidy->set_cfg('remove_last_;', true);

echo $cssTidy->print->plain();

A: YUI compressor. You can even create an ANT task to run it over your CSSs while generating deployable version and stuff

A: Although this isn't a programming question, I actually use my own, very simple minifier:
public static function CompressCssFile($file) {
    ob_start(array(self::GetInstance(), 'compressCss'));

    header('Cache-Control: max-age='.(3600 * 24).', must-revalidate');
    header('Content-type: text/css');
    header('Expires: ' . gmdate('D, d M Y H:i:s', time() + (3600 * 168)) . ' GMT');
    header('Last modified: ' . (file_exists($file) ? filemtime($file) : gmdate('D, d M Y H:i:s', time())) . ' GMT');

    include_once $file;
    ob_end_flush();
}

private function compressCss($buffer) {
    // Remove comments:
    $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
    // Remove tabs, excessive spaces and newlines
    $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '   '), '', $buffer);

    return $buffer;
}

Works great for me.

A: http://code.google.com/p/minify/
I use this on all my projects. It's easy to setup: just drop the "min" directory in your root folder, then go to http://yourserver.com/min to add files to the minify URL.
It's main advantage is for production however, it can be frustrating to use in development as the files get cached (so if your CSS file is constantly changing this isn't your best choice). However it's very powerful for combining multiple CSS or multiple JS files and caching the combined, minified file for significantly optimized load time.

P.S.
I use this in combination with lessphp https://github.com/leafo/lessphp
This less PHP implementation still has some bugs regarding parsing percentages but other than that works like a charm.

A: This is pretty good: https://github.com/leafo/lessphp
You can use it in your PHP scripts as a class or execute it from the command line. It compiles Less into CSS and can also minify it. Even if you're not using Less, it can still minify plain old CSS.

A: As the author of https://packagist.org/packages/tubalmartin/cssmin may I suggest you to give it a try? It's a PHP port initially based on YUI compressor. It should cover CSS3 just fine if you ask me ;)

A: This article also has a nice bit of sample code with an explanation. I find this block of code to be more complete and easier to read than some of the others here:
function minimizeCSS($css){
    $css = preg_replace('/\/\*((?!\*\/).)*\*\//', '', $css); // negative look ahead to remove comments
    $css = preg_replace('/\s{2,}/', ' ', $css); // remove extra whitespace
    $css = preg_replace('/\s*([:;{}])\s*/', '$1', $css); // remove unneeded whitespace
    $css = preg_replace('/;}/', '}', $css); // remove last semicolon
    return $css;
}

A test is:
/* crazy ** /** test */ body { /* who would write css
 like this? */background:    white   !important;}
a
{
color :blue
;
}

Which becomes:
body{background:white !important}a{color:blue}

Which test for correct handling of the following cases:

*

*Two comments on a single line

*Extra asterisks and slashes in a comment

*A necessary white space that shouldn't be removed

*A comment that spans multiple lines


text:
Q: Why is RiverPod StreamProvider stuck in loading even though Stream.empty() should be returning when database is null I'm using this great flutter/riverpod/firebase starter architecture. On my initial flutter screen, which imports top_level_providers.dart the loading parameter is all that is ever called.
In my accountStreamProvider when the databaseProvider returns null Stream.empty() is emitted, which according to the docs "This is a stream which does nothing except sending a done event when it's listened to.".
Why isn't the data parameter being called in the account.when section?
root_screen.dart
class AppStartupScreenRouter extends ConsumerWidget {
  const AppStartupScreenRouter({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context, ScopedReader watch) {
    final didCompleteOnboarding = watch(onboardingViewModelProvider.state);
    AsyncValue<Account> account = watch(accountStreamProvider);

    return account.when(
      data: (data) {
        if (data != null) {
          // evaluate the account info data and
          // return a screen widget
        } else if (didCompleteOnboarding) {
          // return a screen widget
        }

        return IntroScreen();
      },
      loading: () => LoadingScreen(),
      error: (err, stack) => EmptyContent(),
    );
  }
}

top_level_providers.dart
final firebaseAuthProvider =
    Provider<FirebaseAuth>((ref) => FirebaseAuth.instance);

final authStateChangesProvider = StreamProvider<User>(
    (ref) => ref.watch(firebaseAuthProvider).authStateChanges());

final databaseProvider = Provider<FirestoreDatabase>((ref) {
  final auth = ref.watch(authStateChangesProvider);

  if (auth.data?.value?.uid != null) {
    return FirestoreDatabase(uid: auth.data?.value?.uid);
  }

  return null;
});

final accountStreamProvider = StreamProvider<Account>((ref) {
  final db = ref.watch(databaseProvider);
  return db != null ? db.accountStream() : Stream.empty();
});

firestore_database.dart
class FirestoreDatabase {
  FirestoreDatabase({@required this.uid})
      : assert(
            uid != null, 'Cannot create FirestoreDatabase entry with null uid');
  final String uid;

  final _service = FirestoreService.instance;

  Future<void> setAccount(Account account) => _service.setData(
        path: FirestorePath.account(uid),
        data: account.toMap(),
      );

  Stream<Account> accountStream() => _service.documentStream(
        path: FirestorePath.account(uid),
        builder: (data, documentId) => Account.fromMap(data, uid),
      );

  Future<void> deleteAccount(Account account) =>
      _service.deleteData(path: FirestorePath.account(uid));
}

account.dart
@immutable
class Account extends Equatable {
  const Account({
    @required this.id,
    @required this.firstName,
    @required this.lastName,
  });

  final String id;
  final String firstName;
  final String lastName;

  @override
  List<Object> get props => [
        id,
        firstName,
        lastName,
      ];

  @override
  bool get stringify => true;

  factory Account.fromMap(Map<String, dynamic> data, String documentId) {
    if (data == null) {
      return null;
    }

    final firstName = data['firstName'] as String;
    final lastName = data['lastName'] as String;

    if (firstName == null || lastName == null) {
      return null;
    }

    return Account(
      id: documentId,
      firstName: firstName,
      lastName: lastName,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'firstName': firstName,
      'lastName': lastName,
    };
  }
}

A: Stream.empty() never contains any data. If this is what your StreamProvider returns, the data callback will not be called. Most likely you'll get loading only.
In order to get a data callback, your stream should return at least one element (whether it's null or not).


text:
Q: How to find and delete many numbers in Word I have a 300 page research paper and I have to delete probably close to 1000 items, for example:

action seeking to enjoin the defendants from violating the minimum wage requirements and to enforce *1532 the record-keeping and child labor provisions of the Act.

I need to delete the *1532 which normally the easy Ctrl+F *1532 would be the route, but the numbers are all different so I would have to start from the highest one and count down (but the numbers aren't in any simple order because of the nature of the paper). How can I remove all such strings?

A: I'm using Word 2003.
In order to search and replace all occurrence of " *####" strings in your document, I used the following search parameter with the "Use wildcards" option:
 \*<[0-9]*>

Note the space in front of the first "\"


text:
Q: What is appropriate UML class relationship? In my case, what is appropriate relationship between CarBuilder and SuperCar (SportCar as well)?
Explanation: CarBuilder holds an array of Car class's instance but it doesn't construct any instance of Car class. Instead, it constructs SportCar, and SuperCar classes' instances by directly call CreateInstance() method of these two classes.
Class Diagram:CarBuilder

A: In your question you are describing three different relationships -- a compositional one (that you already have), and then two others to the constructors of SuperCar and SportCar. So I'd just add an association to SuperCar and SportCar from CarBuilder.
Incidentally, it seems unlikely that you'd only ever have a car composed within CarBuilder -- maybe you mean a (weak) aggregate rather than a composition? Surely a car can exist outside CarBuilder? Also, this looks like a partial implementation of the strategy pattern, might be worth looking whether that's relevant.


text:
Q: Repairing Hooks and Permissions in Migrated Gitolite Repo I had a gitolite pre-g2 repository I am attempting to get going on g3.
I copied over the entire repositories folder, and started with a clean g3 conf file, and removed all the gl-perms files to have a clean slate. I am trying to get a couple repos up and running with per-repo permissions.
Specifically I have my admin access keys and can clone and push the repo. This is defined the gitolite.conf as:
@admin = nikolaj

repo @all
    RW+ = @admin

Then for the individual repo, I made sure my name (nikolaj) was in the gl-creator file, and removed the old gl-perms file.
I then try to run
ssh git@myserver perms my/repo

and I get
FATAL: sorry you are not authorised

Any help on how I can go about debugging this is greatly appreciated!

A: Make sure you followed the migration guide and did preset your gitolite.rc file

If you don't preset the rc (in this case, by commenting out the 'ssh-authkeys' line) before running gitolite setup, your ~/.ssh/authorized_keys file will get clobbered.

In your case, you did get a new gitolite.rc file, but still check if your  ~/.ssh/authorized_keys is still intact (with a forced-command using nikolaj as parameter)


text:
Q: Как изменить выпадающий список в инспекторе из кода? Я пишу игру на юнити. Есть задача, менять значение выпадающего списка (!В инспекторе!) во время игры, из кода. Необходимо написать метод, выполняющий эту задачу. Как это реализовать? Вот код скрипта: https://pastebin.com/3MRiSF4C

A: Герман, добрый день, насколько я понимаю, вам нужно создать выпадающий список и менять его значения во время игры программно, из скрипта. В предыдущем ответе предложили сделать как-то что-то с enum. Однако перечисление enum является строго типизированным значением, что значит, что вы не можете менять его в "рантайме", то есть во время игры. Вы можете только задать сразу стартовые значения из скрипта. Перечисления - это, скажем так, константа.
Вместо этого я могу предложить вам попробовать реализовать вашу идею с помощью массива со значениями:
string[] modes = new string[] {"Disabled", "ClickAnywhere", "ClickOnDialog", "ClickOnButton"};

И простой переменной типа string:
string current_mode;

Когда нужно сменить тип, то просто сменяете:
current_mode = modes[2];
Или можно вообще без массива и менять напрямую:
current_mode = "ClickOnDialog";
Чтобы проверить режим, используете простейшую проверку строк:
switch (current_mode) {
    case "Disabled":
        // Do 1
        break;
    case ClickAnywhere:
        // Do 2
        break;
}

Очень надеюсь, что помог вам. Если есть какие-либо вопросы - задавайте, я обязательно отвечу. Если мой ответ вам помог, пожалуйста, примите его, нажав на галочку.

A: Такое выпадающее меню легко создать. В своём скрипте, где вы хотите такое реализовать создаёте перечисление enum, в нем будут содержаться элементы меню. Потом просто создаете публичный экземпляр этого перечесления. А в методе Update просто проверяете этот экземпляр.


text:
Q: Emscripten throws exception for unresolved mcount symbol Trying to get emscripten to build an old C project. It builds, but throws a warning:
warning: unresolved symbol: mcount
Which is weird, because that's not something in my code, but it shows up in the .js file all over the place and in weird places too. Can't tell what it's doing.
Trying to run it in a browser throws an exception from the missing function.
uncaught exception: abort(-1) at jsStackTrace@file: ...

A: Turns out it was the -pg gcc flag I was previously calling so I could profile it.
emcc main.c display.o azure.o -o main.html -lm  -s USE_SDL=2 -s USE_SDL_TTF=2 -g -Wall  -pg -O2 -Wl,-rpath,.
It inserts it's own _mcount functions everywhere to see how long parts take.
Remove it and remember next time you profile something to not let that get into the commit.


text:
Q: How to handle events in extended classes? When one extends a class, how is the proper way of setting code to be executed upon some event of the base class?
Should one handle the base class event this way:
Public Class Class2
    Inherits Class1

    Private Sub MyBase_MyEvent(sender as object, e as eventargs) Handles MyBase.MyEvent
        ' do stuff here
    End Sub
End Class

Or should one override the event caller sub?
Public Class Class2
    Inherits Class1

    Protected Overrides Sub OnMyEvent(e as EventArgs)
        MyBase.OnMyEvent(e)
        ' do stuff here
    End Sub
End Class

Thank you very much

A: I got and answer at https://softwareengineering.stackexchange.com/a/343769/234737 and post it here for record and help of others with same question:

Both options are fine and common. The big difference: with option 1, you can't necessarily tell what order the handlers are fired in, while with the second option, you can decide whether MyBase.OnMyEvent is called before or after your overridden implementation.


text:
Q: How to create solr password hash From solr documentation to create a user I need to add following lines to security.json config file:
"authentication":{
  "class":"solr.BasicAuthPlugin",
  "credentials":{
    "solr":"IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0= Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c="
  }
},

I know that under authentication.credentials the key solr is the username and value IV0EHq1OnNrj6gvRCwvFwTrZ1+z1oBbnQdiVC3otuq0= Ndd7LKvVBAaZIF0QAVi1ekCfAJXr1GGfLtRUXhgrF8c= is the hash of password SolrRocks.
But my question is, how can I generate that hash?
The documentation does not mention it anywhere,
It does not look like md5, sha1, argon nor any hash known to me.
After decoding the base64 it seems to be stored as some binary data.
What kind of hash is that, and how can I create it from bash?

A: You'd usually use set-user in the Authentication API to add the user.
rmalchow on GitHub has created a standalone version for bash:
#!/bin/bash
PW=$1
SALT=$(pwgen 48 -1)
echo "hash    : $(echo -n "$SALT$PW" | sha256sum -b | xxd -r -p | sha256sum -b | xxd -r -p | base64 -w 1024) $(echo -n "$SALT" | base64 -w1024)"


text:
Q: Pulse LED on button toggle in QT I am learning Qt and i came up with an idea to switch on and off an LED with buttons, i got it working but i couldn't figure out how to implement the same with a toggle button. I will be posting the code below, please take a look and let me know how i can implement the above stated behavior.

pulseledwidget.h
#ifndef PULSINGLEDWIDGET_H
#define PULSINGLEDWIDGET_H

#include <QLabel>
#include <QPixmap>
#include <QTimer>
#include <QObject>
#include <QDebug>

class pulsingLedWidget : public QLabel
{
    Q_OBJECT
public:
    explicit pulsingLedWidget(QWidget *parent = 0);
public slots:
    void startPulsing();
    void extinguish();
private:
    QPixmap onPixmap,offPixmap;
    QTimer timer;
    bool state;
};

#endif // PULSINGLEDWIDGET_H

pulseledwidget.cpp
#include "pulsingledwidget.h"

pulsingLedWidget::pulsingLedWidget(QWidget *parent) : QLabel(parent)
{
    onPixmap.load(":/ledon.png");
    offPixmap.load(":/ledoff.png");

    state = true;

    setPixmap(offPixmap);
    timer.setInterval(200);
    connect(&timer,SIGNAL(timeout()),this,SLOT(startPulsing()));
}

void pulsingLedWidget::startPulsing()
{
    timer.start();
    if(state)
    {
        setPixmap(onPixmap);
        state = false;
    }
    else
    {
        setPixmap(offPixmap);
        state = true;
    }
}

void pulsingLedWidget::extinguish()
{
    timer.stop();
    setPixmap(offPixmap);
}

leddialog.h
#ifndef LEDDIALOG_H
#define LEDDIALOG_H

#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include "pulsingledwidget.h"

class ledDialog : public QDialog
{
    Q_OBJECT
public:
    explicit ledDialog(QWidget *parent = 0);
private:
    QPushButton *onbutton;
    QPushButton *offbutton;
    QVBoxLayout *layout;
    pulsingLedWidget *ledwidget;
};

#endif // LEDDIALOG_H

leddialog.cpp
#include "leddialog.h"

ledDialog::ledDialog(QWidget *parent) : QDialog(parent)
{
    QPushButton *onbutton = new QPushButton("On");
    QPushButton *offbutton = new QPushButton("Off");
    QVBoxLayout *layout = new QVBoxLayout(this);
    pulsingLedWidget *ledwidget = new pulsingLedWidget(this);

    ledwidget->setAlignment(Qt::AlignCenter);

    layout->addWidget(ledwidget);
    layout->addWidget(onbutton);
    layout->addWidget(offbutton);

    resize(150,200);
    connect(onbutton,SIGNAL(clicked(bool)),ledwidget,SLOT(startPulsing()));
    connect(offbutton,SIGNAL(clicked(bool)),ledwidget,SLOT(extinguish()));

}

What i have tried :
leddialog.h
#ifndef LEDDIALOG_H
#define LEDDIALOG_H

#include <QDialog>
#include <QVBoxLayout>
#include <QPushButton>
#include "pulsingledwidget.h"

class ledDialog : public QDialog
{
    Q_OBJECT
public:
    explicit ledDialog(QWidget *parent = 0);
private slots:
    void makeDecision(bool state);
private:
    QPushButton *onbutton;
    QPushButton *offbutton;
    QVBoxLayout *layout;
    pulsingLedWidget *ledwidget;
};

#endif // LEDDIALOG_H

leddialog.cpp
#include "leddialog.h"

ledDialog::ledDialog(QWidget *parent) : QDialog(parent)
{
    QPushButton *onbutton = new QPushButton("On");
    QPushButton *offbutton = new QPushButton("Off");
    QVBoxLayout *layout = new QVBoxLayout(this);
    pulsingLedWidget *ledwidget = new pulsingLedWidget(this);

    ledwidget->setAlignment(Qt::AlignCenter);

    onbutton->setCheckable(true);

    layout->addWidget(ledwidget);
    layout->addWidget(onbutton);
    layout->addWidget(offbutton);

    resize(150,200);
connect(onbutton,SIGNAL(toggled(bool)),this,SLOT(makeDecision(bool)));

}

void ledDialog::makeDecision(bool state)
{
    if(state)
    {
        ledwidget->startPulsing();
    }
    else
    {
        ledwidget->extinguish();
    }
}

but the above procedure is not working. I tried to run it in debug mode to know the mistake that i have made, it is showing "Segmentation fault" error.


text:
Q: GTK+ How do I find which radio button is selected? The tutorial here http://developer.gnome.org/gtk-tutorial/2.90/x542.html
shows how to set up the radio buttons, but neglects to tell you how to use them.
How do I then find which radio button is selected?
My solution:
Initialise radio buttons with:
rbutton1 = gtk_radio_button_new_with_label(NULL, "button1");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton1, TRUE, TRUE, 0);

rbuttonGroup = gtk_radio_button_get_group(GTK_RADIO_BUTTON(rbutton1)); /*not sure what I'd use this line for currently though*/
rbutton2 = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rbutton1), "button 2");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton2, TRUE, TRUE, 0);

rbutton3 = gtk_radio_button_new_with_label_from_widget(GTK_RADIO_BUTTON(rbutton1), "button 3");
gtk_box_pack_start(GTK_BOX(rbutton_box), rbutton3, TRUE, TRUE, 0);

And update a variable telling you which radio button is selected with this method:
        void checkRadioButtons()
{
    if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton1))==TRUE) selectedRadioButton =1;
    if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton2))==TRUE) selectedRadioButton =2;
    if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON(rbutton3))==TRUE) selectedRadioButton =3;
}

A: Google brought me here for python / pygtk / pygtk3 searches, so I hope its okay that I post a pygtk solution:
def _resolve_radio(self, master_radio):
    active = next((
        radio for radio in
        master_radio.get_group()
        if radio.get_active()
    ))
    return active

This uses a generator to return the first (which should be the only) active radio box that is active.

A: This is how I do it.
GtkRadioButton * radio_button;
GtkRadioButton * radio_button1;
GtkRadioButton * radio_button2;
...
GSList * tmp_list = gtk_radio_button_get_group (radio_button);//Get the group of them.
GtkToggleButton *tmp_button = NULL;//Create a temp toggle button.

while (tmp_list)//As long as we didn't reach the end of the group.
{
  tmp_button = tmp_list->data;//Get one of the buttons in the group.
  tmp_list = tmp_list->next;//Next time we're going to check this one.

  if (gtk_toggle_button_get_active(tmp_button))//Is this the one active?
    break;//Yes.

  tmp_button = NULL;//We've enumerated all of them, and none of them is active.
}
//Here. tmp_button holds the active one. NULL if none of them is active.

See the discussion here.
I don't know if they will add this function into it (seems not).

A: Here's how I suggest doing it:
void radio_button_selected (GtkWidget *widget, gpointer data)
{
    if (gtk_toggle_button_get_active (GTK_TOGGLE_BUTTON (widget))
    {
        GSLIST *group = gtk_radio_button_get_group (GTK_RADIO_BUTTON (widget));
        g_print ("Index = %i%\n", g_slist_index (group, widget));
    }
}

A: You may connect to the GtkToggleButton::toggled signal instead. In the associated callback, you'll be able to update your variable. As for the call to gtk_radio_button_get_group, you only need it if you call gtk_radio_button_new_with_label instead of gtk_radio_button_new_with_label_with_widget, as specified in the tutorial you're refering to.

A: Let's create a serie of buttons :
for severity in levels:
    radio = gtk.RadioButton(group=radioButtons, label=severity)
    if severity == actualLevel:
        radio.set_active(True)
    hBox.pack_start(radio, True, True, 3)
    radio.connect('toggled', self.radioButtonSelected, severity)

and all buttons are connected to the same handler :
def radioButtonSelected(self, button, currentSeverity):
    # proceed with the task
    # as you can see, button is passed by as argument by the event handler
    # and you can, for example, get the button label :
    labelReadFromButton = button.getLabel()

A: Use lambda expressions if you dont want to mess around with the annoying methods, still have to use connect though, but its alot easier to read:
Enum RadioValues { A, B, C, none };

RadioValues values = RadioValues.none; // only needed if you dont have an initially selected radio button

MyConstructor()
{
   Build();
   // asumming you have 3 radio buttons: radioA, radioB, radioC:
   radioA.Toggled += (sender,e) => values = RadioValues.A;
   radioB.Toggled += (sender,e) => values = RadioValues.B;
   radioC.Toggled += (sender,e) => values = RadioValues.C;

}

and thats it, no methods to deal with, and you dont have to restrict yourself to just that either, you can also use an anonymous function if you need more flex--of course the next step after that is using methods. Unfortunately they didnt offer a simple .Checked property, my next suggestion is to override the radio button itself and chain a Checked property when it's toggled state is changed, emulating other frameworks like MFC, Qt, and Winforms... etc.
PS: I left out boilerplate code for simplicity's sake, which can make answers a bit more muddled and you probably just want the facts not a demonstration on whether or not I can properly call a constructor :)

A: My solution for GTKmm is quite easier,
You just have to call the function :
my_radio_button.get_active(); \n

This will return either 0 if its unactive or 1 if its active.

A: This is a demo code using Radio Buttons, where you can find how I find which radio button is selected:
#include <gtkmm/window.h>
#include <gtkmm/box.h>
#include <gtkmm/radiobutton.h>
#include <gtkmm/separator.h>
#include <gtkmm/application.h>
#include <iostream>

class ButtonWindow : public Gtk::Window
{
private:
   //Child widgets:
   Gtk::Box m_Box_Top, m_Box1, m_Box2;
   Gtk::RadioButton m_RadioButton1, m_RadioButton2, m_RadioButton3;
   Gtk::Separator m_Separator;
   Gtk::Button m_Button_Close;
   Gtk::RadioButton *m_SelectedButton{nullptr};

public:
   ButtonWindow()
      : m_Box_Top(Gtk::ORIENTATION_VERTICAL),
        m_Box1(Gtk::ORIENTATION_VERTICAL, 15),
        m_Box2(Gtk::ORIENTATION_VERTICAL, 0),
        m_RadioButton1("button 1"),
        m_RadioButton2("button 2"),
        m_RadioButton3("button 3"),
        m_Button_Close("close")
   {
      // Set title and border of the window
      set_title("radio buttons");
      set_border_width(0);

      // Put radio buttons 2 and 3 in the same group as 1:
      m_RadioButton2.join_group(m_RadioButton1);
      m_RadioButton3.join_group(m_RadioButton1);

      // Add outer box to the window (because the window
      // can only contain a single widget)
      add(m_Box_Top);

      //Put the inner boxes and the separator in the outer box:
      m_Box_Top.pack_start(m_Box1);
      m_Box_Top.pack_start(m_Separator);
      m_Box_Top.pack_start(m_Box2);

      // Set the inner boxes' borders
      m_Box1.set_border_width(20);
      m_Box2.set_border_width(10);

      // Put the radio buttons in Box1:
      m_Box1.pack_start(m_RadioButton1);
      m_Box1.pack_start(m_RadioButton2);
      m_Box1.pack_start(m_RadioButton3);

      // Put Close button in Box2:
      m_Box2.pack_start(m_Button_Close);

      // Connect the button signals:
#if 1 // Full C++11: (change this to #if 0 to use the traditional way)
      m_RadioButton1.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton1);});
      m_RadioButton2.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton2);});
      m_RadioButton3.signal_clicked().connect([&]{on_radio_button_clicked(m_RadioButton3);});

      m_Button_Close.signal_clicked().connect([&]{on_close_button_clicked();});
#else // Traditional:
  m_RadioButton1.signal_clicked() // Full sigc
     .connect(sigc::bind(sigc::mem_fun(*this, &ButtonWindow::on_radio_button_clicked),
                         sigc::ref(m_RadioButton1)));

  m_RadioButton2.signal_clicked() // sigc && C++98
     .connect(std::bind(sigc::mem_fun(*this, &ButtonWindow::on_radio_button_clicked),
                        std::ref(m_RadioButton2)));

  m_RadioButton3.signal_clicked() // Full C++98
     .connect(std::bind(&ButtonWindow::on_radio_button_clicked, this,
                        std::ref(m_RadioButton3)));

      m_Button_Close.signal_clicked()
         .connect(sigc::mem_fun(*this, &ButtonWindow::on_close_button_clicked));
#endif

      // Set the second button active:
      m_RadioButton2.set_active();

      // Make the close button the default widget:
      m_Button_Close.set_can_default();
      m_Button_Close.grab_default();

      // Show all children of the window:
      show_all_children();
   }

protected:
   //Signal handlers:
   void on_radio_button_clicked(Gtk::RadioButton& button)
   {
      if(m_SelectedButton != &button && button.get_active())
      {
         m_SelectedButton = &button;
         std::cout << "Radio "<< m_SelectedButton->get_label() << " selected.\n";
      }
   }

   void on_close_button_clicked()
   {
      hide(); // Close the application
   }
};

int main(int argc, char *argv[])
{
   auto app = Gtk::Application::create(argc, argv, "org.gtkmm.example");

   ButtonWindow button;

   //Shows the window and returns when it is closed.
   return app->run(button);
}


text:
Q: How to turn the reflection about $y=x$ into a rotation. If we reflect $(x,y)$ about $y=x$ then we get $(y,x)$. And because $x^2+y^2=y^2+x^2$ this can also be represented by a rotation.
Using this we get:
$$(x,y)•(y,x)=2xy=(x^2+y^2)\cos (\theta)$$
Hence
$\theta=\arccos (\frac{2xy}{x^2+y^2})$
So using complex numbers we rotate $(x,y)$ clockwise/counterclockwise an angle of $\arccos (\frac{2xy}{x^2+y^2})$ depending on which side of $y=x$ the point is, i.e. Depending on wether or not $y > x$.

My question :
  How can we know the angle is $\arccos (\frac{2xy}{x^2+y^2})$ without using the already known result that $(x,y)$ rotated about $x=y$ is $(y,x)$?

A: If $\theta$ is the angle between the x-axis and the line from 0 to $(x,y)$, then $\theta = \arccos(\frac{y}{\sqrt{x^2+y^2}})$.  We reflect about a line with angle $\frac{\pi}{4}$, so the angle between $(x,y)$ and the line $x=y$ is $\frac{\pi}{4} - \theta$.  The angle between $(x,y)$ and the reflected point will be double the previous angle, or $\frac{\pi}{2} -2 \theta$.  Compute the cosine of $\frac{\pi}{2} - 2\theta$ and you will get $\frac{2xy}{x^2+y^2}$.

A: What follows might be difficult to understand because of abuse of notation.
First calculate the orthogonal projection of $(x,y)$ onto the line $y=x$ (i.e. the point on the line $y=x$ which is closest to the point $(x,y)$).
Call the resulting point $(a,b)$.
Then calculate the angle between the vector with $(a,b)$ as its arrow and $(0,0)$ as its base and the vector with $(x,y)$ as its head and $(0,0)$ as its base. Call this angle $\theta$.
If $(x,y)$ is $\theta$ to the right of $y=x$ then its reflection about the line is $\theta$ to the left of $y=x$ (and $2\theta$ to the left of the vector with arrow $(x,y)$ and base at the origin).
Likewise everything above with left and right interchanged if $(x,y)$ is $\theta$ to the left of $y=x$.
The rotation of $(a,b)$ by $\theta$ or $(x,y)$ by $2\theta$ can be accomplished by using a 2d rotation matrix: https://en.wikipedia.org/wiki/Rotation_matrix


text:
Q: ORA-01005 NullPassword: What does Oracle consider to be null? I have a piece of code along the following lines:
Properties props = new Properties();
props.put("user", user.getUserName());
props.put("password", user.getPassword());
//add more properties
//...
Connection conn = DriverManager.getConnection("url",props);

So, there is no way that I can see that a null password property can be passed into the connection.  Not only does user.getPassword() throw an exception if the password is null, setting a null value on props would throw an NPE.  Either of this will cause the call to DriverManager.getConnection(..) to be bypassed.  Yet on occasion, the connection attempt fails and Oracle returns an

ORA-01005 ORA-01005: null password given; logon denied

The only way I can recreate this on demand is by commenting out the line that sets the password.  Otherwise I can't see how a null value is getting to Oracle.
Could it be that there are some values that Oracle reports to be null that are not strict Java nulls?
I'm using oracle.jdbc.OracleDriver to connect to Oracle 11.2.0.3.0
Many thanks for any help!

A: I think the Oracle jdbc driver considers the empty string to be equivalent to NULL.

A: Oracle database differs from Java in this sense. It treats String empty values as null.
See also Oracle treating empty string as NULL problem for a Java / JPA programmer


text:
Q: How to get process id in Ada? I want to make a method returning the calling process id, but can't seem to find how to do that in Ada. Must be looking in the wrong places.
How to get process id on windows and POSIX platforms?

A: The Florist binding to POSIX should work, but it is quite a sizeable library. Here is a simpler binding example, tested on Mac OS-X:
with Ada.Text_IO;
with Interfaces.C;
procedure My_Pid
is
   function Get_Pid return Interfaces.C.int
   with Import, Convention => C, External_Name => "getpid";
begin
   Ada.Text_IO.Put_Line (
      "My PID is" & Interfaces.C.int'Image (Get_Pid));
end My_Pid;

This assumes that the POSIX type pid_t, defined in <unistd.h>, is compatible with Interfaces.C.int, which may not hold on all POSIX platforms; the alternative AIUI is Interfaces.C.long.
I don't have access to a Windows system to test, but it seems there is a _getpid function (https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/getpid?view=msvc-170), with getpid (no leading underscore) as a deprecated alias (https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/posix-getpid?view=msvc-170).
There is also an extensive binding to the Win32 API, similar in scope to Florist, at https://github.com/AdaCore/win32ada.


text:
Q: Nativescript (angular) not finding module for lazy loading I am attempting to lazy load a module in my application. This example is supposed to work on angular, but it is throwing the following error:
Computed path '/Users/faridgarciayala/Library/Developer/CoreSimulator/Devices/D5EE2284-8088-43A1-A703-1A5C7021DF42/data/Containers/Bundle/Application/0D994956-6311-438F-B459-98BA7424EF1A/routingexample.app/app/one/one.module'
It is apparently trying to get the module from the emulator.
here is my repo
complete error log:
CONSOLE ERROR file:///app/tns_modules/@angular/core/bundles/core.umd.js:15768:28: ERROR Error: Uncaught (in promise): Error: Could not find module './one/one.module'. Computed path '/Users/faridgarciayala/Library/Developer/CoreSimulator/Devices/D5EE2284-8088-43A1-A703-1A5C7021DF42/data/Containers/Bundle/Application/0D994956-6311-438F-B459-98BA7424EF1A/routingexample.app/app/one/one.module'.
require@[native code]
file:///app/tns_modules/tns-core-modules/globals/globals.js:81:39
ZoneAwarePromise@file:///app/tns_modules/nativescript-angular/zone-js/dist/zone-nativescript.js:902:37
import@file:///app/tns_modules/tns-core-modules/globals/globals.js:79:27
loadAndCompile@file:///app/tns_modules/@angular/core/bundles/core.umd.js:18403:33
loadModuleFactory@file:///app/tns_modules/@angular/router/bundles/router.umd.js:3702:50
load@file:///app/tns_modules/@angular/router/bundles/router.umd.js:3690:56
file:///app/tns_modules/@angular/router/bundles/router.umd.js:2693:55
_tryNext@file:///app/tns_modules/rxjs/inte<…>

A: Try to this for lazy loading routing.
app-routing.module.ts :-
import { NgModule } from "@angular/core";
import { Routes } from "@angular/router";
import { NativeScriptRouterModule } from "nativescript-angular/router";

const routes: Routes = [
{ path: "", redirectTo: "/login", pathMatch: "full" },
{ path: "library", loadChildren: "~/pages/library/library.module#LibraryModule" },
{ path: "login", loadChildren: "~/pages/login/login.module#LoginModule" }
]

@NgModule({
imports: [NativeScriptRouterModule.forRoot(routes)],
exports: [NativeScriptRouterModule]
})
export class AppRoutingModule { }

Redirection Code:-
import { NgZone } from "@angular/core";
import { isIOS } from "tns-core-modules/platform";
import { RouterExtensions } from "nativescript-angular/router";

constructor(private zone: NgZone,
private _routerExtensions: RouterExtensions){ }

gotoStartPage() {
setTimeout(() => {
    this.zone.run(() => {
        this._routerExtensions.navigate(["library"], {
            clearHistory: (isIOS) ? true : false,
        });
    });
}, 500);
}


text:
Q: How do I using Application Designer, add Failure Class field from different Maximo table to Work Order Tracking? We want to "Categorize" our work orders more systematically. So far, we've been using Description, but we feel it is not a reliable way. We were hoping to use Failure Class as a starting point, but we find that having on a different tab discourages technicians and the help desk from classifying the work order.
Is it possible to add/duplicate the Failure Class field to Work Order Tracking screen?
Normally, I wouldn't ask, but was not clear if this was possible because Failure Class, Codes, and Tracking are different tables in Maximo. So, I wasn't sure how this would work exactly...

A: The simple answer is to use Application Designer's copy / paste functionality to duplicate the field. The specific field in question is on the top level of the Work Order Tracking application and facilitates interaction with the FAILURECODE attribute of the Main Object of the application, which is WORKORDER. Therefore, a copy / paste operation should be all you need. (Note: Application Designer's copy / paste functionality is used via that application's toolbar buttons, not Ctrl+C / Ctrl+V.) And if using Application Designer's copy / paste functionality doesn't work to your satisfaction, I would recommend exporting the XML for the application, copying the line of XML as desired and giving it a unique id, and importing the updated XML back in to Maximo. (Application Designer has toolbar buttons for exporting and importing an application's XML.)
You mentioned difficulty getting users to fill it in as a driver for asking the question. Another solution, which you can do as well as or instead of copying the field, is to specify the Failure Class on each Asset. Then, when an Asset is put on a Work Order, its Failure Class will be copied over, saving the users work and risk of not choosing correctly. And another idea is to highlight the Failure tab until a Failure Class is supplied.
And you also mentioned that the driver behind getting them to fill in the Failure Class, and etc, was to help categorize work. To that point, you should know that Failure Classes, in specific, and Failure Codes, in general, are intended to be used to help you determine what's going wrong with your assets, how often, and how the problems are being fixed. So, using them to categorize work is a bad idea. Instead, you should be using the Work Type field and Classifications, because categorizing work is what these are meant to be used for. The Work Type field is already on the Work Order tab, and Classifications fields are on the Specifications tab. You could copy the Classifications fields the same as I directed above for the Failure Class field.


text:
Q: Advanced Installer UI events I'm using Advanced Installer 14.2 and need to detect when a scroll box is scrolled to the bottom. If true, then set the "enable" property for the "Next" button. I don't see a scroll box attribute I can use to detect the scrolled to the bottom state. My requirement is to force the user to scroll through the entire EULA before being able to proceed.

A: Here's a solution for this in the FAQ from the from advancedinstaller.com.


text:
Q: My-Weather-Indicator Inaccurate, Not Able To Select Wunder Ground In Options I'm using My-Weather-Indicator, but it is never accurate! The Wunderground option is disabled and I can't select it! How do I enable it? I'm using Ubuntu 14.04 LTS.

And what does "Activate" mean?

A: You need an API key:
Wunderground: http://www.wunderground.com/weather/api/
World Weather Online: http://www.worldweatheronline.com/register.aspx
Then paste in your key and activate.

A: "we [Wunderground] will no longer provide free weather API keys as part of our program. If you have been directed to download our Weather Underground free API key by a third party provider, please contact your vendor for resolution."
https://www.wunderground.com/weather/api/


text:
Q: Variadic template method I would to create a class method that takes variadic argument (in template) and then use them to get (for example) the name of the passed argument.
I tried to implements (but it's not working):
#include <iostream>

struct St1 {};
struct St2 {};
struct St3 {};

class Test {
public:
    template<typename T>
    void method()
    {
        std::cout << typeid(T).name() << std::endl; // for example
    }

    template<typename T, typename ...Targs>
    void method()
    {
        method<T>();
        method<Targs...>();
    }
};

int main(void) {
    Test a;

    a.method<St1, St2, St3>();
    a.method<St1>();
}

And when I want to compile I get these errors, 'ambiguous':
testSpeed.cpp:29:19: error: call of overloaded 'method()' is ambiguous
     a.method<St1>();
                   ^
testSpeed.cpp:12:10: note: candidate: void Test::method() [with T = St1]
     void method()
          ^~~~~~
testSpeed.cpp:18:10: note: candidate: void Test::method() [with T = St1; Targs = {}]
     void method()
          ^~~~~~
testSpeed.cpp: In instantiation of 'void Test::method() [with T = St1; Targs = {St2, St3}]':
testSpeed.cpp:28:29:   required from here
testSpeed.cpp:20:18: error: call of overloaded 'method()' is ambiguous
         method<T>();
         ~~~~~~~~~^~
testSpeed.cpp:12:10: note: candidate: void Test::method() [with T = St1]
     void method()
          ^~~~~~
testSpeed.cpp:18:10: note: candidate: void Test::method() [with T = St1; Targs = {}]
     void method()

A: You can use SFINAE to disable variadic version when parameters pack is empty:
template<typename T, typename ...Targs,
    std::enable_if_t<sizeof...(Targs) != 0>* = nullptr>
void method()
{
    method<T>();
    method<Targs...>();
}

Demo

A: In C++17 this is pretty simple:
class Test {
public:
    template<typename T, typename... Ts>
    void method() {
        std::cout << typeid(T).name() << std::endl;
        if constexpr (sizeof...(Ts) > 0)
            method<Ts...>();
    }
};

In C++11 you can do this:
class Test {
    template<class> struct Tag {};

    template<typename T>
    void method_impl(Tag<T>) {
        std::cout << typeid(T).name() << std::endl;
    }

    template<typename T, typename... Ts>
    void method_impl(Tag<T> tag, Tag<Ts>... tags) {
        method_impl(tag);
        method_impl(tags...);
    }

public:
    template<typename... Ts>
    void method() {
        method_impl(Tag<Ts>{}...);
    }
};

With a slight modification empty packs can be handled automatically:
class Test {
    template<class> struct Tag {};

    void method_impl() { }

    template<typename T, typename... Ts>
    void method_impl(Tag<T>, Tag<Ts>... tags) {
        std::cout << typeid(T).name() << std::endl;
        method_impl(tags...);
    }

public:
    template<typename... Ts>
    void method() {
        method_impl(Tag<Ts>{}...);
    }
};

A: argument of function allows to select overload, not template parameters.
One solution is to turm your template argument into parameters:
template <typename ... Ts> struct Tag{};

class Test {
public:
    template<typename T>
    void method(Tag<T>)
    {
        std::cout << typeid(T).name() << std::endl; // for example
    }

    template<typename T, typename ...Ts>
    void method(Tag<T, Ts...>)
    {
        method(Tag<T>{});
        method(Tag<Ts...>{});
    }
};

int main() {
    Test a;

    a.method(Tag<St1, St2, St3>{});
    a.method(Tag<St1>{});
}

Demo
or
template <typename T> struct Tag{};

class Test {
public:
    template<typename T>
    void method(Tag<T>)
    {
        std::cout << typeid(T).name() << std::endl; // for example
    }

    template<typename T, typename ...Ts>
    void method(Tag<T>, Tag<Ts>...)
    {
        method(Tag<T>{});
        method(Tag<Ts>{}...);
    }
};

int main() {
    Test a;

    a.method(Tag<St1>{}, Tag<St2>{}, Tag<St3>{});
    a.method(Tag<St1>{});
}

Demo
But you can get rid of recursive calls (and of overloads):
Fold expression in C++17:
template<typename ... Ts>
void method()
{
    ((std::cout << typeid(Ts).name() << std::endl), ...);
}

In C++11/C++14, it is more verbose, and less clear:
template<typename ... Ts>
void method()
{
    std::initializer_list<int>{0, ((std::cout << typeid(Ts).name() << std::endl), 0)...};
}


text:
Q: ACTION_UP is not triggered for a quick/normal click on OnTouchListener.onTouch I have a button to trigger some action in MainActivity and I want to draw animation as follows: when user holds the button (ACTION_DOWN) it scales down, when the button is released (ACTION_UP or ACTION_CANCEL) it scales up and go back to its normal state.
This works great when user holds the button for some time, but for a normal click, ACTION_UP never gets called even though ACTION_DOWN does.
I searched in the documentation and checked almost every answer on stackoverflow but didn't find anything useful.
Here's what the documentation says: "While the framework tries to deliver consistent streams of motion events to views, it cannot guarantee it. Some events may be dropped or modified by containing views in the application before they are delivered thereby making the stream of events inconsistent. Views should always be prepared to handle ACTION_CANCEL and should tolerate anomalous situations such as receiving a new ACTION_DOWN without first having received an ACTION_UP for the prior gesture."
And here's my code:
button.setOnTouchListener { view, event ->
            when(event?.action){
                //behaves as expected
                MotionEvent.ACTION_DOWN -> {
                    scaleDown(view)
                }
                //the problem here: ACTION_UP gets called only when user holds the button for some time
                //and not for a quick/ normal click.
                MotionEvent.ACTION_UP -> {
                    scaleUp(view)
                    doSomething()
                }
                //behaves as expected
                MotionEvent.ACTION_CANCEL -> {
                    scaleUp(view)
                }
            }
            true
        }

I have two questions, First: why ACTION_UP never gets called for a quick/normal click?
Second: how to differentiate between normal click and when user holds the button for some time if i want to react in two different ways?

A: Question#1
I tried the below snippet and it was working as expected with long, normal, and quick clicks
button.setOnTouchListener { view, event ->

    if (event.action == MotionEvent.ACTION_DOWN) {
        Log.d("TESTOOO", "DOWN")
    } else if (event.action == MotionEvent.ACTION_UP) {
        Log.d("TESTOOO", "UP")
    }

    true
}

Question#2
Can you try setOnLongClickListener(), I tried it and worked fine

A: Answering my own question:
For the first question, the problem was with the animation not the OnTouchListener.
For the second question, to differentiate between a normal click and a long click, i had to calculate how many milliseconds have passed since ACTION_DOWN was triggered when ACTION_UP or ACTION_CANCEL is triggered.
If the difference between the two events is less than 300 milliseconds it's considered a normal click, else it's a long click.
button.setOnTouchListener { view, event ->
    val now = System.currentTimeMillis()
    when(event?.action){
        MotionEvent.ACTION_DOWN -> {
            scaleDown(view)
        }
        MotionEvent.ACTION_UP -> {
             scaleUp(view)
             if(now - event.downTime < 300){
                 //normal click
             }else{
                 //long click
             }
        }
        MotionEvent.ACTION_CANCEL ->
             scaleUp(view)
        }
   }
   true
}


text:
Q: Spatial databases learning resources for newbies? Would be taking up a course on spatial databases next semester.
Would anybody know a newbie friendly introductory resource?
A vendor neutral one would be preferable.

A: I strongly recommend the book "PostGIS in Action" by Regina Obe and Leo Hsu.
They are the same people who run the Boston GIS site mentioned above.
The book goes into a lot of detail about PostGIS but the concepts transfer well to other platforms.

A: *

*Spatial Databases course from School of Computing, Dublin Institute of Technology.

*Introduction to PostGIS & Spatial Database Tips and Tricks Workshop from OpenGeo

*Introduction to Spatial Databases slides from Toni Hernández

A: Beginning Spatial with SQL Server 2008 would definitely be helpful even though it is specific to SQL Server.  For now at least, SQL Server seems to be one of the better platforms for leaning about spatial SQL operations.
SQL Server Express is free and will give you full access to the same spatial capabilities you would get with the Enterprise version.

A: For Spatialite, the best resource is the official doc.
The main developers are maintaining a great cookbook and it's oriented general spatial database too. It's really good material for beginners.

A: take a look at http://www.bostongis.org
they have great "An almost idiot guide ..." for
PostGIS,
Microsoft SQL Server spatial and
SpatiaLite.
that is really a great start.

A: See also OSGeo's Searchable Database of Educational Material for courseware: http://www.osgeo.org/educational_content


text:
Q: Bayesian inference - Pi notation I often see people use $\pi(\theta|y)$ and $\pi(\theta)$ for posterior distribution and prior, respectively. e.g.
$\pi(\theta|y) \propto f(y|\theta)*\pi(\theta)$
sometime, the notation is simply written as
$p(\theta|y) \propto p(y|\theta)*p(\theta)$
I would like to know when $\pi(x)$ and $p(x)$ can be used interchangeably.
ps. I believe that there is no significant difference between $p(x)$ and $f(x)$. It only depends on one's preference; however, $p(x)$ might be more precise since it explicitly states that it is a probability distribution.


text:
Q: Throwing 6 sided cube 12 times. Probability of not getting 6 twice Throwing 6 sided cube 12 times.
What is the probability of rolling no more than two 6's?
My thoughts so far:
There are 6 outcomes for each throw, so 6¹² is the total number of outcomes.
(5/6)¹² is the number of outcomes that I don't get a 6.
(5/6)¹⁰ is that I don't get a 6 in 10 throws, so the last 2 don't matter.
Is my thinking correct here, or am I missing something ?
Can someone help me with understanding the solution. Thanks.

A: $$\binom{12}{0}(\frac{1}{6})^0(\frac{5}{6})^{12}+\binom{12}{1}(\frac{1}{6})^1(\frac{5}{6})^{11}+\binom{12}{2}(\frac{1}{6})^2(\frac{5}{6})^{10}$$
$\binom{12}{0}(\frac{1}{6})^0(\frac{5}{6})^{12}$ is the probability of no any 6
$\binom{12}{1}(\frac{1}{6})^1(\frac{5}{6})^{11}$ is the probability of one 6
$\binom{12}{2}(\frac{1}{6})^2(\frac{5}{6})^{10}$ is the probability of two 6's

A: Hint
Binomial distribution:
$$P(X=x)={n\choose x}p^x q^{n-x}$$
Where
$$n=\text{Number of trials}\\
x=\text{Number of succeses}\\
p=\text{Probability of succeding in one trial}\\
q=1-p$$

A: Rolling no more than two sixes would mean we either roll no six, $1$ six or we roll $2$ sixes in $12$ times. If random variable $X$ is the number of sixes then we have,
$P(X = 0) \, = (\frac{5}{6})^{12}$
$P(X = 1) \, = {12 \choose 1} \times \frac{1}{6} \times (\frac{5}{6})^{11}$
$P(X = 2) \, = {12 \choose 2} \times (\frac{1}{6})^2 \times (\frac{5}{6})^{10}$
Desired probability $ P (X \leq 2) = P(X = 0) + P(X = 1) + P(X = 2)$


text:
Q: presentModalViewController viewDidLoad not being called I have an event which calls a view to appear, but the -viewdidload event isn't appearing as expected each time it's called. Here's the method I use to call it...
[self presentModalViewController:addItemViewController animated:YES];

then inside the addItemViewController, the method is
- (void)viewDidLoad {
    NSLog(@"alright, lad!");
}

To close the view, I have a button with the code
- (IBAction)cancel {
    [self dismissModalViewControllerAnimated:YES];
}

the "alright, lad" log is shown the first time the view appears, but never again when it's launched. Is there a method I can use to let the app "forget" about the view? Or should I be using another load method? I tried loadView (I think) but that had a blank screen...
Thanks for any help!

A: viewDidLoad is only called when the view is first instantiated. If you're not recreating the view controller each time, you'll only get it called once (and called again if you get a memory warning, and the view is nil'd out). You probably want to use viewWillAppear: or viewDidAppear:.

A: Make sure you call the superclass in each of those methods, e.g.
- (void)viewWillAppear:(BOOL)animated {
  NSLog(@"view appeared");
  [super viewWillAppear:animated];
}


text: Q: What is the importance of magnetuc flux cutting the surface of coil Iam a bit confused about magnetic flux lines cutting a coil say if we have a rectangular coil abcd like in the dynamo and the sides ab and cd are perpendicular to the magnetic flux when the plane of the coil is parallel to it, then I read that in such case the magnetic flux cutting the coil is zero. I'm confused about how it is zero although ab and cd are perpendicular to the field, I mean it is not important that the field lines cut the surface of the coil or not as it is already cutting the sides of the coil. I'm saying this because when we calculate the average induced emf we say that if the coil position changed from parallel to perpendicular then the magnetic flux cutting the coil is +BA although it should be negative. Please try to understand me I feel like I'm very confused.


text:
Q: Set Iframe Value From Field Using JavaScript I have a CRM form with an iframe on it that contains an HTML textarea (id=textbox). On the form, I have a field called "Justification". I need the textarea value that is in the iframe, to be set to the value that is in the "Justification" field on the parent form Onload using javascript. is there a simple way to do this, and if so, can you provide a script? Thank you in advance, any help would be appreciated

A: There is quite a few different way to accomplish that goal, since you state a onload event in your tags, you could go with:
var parentValue = parent.document.getElementById("Justification").value;
document.getElementById("textbox").value = parentValue;

A: If the iframe src and the parent exist on the same domain you can use the contentWindow of the iframe to access the DOM elements. MDN contentWindow
If they don't exist on the same domain then the browser will prevent you from manipulating the DOM due to cross-origin restrictions.
If you have access to the source code for the parent and the iframe you could implement window.postMessage() to pass data between the parent and iframe. MDN postMessage


text:
Q: What is the best way to determine a value based on two different values in Python I need to determine the amount of damage done to a character depending on both the enemy and the weapon. Each weapon does a different amount of damage depending on who it attacks. What would be the best way to do this without writing a lot of if statements?

A: If you are looking at a generic approach, I would recommend building a lookup dictionary such as the following. You can use this dictionary to compute the damage,
def get_damage(enemy_type,weapon):
    damage_dict = {"enemy_type1":{'weapon1':10,'weapon2':20,'weapon3':50},
                   "enemy_type2":{'weapon1':5,'weapon2':20,'weapon3':45},
                   "enemy_type3":{'weapon1':15,'weapon2':20,'weapon3':40,'weapon4':50},
                   }
    return damage_dict.get(enemy_type).get(weapon)

print(get_damage('enemy_type2','weapon2'))


text:
Q: New terminal working directory When I login (using ssh) to other host and open a new tab (pressing CTRL + Shift + T). It sets current working directory to a particular directory in my home independent from current working directory on remote host.

*

*So what can be the reason for this behavior?

*And how can I change it?

I am using RedHat.

A: When you press Ctrl+Shift+T, Gnome-terminal looks at the current directory of the process that's running in this tab, and switches to that directory to run the process in the new tab.
Observe that if you type bash in a Gnome-terminal tab that's already running a shell and is in /directory1, and you run cd /directory2 in that instance of bash, then press Ctrl+Shift+T launches a new tab with a shell in /directory1. Gnome-terminal only looks at its child process's current directory, not at its descendants. (That's the only reasonable way, really: how would it decide which descendant to pick?)
When you run ssh to open a shell on another machine, Gnome-terminal does what it always do: when you open a new tab, that tab starts in the directory of the shell from which you ran the ssh command.
Gnome-terminal has no way to know about the current directory on another machine. To do that, it would need some very tight integration with SSH and with the remote shell. I'm not saying it's impossible — Emacs's Tramp parses the prompt from the remote shell to figure out the remote directory — but it has a cost in complexity, reliability and flexibility. Gnome-terminal gives you a terminal and lets you do what you want in it; Tramp takes control of the SSH connection and doesn't cope with arbitrary behavior of the remote shell.
You cannot change this without doing some nontrivial development work. You could use Emacs as your terminal emulator (but of course Emacs is far from being a drop-in replacement for Gnome-terminal, you'd need to pick up different habits). If all you need to do on the remote machine is manipulate files and not run programs, you can mount the files over SSHFS, and then you'd only be running a local shell so you'd get the current directory tracking that you want. But by far the simplest way to create a new tab in the same remote directory is to create a new tab, run the same ssh command, and copy-paste the remote path.


text:
Q: IE8 crashing on page load, debugger says nothing The report I get is that all browsers work just fine on this site (link below), except IE8.  I tested IE8, and it does crash on each new page load, then it reloads the tab and shows the page.  When I use the built in debugger, it simply crashes and restarts the tab, which turns debugging off.
If I put IE8 in compatibility mode, it works fine.  I turned on the debugger in compat mode and I don't get any errors.  The only console message that comes up is "LOG: [cycle] terminating; zero elements found be selector", which I doubt is a problem.
I did not develop this site, so I'm not really familiar with the JS code it's running, but it appears to be mostly jQuery and a plugin called jsDatePick.  There is also a swfobject.js, and it's using cufon.
I don't expect anyone to do massive debugging on my behalf, I can take care of that.  I was just hoping that someone might have come across a similar issue and might be able to pinpoint it quickly or at least point me in the first places to look before I start removing js includes one at a time.
[link removed]

A: I had a similar error while using IE7 and IE8 on a website I developed a while ago.
The problem was related with using position:relative; on an element. I know this is a long shot actually and probably not related, but it might give you a starting point.
Best thing to do, to know what might be wrong, is cloning the website to a local or offsite location and start chopping code. IE8 is not that good when it comes to debugging and might point you a code line completely unrelated to the actual error.
As soon as you find the code portion responsable for the error it's just a matter of time until you can find the actual culprit.

A: Narrowed down the answer:
wp_enqueue_script() was not being used to include jQuery in the WordPress header file.  Instead, jQuery was being included manually.  Then, when a lightbox WordPress plugin needed jQuery, since enqueue had not been used, it created a second script include for jQuery.  This was apparently too difficult for IE to handle.
Anyway, removing the second script include for jQuery fixed the problem on my local machine.  So, I'll assume that's the answer.


text:
Q: Как присвоить умному указателю новое значение int* ptr_1 = new int(10);
int* ptr_2 = new int(20);
std::unique_ptr<int> u_1 (ptr_1);

Можно ли сделать так, чтобы u_1 указывал на ptr_2, не затирая данные в ptr_1.
При использовании u_1.reset(ptr_2) в ptr_1 затираются данные

A:
Можно ли сделать так, чтобы u_1 указывал на ptr_2, не затирая данные в ptr_1.

int* old_ptr = u_1.release();
u_1.reset(ptr_2);

см. std::unique_ptr<>::release


text:
Q: iOS data stays the same after switching view controllers Im making an app that basically just tracks your speed and elevation and plays a song. It uses storyboards. It has multiple view controllers. If I am currently tracking the data on the app and playing a song, and then switch to another view, when I switch back everything is messed up. It is no longer tracking, and the music controls are all messed up. How do I switch view controllers without changing what is taking place on the view that I am switching from?

A: configure your view contents in
-(void)viewDidLoad
dont use
viewWillAppear or
ViewDidAppear
unless its mandatory


text:
Q: How am I able to pass a variable over to a button click event? I passed a variable from one page to another for a pop up menu. I want to be able to add the selected adviser to the favorites list. The issue is, when I pass the variable to one page, it only allows me to use it for that specific method. I am trying to get it passed to a Button Click event,(OkayButtonClicked), so it will be saved to the favorites list. I have tried two different attacks to this.
I have tried:
Declaring the button, using FindByName from the xaml code x:Name property.
Button okaybutton = FindByName("OkayButton") as Button;
Then I tried two different ways of using this variable to pass the string.
One way was:
okaybutton += (sender2, e2) => OkayButtonClicked(sender2, e2, selectedAdvisor);

The second way was:
okaybutton += delegate(object sender, EventArgs e)
{
   OkayButtonClicked(sender, e, selectedAdvisor);
};

(selectedAdvisor is the variable that was passed from one page to the current one I am on, which is where the problem is occurring)
There is one error, each, that I get with these.
First One:
"Operator '+=' cannot be applied to operands of type "Button" and "lambda expression"
Second One:
"Operator '+=' cannot be applied to operands of type "Button" and "anonymous expression"
(The Button click event that I am trying to get the variable passed to)
private void OkayButtonClicked(object sender, EventArgs e)
{

    PopupNavigation.Instance.PopAsync();

    DisplayAlert("Attention", "You have successfully added Adviser to said List", "Okay");
}

A: you constructor for FavoriteButtonPopupView probably looks something like this
public FavoriteButtonPopupView(string selectedAdvisor)
{
  ...
}

the selectedAdvisor variable you pass is locally scoped - meaning it is only visible within the constructor, and other methods on that page can't access it.
What you need to do is create a class level variable that will be visible to all methods of the class.
private string SelectedAdvisor;

public FavoriteButtonPopupView(string selectedAdvisor)
{
  // store the parameter in a class level variable so other methods can access it
  SelectedAdvisor = selectedAdvisor;

  ...
}

private void OkayButtonClicked(object sender, EventArgs e)
{

    // do something with SelectedAdvisor here

    PopupNavigation.Instance.PopAsync();

    DisplayAlert("Attention", "You have successfully added Adviser to said List", "Okay");
}

note - this is basic C# and has nothing specific to do with Xamarin

A: Instead of okayButton += you need to use okayButton.Click += event.
Your code should be like
okaybutton.Click += delegate(object sender, EventArgs e)
{
 .....
};
You can only use += with an event or delegate in c#. You can't use += operator with a button instance
Hope this helps


text:
Q: passing json reply from webservice to variables i'm posting some data to a web service and i'm getting a json reply which i want to pass to a jsonobject.
The reply of the web service is:
{
    "ValidateLoginResult": [
        {
            "ErrorMessage": "Wrong username pass",
            "PropertyName": null
        }
    ]
}

and i want to pass the error message and the property name to variables. I tried using JSONobject and JSONarray but didnt have any luck
                HttpClient httpclient = new DefaultHttpClient();

                // 2. make POST request to the given URL
                HttpPost httpPost = new HttpPost(serverURL);
                StringEntity se = new StringEntity(data);
                httpPost.setEntity(se);

                // 7. Set some headers to inform server about the type of the content
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-type", "application/json");

                // 8. Execute POST request to the given URL
                HttpResponse httpResponse = httpclient.execute(httpPost);
                // 9. Getting Reply
                inputStream = httpResponse.getEntity().getContent();
                ...
                ...
                 JSONArray json = new JSONArray(convertInputStreamToString(inputStream));

                JSONObject json_LL = json.getJSONObject(0);

                String str_value=json_LL.getString("ErrorMessage");

A: You are getting response in JSONObject and you are trying to get it in JSONArray.. thats why you are getting error..
Try this way...
try {
    JSONObject result = new JSONObject(response);

    if(data.has("ValidateLoginResult"){
        JSONArray array = result.getJSONArray("ValidateLoginResult");

        for (int i = 0; i < array.length(); i++) {
        JSONObject obj = array.getJSONObject(i);
            String ErrorMessage= ""+obj.getString("ErrorMessage");
            String PropertyName= ""+obj.getString("PropertyName");
        }
    }

} catch (JSONException e) {
    e.printStackTrace();
}

OR
if you want one line answer..Try this..
// going directly to array object..
JSONObject result = new JSONObject(response).getJSONArray("ValidateLoginResult").getJSONObject(0);

String ErrorMessage= ""+result.getString("ErrorMessage");
String PropertyName= ""+result.getString("PropertyName");


text:
Q: OpenID Connect - how to handle single logout I'm investigating the use of OpenID connect as the SSO protocol for our enterprise applications (that are consumer facing).  In general most aspects of it align with our needs, except for its ability to handle single logout and am hoping for some guidance on this.
I've had a chance to review the latest OIDC session management spec, as well as several stack overflow questions that touched upon similar themes:

*

*OpenID Connect will eventually replace saml...

*single sign off using oauth2
As the person from ping mentioned, single logout is handled differently from SAML2 in that it is more user centric.  That's all good but it still doesn't feel like fitting the needs of actual single logout.  Specifically, the user-centric handling (through somewhat kludgy iframe communication) only works for the current browser view, but wouldn't apply to an RP that isn't currently being viewed.
For example, the user logs into RPs A, B, and C using a specific OP. Single logout would only trigger logout for those RPs that a browser is viewing; that would leave those other sessions lingering, which can be a security issue.  (please correct if I've mis-analyzed this though).
I've seen some solutions that work outside of the protocol (e.g. parent domain cookie, or possibly (??) the same session store) but those unfortunately would not fit my needs.
I'm trying to see if I may have missed something about the OIDC spec which suggests a single logout protocol covering use cases similar to SAML2's own single logout?  (maybe some direct OP->RP communication?  or even a client-side "iterate-through-RP" logout?).  Or am I really left on my own to develop a proprietary solution for it?
BTW, would also be curious as to whether this has been discussed in the OIDC committee (am sure it has), and whether it is on the roadmap to be addressed.
Thanks in advance for the help!

A: What kind of solution do you expect?
SLO will work fine if you use OIDC for protection of your resources (you will check access_token on access to resources anyway, which will be revoked) but not in case when OIDC used as an Identity Provider.
OIDC has no push-SLO. You cannot implement a reliable SLO within the OP by the means of OIDC.
At the moment each RP should take care of SLO, which is specified in OIDC Session Management spec mentioned by you. If RPs are out of your control, you have no means to enforce it.

A: You mentioned 'some direct OP->RP communication' ; that's exactly what the Back-Channel Logout mechanism does.
Each client registered at the OP includes the backchannel_logout_uri; when the user logs out of the OP, the OP uses an http POST to this URI at every signed-in RP to tell them to log the user out.
Because this goes to the client system's back-end, it will work even if the user doesn't have a browser session with the client system's front-end active.

A: There is no official solution for this, and as Vilmantas has correctly pointed out in his answer:

If RPs are out of your control, you have no means to enforce it.

Anyway, there still is an option, although this may contradict the use of OpenID Connect, but anyway, here we go:
Use a token revocation list.
When the user signs out, put the token on a revocation list at the identity provider. Then you need a mechanism to push (or regularly pull) this revocation list to all the relying partys' backends. Then, when the user tries to access a relying party (and they still have their token), although the token is basically still valid, the relying party can reject it because it had been revoked meanwhile.
Of course this means that you need some kind of ideally-real-time-update for the revocation lists, and this might render the entire idea of OpenID Connect useless. But it's an option…

A: If your OAuth server issues refresh tokens, and it implements RFC 7009 then you can use that endpoint to revoke the refresh token, and prevent it from being used to issue any new access tokens.
We use this successfully in a scenario with a long (12 hour) refresh token and short (5 minutes access token). And for good measure the OAuth server also marks sessions as idle (essentially a revoke) when no new access token has been requested within a certain period (30 minutes).


text:
Q: Routing on button click in angular 5 I need to route to a home component when the user clicks a button. I know how to do that using: , but not using: routerLink. Is there any way to do that using a button click event?
home

The code above is how I use an  tag to route.

A: Yes, routerLink works on both anchor tags and button tags. You can do this:
<button class="nav-item nav-link-edit" [routerLink]="['']">home</button >

A: routerLink will be working properly.
app.component.html:
<button class="nav-item nav-link-edit" [routerLink]="['Home']">Home</button >


text:
Q: Magic Zoom Plus breaks scroll on touch and mobile devices I've just added Magic Zoom Plus to a page and it's working as expected on desktop.
However, when viewing on a mobile or touch screen device, you can't scroll/drag past the image, so if your image takes up most of the screen, it makes it very difficult to scroll past it.
I've checked their integration docs but can't find anything which talks about allowing dragging/scrolling on touch/mobile devices.
Does anyone know of a way to fix this or a way around it?

UPDATE - 26/08/2015
I realised the version I was supplied with was an older version and updating to a newer version (v4.5.41) fixed my issue.

A: Either enable the click-to-activate setting:
https://www.magictoolbox.com/magiczoomplus/integration/#activate
Or better, wait 2 weeks until 8 September 2015 when Magic Zoom Plus v5.0 will be released. One of the improvements in version 5.0 is native support for dragging the page through the image.


text:
Q: Why is it said that Class adapter pattern is not possible in Java? I have seen mentioned at several places that class adapter pattern cannot be done in Java (including Head First: Design pattern and Implementing Class Adapter Pattern in Java on SO). I cannot understand why.
Consider the following adaptee, target interface and adapter code:
Object to be adapted (adaptee)
class Adaptee{

   int id = 123;

   void doStuff(){
     /* Doing stuff */
   }

   int getId(){
       return id;
   }

}

Target interface
interface TheNewInterface{

     void doAction();

     int getId();
}

Object adapter
class ObjectAdapter implements TheNewInterface{
    Adaptee adaptee;

    ObjectAdapter(Adaptee adaptee){
        this.adaptee = adaptee;
    }

    @Override
    void doAction(){
         adaptee.doStuff();
    }

    @Override
    int getId(){
         adaptee.getId();
    }

}

Class adapter (??)
class ClassAdapter extends Adaptee implements TheNewInterface{

    @Override
    void doAction(){
         doStuff();
    }

    /**No need to provide an implementation of getId() as super class has it implemented*/
}

Why is it said that class adapter is not possible in Java?
The reason for this is mentioned that Java does not supported multiple inheritance.
But per definition the ClassAdapter class is exactly that - conforms to the new interface & at the same time IS of adaptee type.

A: The Class Adapter pattern is possible in Java. Resources:

*

*http://en.wikipedia.org/wiki/Adapter_pattern#Class_Adapter_pattern (has a Java example)

*Implementing Class Adapter Pattern in Java

*Use for the adapter pattern in Java

*https://www.google.com/search?q=adapter+pattern+java

*http://sourcemaking.com/design_patterns/adapter/java/1
Here's a question I asked exactly on this subject: How to wrap a java.lang.Appendable into a java.io.Writer?
The answer of which is a Class Adapter.


text:
Q: `puma:restart' invoke twice but i only call it once on my deploy app via Capistrano? I tried to deploy Rails app to the server via Capistrano.
This is my code on deploy.rb
set :repo_url,        'git@bitbucket.org:varisdaOfficial/insurance_site.git'
set :application,     'insurance_code'
set :user,            'deploy'
set :puma_threads,    [4, 16]
set :puma_workers,    0

set :pty,             true
set :use_sudo,        false
set :stage,           :production
set :deploy_via,      :remote_cache
set :deploy_to,       "/home/#{fetch(:user)}/apps/#{fetch(:application)}"
set :puma_bind,       "unix://#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.error.log"
set :puma_error_log,  "#{release_path}/log/puma.access.log"
set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true  # Change to false when not using ActiveRecord
set :linked_dirs, %w(public/uploads)

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end

namespace :deploy do
  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      unless `git rev-parse HEAD` == `git rev-parse origin/master`
        puts "WARNING: HEAD is not the same as origin/master"
        puts "Run `git push` to sync changes."
        exit
      end
    end
  end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  desc 'Restart application'
  task :restart do
    on roles(:app), in: :sequence, wait: 5 do
      invoke 'puma:restart'
    end
  end

  desc 'clear temp cache'
  task :clear_cache do
    on roles(:app) , in: :sequence, wait: 1 do
      execute "rm -rf #{shared_path}/tmp/cache/[^.]*"

    end
  end

  before :starting,     :check_revision
  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :clear_cache
  after  :finishing,    :restart
end

So when i ran 'cap production deploy' everything work smoothly my site can be deployed successfully but i got a message after that.
Capistrano tasks may only be invoked once. Since task `puma:restart' was previously invoked,
invoke("puma:restart") at/Users/manjarb/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/capistrano3-puma-1.2.1/lib/capistrano/tasks/puma.rake:134 will be skipped.
If you really meant to run this task again, first call Rake::Task["puma:restart"].reenable
THIS BEHAVIOR MAY CHANGE IN A FUTURE VERSION OF CAPISTRANO. Please join the conversation here if this affects you.
https://github.com/capistrano/capistrano/issues/1686

I just only call restart task once.
So how can i fixed this message?
Thanks!

A: I assume you are using the capistrano3-puma gem. That gem automatically restarts puma for you at the conclusion of a successful deployment. So that is the first time the restart task is being called.
Additionally, in your deploy.rb, you've defined your own custom restart task, and you are invoking it after :finishing. That is the source of the second invocation, and thus the warning.
To "fix" this problem, remove the redundant task:
desc 'Restart application'
task :restart do
  on roles(:app), in: :sequence, wait: 5 do
    invoke 'puma:restart'
  end
end

And remove this:
after  :finishing,    :restart


text:
Q: Adding MVC4 Display Modes Dynamically In Global.asax, I want to add a number of display modes dynamically, based on a string array I have, thus:
foreach (string displayModeId in myDisplayModeIds)
{
    modes.Insert(0, new DefaultDisplayMode(displayModeId)
        {
            ContextCondition = context =>
                context.Request["DisplayMode"] == displayModeId
        }
    );
}

Of course this doesn't work, because displayModeId needs to be a constant within the scope of the ContextCondition.
Any help appreciated.

A: You could capture it in a closure so that it doesn't run away from you in the loop:
foreach (string displayModeId in myDisplayModeIds)
{
    string dmId = displayModeId;
    modes.Insert(0, new DefaultDisplayMode(displayModeId)
    {
        ContextCondition = context => context.Request["DisplayMode"] == dmId
    });
}


text:
Q: allow touch control up and down in aframe touch control in aframe scene works only in the left and right, it does not work up and down using a mobile
however using the desktop it works perfectly
when I added touch control, look control is removed
how to add both of them at the same time

A: I wanted the same thing on mobile. Add this code after you load the aFrame library:
AFRAME.components["look-controls"].Component.prototype.onTouchMove = function (t) {
                        var PI_2 = Math.PI/2,
                        e,
                        o = this.el.sceneEl.canvas,
                        i = this.yawObject,
                        j = this.pitchObject;
                        this.touchStarted && this.data.touchEnabled && (e = 2 * Math.PI * (t.touches[0].pageX - this.touchStart.x) / o.clientWidth, f = 2 * Math.PI * (t.touches[0].pageY - this.touchStart.y) / o.clientHeight, j.rotation.x += .3 * f, i.rotation.y += .5 * e, j.rotation.x = Math.max(-PI_2, Math.min(PI_2, j.rotation.x)), this.touchStart = {
                                x: t.touches[0].pageX,
                                y: t.touches[0].pageY
                            })
                        }

Or, alternatively, you can find the code for "look-controls" in the aframe.min.js(or whichever file you use) and modify onTouchMove function there.

A: I took the answer from 'Igor R' and cleaned it a little bit up.
AFRAME.components["look-controls"].Component.prototype.onTouchMove = function (t) {
    if (this.touchStarted && this.data.touchEnabled) {
        this.pitchObject.rotation.x += .6 * Math.PI * (t.touches[0].pageY - this.touchStart.y) / this.el.sceneEl.canvas.clientHeight;
        this.yawObject.rotation.y += /*  */ Math.PI * (t.touches[0].pageX - this.touchStart.x) / this.el.sceneEl.canvas.clientWidth;
        this.pitchObject.rotation.x = Math.max(Math.PI / -2, Math.min(Math.PI / 2, this.pitchObject.rotation.x));
        this.touchStart = {
            x: t.touches[0].pageX,
            y: t.touches[0].pageY
        }
    }
}

A: Please specify if you are using an iOS device or an Android. Steps to follow:

*

*On iOS 12.2 it is a known issue as Apple has disabled deviceorientation and device motion in Safari.  Tried to manually enable it but still doesn't work.  Installed Chrome and cardboard-vr files but no fruitful results.

*On Android, install google cardboard, if you don't have it.  Update the version of the Aframe, make sure you are on A-Frame 0.9.2.