text:
Q: UI not update (have to click somewhere) & router not work in Angular2-Meteor I cannot update the UI immediately after subscribing the data from database, I have to click somewhere
Also if I use the router to go to another page, it does not work
@Component({
  selector: 'foo-component',
  template: `
    {{foo}}
  `
})
export class FooComponent extends MeteorComponent {
  foo: string ;

  constructor() {
    super();

    this.subscribe('messages', () => {
      // I cannot change foo value immediately, I have to click somewhere
      this.foo = 'foo';

      // Also if I use the router to go to another page, it does not work
      // this.router.navigate(['Home']);
    });
  }
}

How to solve this?

A:
Note the new angular2-meteor version  autoBind is set to true by default. So you probably won't meet this issue again.
But you still need use NgZone in Accounts.changePassword or other similar Accounts.foo() functions.

This problem is because that part of code run out of Angular 2 zone, you need run it inside of zone to update UI immediately or use router to go to another page.
Where do these problems usually happen?
Most time you don't do this. So when do you need this? Usually in callback of Meteor functions:
   this.autorun(() => {
     // here you need
   });

   this.subscribe('messages', () => {
     // here you need
   });

   this.call('newMessage', (error, result) => {
     // here you need
   });

   Accounts.changePassword(currentPassword, newPassword, error => {
     // here you need
   });

How to solve?
Take
 this.call('newMessage', (error, result) => {
   this.router.navigate(['Home']);
 });

for example, you need change to:
import { NgZone } from '@angular/core';

constructor(private zone: NgZone) {}

this.call('newMessage', (error, result) => {
  this.zone.run(() => {
    this.router.navigate(['Home']);
  });
});

Is there a clean way?
Luckily, Angular2-Meteor helps you do this dirty work.
Check Angular2-Meteor API document, there is an autoBind parameter for this.subscribe and this.autorun.
So now you don't need use this.zone.run, instead you can just add a true:
   this.autorun(() => {
     // your code
   }, true);

   this.subscribe('messages', () => {
     // your code
   }, true);


text:
Q: Using "set /p" in C++ I'm trying to set a windows command line environment variable (to help automate starting a windows process requiring user input) and then echo it back via system().
#include <iostream>
using namespace std;

int main() {
    system("set /p foo= foo=");
    system("echo %foo%");
    system("pause");
    return 0;
}

Upon running, I receive this feedback:

foo=bar
%foo%
Press any key to continue . . .

For the program to work, I need to receive "bar", the content of %foo%, but this is not happening.
What is strange is that the code works if inputted directly into the command line.
C:\Users\JohnDoe>set /p foo= foo=
foo=bar

C:\Users\JohnDoe>echo %foo%
bar

Why does the C++ code not work?
EDIT:
Using the suggested change, as follows:
#include <iostream>
using namespace std;

int main() {
    system("set /p foo=\" Enter foo= \" & echo %foo%");
    system("pause");
    return 0;
}

Returns this feedback:

Enter foo= bar
%foo%
Press any key to continue . . .

Using the following code works, but opens a second window:
#include <iostream>
using namespace std;

int main() {
    system("set /p foo=\" Enter foo= \" & start echo %foo%");
    system("pause");
    return 0;
}

Enter foo= bar
  Press any key to continue . . .

Then in the second window:

bar

A: system runs a new instance of the command interpreter. Setting environment variables in that process has no effect on the program's own process. And unfortunately the C++ standard library has very limited support for environment variables: just a function getenv.
For your purposes, in Windows you might instead issue a call like system( "set foo=bar & run_that_program" );.

A: You can set an environment variable directly in your C program, using the SetEnvironmentVariable function.  (And of course you can prompt the user for the value to set using the usual C I/O functions.)
Such a variable should be inherited by programs you start with system().

redpajama_set_name: RedPajamaStackExchange


text:
Q: I migrated my flutter app to v2 and i get the following errors Hi I upgraded my flutter app to v2 and when I try to launch the app on the ios simulator I get these errors. I followed all the steps like updating cocopods, building the app from xcode, running flutter clean and installing the dependencies again but it didn't work. Any fix?
Failed to build iOS app
Error output from Xcode build:
↳
    objc[31476]: Class RemoteXPCPair is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300708) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fc238). One of the two will be used. Which one is undefined.
    objc[31476]: Class RemoteXPCShim is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300780) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fc2b0). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury11XPCEndpoint is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300e58) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fc920). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury15XPCPeerEndpoint is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300ef8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fc9c0). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury19XPCListenerEndpoint is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300f98) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fca60). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury16XPCObjectEncoder is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e3010a8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fcb70). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury17_XPCObjectEncoder is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301150) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fcc18). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury16XPCObjectDecoder is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301200) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fccc8). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury17_XPCObjectDecoder is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e3012a8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fcd70). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury14XPCSideChannel is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e3015e8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd0b8). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury19RemoteDeviceBrowser is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301730) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd208). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury17XPCFileDescriptor is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e3018b0) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd388). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury12RemoteDevice is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301b00) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd5d0). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury13XPCConnection is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301d20) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd820). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury19RemoteXPCConnection is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e301ee8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fd9e0). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury27RemoteXPCListenerConnection is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e302040) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fdb30). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury23RemoteXPCPeerConnection is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e3021e8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fdcd0). One of the two will be used. Which one is undefined.
     objc[31476]: Class _TtC7Mercury23SystemXPCPeerConnection is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e302d50) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fe830). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7Mercury15XPCFileTransfer is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e302fa8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fea70). One of the two will be used. Which one is undefined.
    objc[31476]: Class _TtC7MercuryP33_2B1830E49151A2D290BADAC81D16B73411_HandlerBox is implemented in both /Library/Developer/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x10e300ae8) and /Library/Apple/System/Library/PrivateFrameworks/Mercury.framework/Versions/A/Mercury (0x1208fc618). One of the two will be used. Which one is undefined.
    ** BUILD FAILED **

Xcode's output:
↳
    Writing result bundle at path:
        /var/folders/_5/9gsv46w9015004z68y2t9vrm0000gn/T/flutter_tools.MStc2D/flutter_ios_build_temp_dirxDM7ou/temporary_xcresult_bundle

    /Users/josh/Documents/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_local_notifications-1.5.0+1/ios/Classes/FlutterLocalNotificationsPlugin.m:17:5: warning: 'UILocalNotification' is deprecated: first deprecated in iOS 10.0 - Use UserNotifications Framework's UNNotificationRequest [-Wdeprecated-declarations]
        UILocalNotification *_launchNotification;
        ^
    In module 'UIKit' imported from /Users/josh/StudioProjects/promise_of_the_day/ios/Pods/Target Support Files/flutter_local_notifications/flutter_local_notifications-prefix.pch:2:
    /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator15.2.sdk/System/Library/Frameworks/UIKit.framework/Headers/UILocalNotification.h:18:12: note: 'UILocalNotification' has been explicitly marked deprecated here
    @interface UILocalNotification : NSObject<NSCopying, NSCoding>


text:
Q: Javascript - How would you regex this pattern. Can't seem to do it
Possible Duplicate:
Get query string values in JavaScript

I "had" this pattern but it didn't quite give me what I need, though it worked.
var regex = new RegExp('\\b' + data.keyword + '(=[^&]*)?(&|$)',"gi");

But the following regular expressions "is" what I need but i can't seem to get it to work within the regex obj:
/&dyanmicTxtHere(\=[^&])?(?=&|$)|^dyanmicTxtHere(\=[^&])?(&|$)/
I tried: This is NOT working -
var regex = new RegExp('&' + data.keyword + '(=[^&]*)?|^' + data.keyword + '(=[^&]*)?&?',"gi");

I can't figure out why. So the above regex should strip out my passed param (and vlaue)(data.keyword), and deal with the ? and & wherever that param sits in the url. It
So, what would this match?
www.someurl.com?Keyword=foo
www.someurl.com?up=down&Keyword=foo
www.somurl.com?up=down&keyword=foo&left=right
etc... so, if I passed in "Keyword" as my dynamic param, then it would remove it and its associated value.

A: Looks to me that what you want is to read parameter values from a request, via JavaScript, correct?
Try using this:
function getParameterByName(name)
{
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(window.location.search);
    if(results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
}

Taken from this question.

A: If you need to see what the produced regex looks like, simply call regex.toString()
If you do that on the one you tried you get:
/&dyanmicTxtHere(=[^&]*)?|^dyanmicTxtHere(=[^&]*)?&?/gi

Based on that, you can fairly see what needs changing to make it like the regex you provided:
var regex = new RegExp('&' + data.keyword + '(\\=[^&])?(?=&|$)|^' + data.keyword + '(\\=[^&])?(&|$)', '');

If we call toString on that we get:
/&dyanmicTxtHere(\=[^&])?(?=&|$)|^dyanmicTxtHere(\=[^&])?(&|$)/

If that doesn't work, try explaining exactly what you're trying to parse.

A: Obviously what follows is not a regular expression; but it should, I think, fulfil your requirements. It takes advantage of the requirements of name-value pairs in a GET query-string, and uses simple string, and some array, manipulation to examine the various (if any) name-value pairs from the passed URL:
function removeParam(url, param) {
    // checks for the existence of a '?' in the passed url:
    var queryAt = url.indexOf('?') + 1;
    /* function exits if:
       1. no 'url' parameter was passed,
       2. no 'param' parameter was passed in, or
       3. the 'queryAt' variable is false, or has a falsey value */
    if ((!url || !param) || !queryAt) {
        return false;
    }
    else {
        /* if the 'param' passed in wasn't found in the 'url' variable,
           the function exits, returning the original url (as no modification
           is required */
        if (url.indexOf(param) == -1) {
            return url;
        }
        else {
                /* gets the substring of the url from the first
                   character *after* the '?' */
            var all = url.substring(queryAt),
                // creates an array of the name and value pairs
                nameValues = all.split('&'),
                // creating a new array
                newNameValues = [],
                parts;
            // iterates through each name-value pair
            for (var i = 0, len = nameValues.length; i < len; i++) {
                // splits the name-value pair into two parts
                parts = nameValues[i].split('=');
                /* if the first part (the 'name' of the param) does not
                   matches what you're looking for then the whole name-value
                   pair is pushed into the 'newNameValues' array */
                if (parts[0] !== param) {
                    newNameValues.push(nameValues[i]);
                }
            }
            // returns the reconstructed URL
            return url.substring(0, queryAt) + newNameValues.join('&');
        }
    }
}

JS Fiddle demo.


text:
Q: Can't get Grub to handle booting, Windows boot manager keeps taking control I have Windows 8 and Liunx Mint installed and can only boot to Mint by overriding the boot order through the UEFI.
I'm using an HP laptop that has a garbage firmware interface so I can't set it to boot by a specific OS on startup, only when I'm doing an override at boot. That at least would give me a temporary fix.
I've disabled secure boot, turned off fast boot, ran boot repair, and used BCDedit to change the Windows boot device to grub64.efi. Also tried shimx64.efi. I set Grub to boot Mint by default as well.
Can't find any other suggestions through Google. Any ideas?

A: This issue seems built into the HP UEFI/BIOS - it will only accept a /Microsoft folder for boot. Having had this issue on a HP laptop, and having tried a number of fixes, I finally just replaced the Windows boot EFI file with the Linux version:

*

*Make an image of the HDD lest something go wrong.

*Move the MS boot file, /boot/efi/EFI/Microsoft/Boot/bootmgfw.efi, to an new folder, e.g. /boot/efi/EFI/old-Microsoft/Boot/bootmgfw.efi

*Copy the contents of /boot/efi/EFI/ubuntu/shimx64.efi (or grubx64.efi) to /boot/efi/EFI/Microsoft/Boot/.

*Rename shimx64.efi (or grubx64.efi) to bootmgfw.efi.

*Change the path for the Windows UEFI bootmgfw.efi entry in grub to the location of the MS boot file, e.g. /boot/efi/EFI/old-Microsoft/Boot/bootmgfw.efi. [Thanks to @BrainRenticus for reminding me of this essential step!]

This should now consistently boot to the grub menu (though I got rid of dual boot, since Ubuntu was so much faster on the laptop).
Assuming you did not disable Secure Boot permanently (e.g. by installing third-party drivers), you can revert that and other UEFI settings. BTW, you might want a hard copy of this procedure -- Windows updates frequently mess with the boot loader (another reason I dropped Windows).


text:
Q: check if office is installed in 64 bit Win OS using registry I trying to check if office is installed using registry. I am able to verify for 32 bit OS using the following regkey
"..HKLM\SOFTWARE\Microsoft\Office\14.0\Common\InstallRoot" + "Path"
But how do i check when using a 64 bit OS? This key does not exist on a 64 bit OS for either 32 or 64 bit Office. (Checked on both Win7 & Win 8)

A: I finally tracked down the answer I was looking for. This forum thread has an answer that suggests some registry keys to try.

A: As said here , the registry key needs to be checked in WOW6432Node.
So your path would be something like :

HKLM\SOFTWARE\Wow6432Node\Microsoft\Office\14.0\Common\InstallRoot


text:
Q: WPF DataGrid - Implementing Combobox column that is editable and filters list based on text inside Please bear with me as I am still new to MVVM and WPF C# (and programming in general). I have read alot and feel overwhelmed and just need some guidance to overcome this issue. I will try to simplify my program into a simple example illustrated below:
A supermarket has the following items available:

*

*Apple

*Peach

*Mango

*Banana

*Toilet paper

*Iphone

*Water

I have several customers (customer objects). Each customer object contains a collection of his items. The items object contains the name and quantity. For example:
Customer X has the following items in his cart
Item                      Quantity

*

*Apple                        1

*Banana                       2

*Peaches                      3

So my simplified application is as follows. I open the application and it has a listview with a list of my current customers. I press on a customer and modify it. This will open a new window. The window contains a datagrid. Column one is the item in his cart (combobox column), column two is a text column with the quantity.
I want to be able to modify the item and quantity. My issue is the combobox column; I want it to be editable and allow me to filter the drop down list based on the current input in that cell. For example if I press it on and I dont enter anything, it will have the full list of available items. if I press "a" it will filter the drop down further for all words starting with an "a". I also want to implement validation so that the combobox column doesnt allow for any duplicates (I will probably be able to figure this out alone).
Here is some code I have implemented quickly for this example (MVVM structure). This code skips the first window and goes straight into the window with the datagrid
My Models
Customer.cs
public class Customer:INotifyPropertyChanged
{
    private string name;

    public ObservableCollection<Item> Items { get; set; }

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public Customer()
    {

    }
    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyRaised(string propertyname)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
        }
    }

}

Item.cs
    public class Item : INotifyPropertyChanged
{
    private string name;
    private double quantity;

    public string Name
    {
        get
        {
            return name;
        }
        set
        {
            name = value;
        }
    }

    public double Quantity
    {
        get
        {
            return quantity;
        }
        set
        {
            quantity = value;
        }
    }

    public Item()
    {

    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyRaised(string propertyname)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
        }
    }
}

ViewModel
public class MainWindowViewModel
{
    public Customer ObjCustomer
    {
        get; set;
    }

    private ObservableCollection<object> itemslist;
    public ObservableCollection<object> ItemsList
    {
        get { return itemslist; }
        set { itemslist = value; }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyRaised(string propertyname)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyname));
        }
    }

    public MainWindowViewModel()
    {
        ObjCustomer = new Customer();
        ObjCustomer.Items = LoadCustomerItems();
        ItemsList = LoadAvailableItems();
    }

    private ObservableCollection<object> LoadAvailableItems()
    {
        ObservableCollection<object> combosAndLoadCasesList = new ObservableCollection<object>();

        combosAndLoadCasesList.Add(new Item() { Name = "Apple" });
        combosAndLoadCasesList.Add(new Item() { Name = "Peach" });
        combosAndLoadCasesList.Add(new Item() { Name = "Mango" });
        combosAndLoadCasesList.Add(new Item() { Name = "Banana" });
        combosAndLoadCasesList.Add(new Item() { Name = "Toilet paper" });
        combosAndLoadCasesList.Add(new Item() { Name = "Iphone" });
        combosAndLoadCasesList.Add(new Item() { Name = "Water" });

        return combosAndLoadCasesList;
    }
    private ObservableCollection<Item> LoadCustomerItems()
    {
        ObservableCollection<Item> ItemsForCustomer =  new ObservableCollection<Item>();
        ItemsForCustomer.Add(new Item() { Name = "Apple", Quantity = 1 });
        ItemsForCustomer.Add(new Item() { Name = "Banana", Quantity = 2 });
        ItemsForCustomer.Add(new Item() { Name = "Peaches", Quantity = 3 });
        return ItemsForCustomer;
    }
}

My window xaml
<Window x:Class="ComboBoxDemo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:ComboBoxDemo"
    xmlns:Syncfusion="http://schemas.syncfusion.com/wpf"
    xmlns:i = "http://schemas.microsoft.com/expression/2010/interactivity"
    mc:Ignorable="d"
    Title="MainWindow" Height="500" Width="500">
<Window.Resources>
    <local:MainWindowViewModel x:Key="viewModel"/>
</Window.Resources>
<Grid>
    <DataGrid HorizontalAlignment="Left"
              Height="374"
              Margin="37,31,0,64"
              VerticalAlignment="Center"
              Width="391"
              ItemsSource="{Binding ObjCustomer.Items,Source={StaticResource viewModel}}"
              AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridComboBoxColumn Header="Item"
                                    ItemsSource="{Binding ItemsList,Source={StaticResource viewModel}}"
                                    TextBinding="{Binding BindingGroupName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
                                    DisplayMemberPath="Name"/>
            <DataGridTextColumn Header="Quantity"
                                Binding="{Binding Quantity, Mode=TwoWay}"/>
        </DataGrid.Columns>
    </DataGrid>

</Grid>

I have played around with some WPF frameworks such as Syncfusion. Do you guys recommend these going forward or should I stick with the standard WPF functionality? If there any tips for me going forward please advise!

A: Here's a SO page with a couple of answers to your filtered/autocomplete combobox question: Autocomplete combobox for WPF
I notice your set properties are all missing the call to OnPropertyRaised which would make your bindings not work - especially the quantity one. Have a look at https://learn.microsoft.com/en-us/dotnet/desktop/wpf/data/how-to-implement-property-change-notification for how that should work.

I have played around with some WPF frameworks such as Syncfusion. Do you guys recommend these going forward or should I stick with the standard WPF functionality? If there any tips for me going forward please advise!

I personally use Devexpress and absolutely love them, but they also take some time to get used to and learn. Plus they're not cheap.
I also tend to use Prism for MVVM instead of plain WPF since I get lots of stuff out of the box like navigation, auto linking Views to ViewModels and a global event aggregator for passing around events.
You will probably find that every single person has a different opinion about whether to use these libraries or not. I find they help and make me more productive so I would personally recommend using them.
PS: Just wanted to add that if you use a library like devexpress you will mostly get controls like the dropdown autocomplete already built in like this one...


text:
Q: Wrong UninitializedPropertyAccessException in Kotlin after property initialization I have Dagger2 injected property in my presenter.
@Inject lateinit var dataInteractor: DataInteractor

It is accessed in couple of methods. In one of them loadAppointments() everything works fine but in another refund() UninitializedPropertyAccessException is thrown. The code has been working well for a while and this issue has raised the only couple of days ago.
No Kotlin updates were installed before.
import android.util.Log
import co.example.Application
import co.example.domain.model.entity.AppointmentsEntity
import co.example.domain.model.entity.ProvidersEntity
import co.example.interactor.data.DataInteractor
import co.example.domain.di.base.RxDisposablePresenter
import co.example.view.operation.OperationView
import io.reactivex.android.schedulers.AndroidSchedulers
import java.util.*
import javax.inject.Inject

class AppointmentsPresenter : RxDisposablePresenter<AppointmentsPresenter.View>() {
    @Inject
    lateinit var dataInteractor: DataInteractor

    private lateinit var operationView: OperationView<*>

    private val results: ArrayList<AppointmentsEntity.AppointmentEntity> = ArrayList()
    private val resultsHistory: ArrayList<AppointmentsEntity.AppointmentEntity> = ArrayList()

    override fun onTakeView(view: View?) {
        super.onTakeView(view)
        operationView = view?.operationView()!!
    }

    fun loadAppointments() {
        val userID = Application.appComponent.userInternalStorage().userID()
        if (userID != null) {
            add(dataInteractor
                    .getAppointments(userID, LIMIT, OFFSET)
                    .observeOn(AndroidSchedulers.mainThread())
                    .doOnSubscribe { operationView.showProgress() }
                    .doFinally {
                        operationView.hideProgress()
                        view?.onAppointmentsDataFilled(results, resultsHistory)
                    }
                    .subscribe(
                            {
                                divideUpcomingAndCompleteAppointments(it)
                                view?.unblockAppointments()
                            },
                            {
                                val message = it.message
                                if (message!!.contains("blocked")) {
                                    view?.blockAppointments()
                                    operationView.showError("Error")
                                    return@subscribe
                                }
                                operationView.showError(message)

                            }
                    ))
        }
    }

    fun refund(position: Int?) {
        add(dataInteractor
                .refund(results[position!!].id!!)
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe { operationView.showProgress() }
                .doFinally {
                    operationView.hideProgress()
                }
                .subscribe(
                        {
                            view?.onRefundCompleted()
                        },
                        {
                            val message = it.message
                            operationView.showError(message!!)
                        }
                ))
    }

    private fun divideUpcomingAndCompleteAppointments(appointmentsEntity: AppointmentsEntity) {
        results.clear()
        resultsHistory.clear()
        for (appointment in appointmentsEntity.results!!) {
            if (appointment.status.equals(STATUS_COMPLETE, true)) {
                resultsHistory.add(appointment)
            } else {
                results.add(appointment)
            }
        }
    }

    fun loadProviderById(doctorId: Long?, onDoctorRetrivedListener: (ProvidersEntity.ProviderEntity) -> Unit) {
        add(
                dataInteractor
                        .getProviders(0, 100, 0, 0)
                        .observeOn(AndroidSchedulers.mainThread())
                        .subscribe(
                                { providersEntity ->
                                    val doctor = providersEntity
                                            .results
                                            ?.filter {
                                                Log.d("ATAT", "loadProviderById: ${it.user_id}")
                                                it.user_id == doctorId
                                            }
                                    doctor?.let {
                                        if (it.isNotEmpty()) {
                                            onDoctorRetrivedListener.invoke(doctor[0])
                                        }
                                    }
                                },
                                {
                                    val message = it.message
                                    operationView.showError(message!!)
                                }))
    }

    interface View {
        fun operationView(): OperationView<*>
        fun onAppointmentsDataFilled(appointments: ArrayList<AppointmentsEntity.AppointmentEntity>?,
                                     appointmentsHistory: ArrayList<AppointmentsEntity.AppointmentEntity>?)

        fun onRefundCompleted()
        fun blockAppointments()
        fun unblockAppointments()
    }

    companion object {
        const val STATUS_COMPLETE = "Complete"
        const val LIMIT: Long = 1000
        const val OFFSET: Long = 0
    }
}

Here is the stack trace:
2018-12-13 11:59:29.359 4808-4808/co.example E/AndroidRuntime: FATAL EXCEPTION: main
    Process: co.example, PID: 4808
    kotlin.UninitializedPropertyAccessException: lateinit property dataInteractor has not been initialized
        at co.example.presenter.appointements.AppointmentsPresenter.refund(AppointmentsPresenter.kt:59)
        at co.example.view.appointements.AppointmentsFragment.refundRequest(AppointmentsFragment.kt:123)
        at co.example.activity.MainActivity.onRefundRequested(MainActivity.kt:295)
        at co.example.view.dialog.RefundDialogFragment$onCreateDialog$1.onClick(RefundDialogFragment.kt:16)
        at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:172)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)

UPD:
Doesn't reproduce if fragment that calls these methods is created as singleton.


text:
Q: What determines the New Year's reward I get, and (how) can I get them all? According to the Prima guide (which is also amazingly unreliable so far), the New Year's countdown gifts from Isabelle vary. To quote their table,
Gift                    Value    Note

Bell knickknack         2,000    Korea only.
Berliner                  960    Germany only.
New Year's noodles      3,500    Japan only.
Sparkling cider           800    North America (English and French) and France.
Twelve-grape plate        480    North America (Spanish) and Spain.

Is the item you get determined by your region, your language, or something else entirely? For example, if I'm playing the German cartridge but in English, do I get the Berliner, or the sparkling cider?
Given the note about "North America (English)" etc, I would assume that this reward is keyed off the language you're playing the game in. But if that's true, does that mean I can't visit a friend using a different region / language to get their item? (Since my game will still be in English.)
Do the U.K. / other European English speakers get sparkling cider or something else?
The game is also available in Italian and sold in Italy. What reward do Italians/Italian-speakers get?

A: I'm playing acnl in spanish (also the region). The other day i invited some japanese friends to my town and they got the christmas socks. If you want those presents from other region, just find some friends in other countries and ask them to invite you.

A: The gift you get from Isabelle is determined by your region, just like how you get the limited-time items from the post office. Regarding to your second question, if you visit a friend from a different region, you cannot receive that region's New Year's reward, unless your friend manually drops the New Year's reward on the ground. For your third question, the U.K. and all those other countries outside North America get different prizes. As for the fourth question, it certainly cannot be answered by me. I even tried researching it online, and no successful links have showed up. I hope this helped!

A: It all depends on your region,  like the items you get from the post office, the are limited edition according to the events that are happening that month/season. If you go to a pals town you will not receive their new year's gift but if they drop it on the pavement then you can get it that way although I suppose you can change your region on system settings, I am French and I changed my system settings to Spain and I received different gifts, so you could do it that way. :) Hope this helped x


text:
Q: Conditionally mount Windows partition Since I'm using dual-boot (Windows 10 / CentOS 7) I want some files to be shared between the two OS, such as music, photos, etc. So I thought that it would be nice to auto-mount my Windows data-partition during start up.
However, this is not always possible because I needed to hibernate Windows, reboot in Linux to do something and then get back on Windows again.
So, how can I auto-mount this partition during boot, but with the condition that: "if it's been detected as "unclean", mount it read-only"?

A: Create a FUSE helper in /usr/bin that attempts a rw mount and, if that fails, retries with a ro mount. (In case you're not familiar with FUSE, it's a subsystem that allows user code to manage custom filesystems.)
Create the file /usr/bin/windowsfs with the following contents. Make it executable.
#!/bin/bash
mount "$@" || mount "$@" -o ro

Install the fuse package (I'm not sure of the name on CentOS, but it's the one that provides the tools and subsystem to support FUSE filesystems).
Use a line such as this in your /etc/fstab, which declares your Windows partition /dev/sda2 as being of type fuse.windowsfs and to be mounted on /mnt/dsk
/dev/sda2 /mnt/dsk fuse.windowsfs defaults 0 0

When this line is acted upon, it calls the FUSE helper /usr/bin/windowfs to mount the partition. This is our script that attempts a writeable mount but falls back to a read-only mount if necessary.
A standard umount /mnt/dsk operation is sufficient to unmount the partition after use.

A more robust windowsfs script might look like this, where you would get the error message from the "normal" mount if both mounts failed:
#!/bin/bash
#
exec 3>&1
error1=$(mount "$@" 2>&1 1>&3); ss1=$? ss2=0
[[ 0 -lt $ss1 ]] && { error2=$(mount "$@" -o ro 2>&1 1>&3); ss2=$?; }
[[ 0 -lt $ss2 ]] && { error="$error1" ss=$ss1; } || { error="$error2" ss=$ss2; }

[[ 0 -lt $ss ]] && echo "$error" >&2
exit $ss


text:
Q: kirchhoff laws with current source connected in series to resistor I'm struggling with the following circuit trying, using kirchhoff laws, to write equations system that solve all variables.

simulate this circuit – Schematic created using CircuitLab
(Ground symbols are used as arrows to show current direction)
I'm using source convention for sources and the other one for passive.
What I did so far is to define kirchhoff laws for each net clockwise
Voltages
$$Net1(ABD) \Rightarrow V_{ab}-V_4=5$$
$$Net2(ACD) \Rightarrow -V_3+V_5=-5$$
$$Net3(BC) \Rightarrow V_4-V_5-V_6=0$$
Currents
$$Net1(ABD) \Rightarrow I_2-I_3=-10$$
$$Net2(ACD) \Rightarrow I_4-I_6=10$$
$$Net3(BC) \Rightarrow I_3+I_5+I_6=0$$
So now problems come, writing single characteristics:
$$V_{CA}=R_3\cdot I_3$$
$$V_{BD}=R_4\cdot I_4$$
$$V_{CB}=E6-(R_6\cdot I_6) \Rightarrow V_{CB}+(R_6\cdot I_6)=10$$
My problem is: how can I write the characteristic for \$V_{AB}\$??

A: So here is your schematic without all the weird arrows that you added:

simulate this circuit – Schematic created using CircuitLab

First step is to pick a node and call it zero (ground.) You get to do this with exactly one node of any schematic. If I see a node with LOTS of branches ending in it, I often will pick that one as ground as it reduces the number of terms in some of the expressions. But it really doesn't matter in the end.
Given how you assigned node names, I've selected this ground:

simulate this circuit

Second step is to dump \$R_1\$. It serves no purpose. A current source has infinite impedance and any finite resistance in series with it is entirely irrelevant. The only purpose it serves is to change the current source's compliance voltage (the change of which of course is immediately dropped by the change in the resistance.)
So just dump it.

simulate this circuit

Third step is to label the remaining nodes.
I followed your guidance there:

simulate this circuit
Given that we've both arrived at the same number of nodes, I suspect you already have the skills to apply what I did above. So that's good.

Now, as the fourth step, just write out equations for each of the labeled nodes:
$$\begin{align*}
\frac{V_A}{R_3} &= \frac{V_C}{R_3} + I_{E_2} + I_{A_1}\tag{$V_A$}\\\\
\frac{V_B}{R_4} + \frac{V_B}{R_6} + I_{A_1} &= \frac{V_D}{R_4} + \frac{0\:\textrm{V}}{R_6}\tag{$V_B$}\\\\
\frac{V_C}{R_3} + \frac{V_C}{R_5} &= \frac{V_A}{R_3} + \frac{V_D}{R_5} + I_{E_6}\tag{$V_C$}\\\\
\frac{V_D}{R_4} + \frac{V_D}{R_5} + I_{E_2} &= \frac{V_B}{R_4} + \frac{V_C}{R_5}\tag{$V_D$}
\end{align*}$$
This is done by keeping all the outgoing currents on the left side and all of the incoming currents on the right side. Let's discuss this jonk's modified nodal method that you will not often see, but is really a whole lot easier to keep track of.

For each node, "imagine" that you are sitting in the middle of the
  node (which is like a flat, small, square floor sitting at some
  elevation you don't yet know on a long pole from "down there
  somewhere.") Water is spilling from above onto your floor. You don't
  know from how high, but you can tell it's spilling down onto your
  floor. Also, the water that hits your small floor now flows off the
  edges and spills down onto other floors below yours. You don't know
  where those are at, either. But you know they must be there. (The
  "water" is current, the heights of these small floors/nodes is the
  voltage of the floor/node.)
So the left side represents the currents spilling away and off the
  edges of your floor and onto other nearby floors. And the right side
  represents the currents spilling inward and onto your floor from other
  nearby floors.
(In keeping with this mental model, you can imagine that current and
  voltage sources may be like conveyors that may move water back upward to
  higher floors, so to speak. Also, no water is ever lost and all of it
  remains in play and the water cannot accumulate on the floors -- the net
  flow onto a floor must equal the net flow off of it -- KCL! -- and hence
  the justification for setting the left side equal to the right side.)

I've chosen a "direction" for \$I_{E_2}\$ and \$I_{E_6}\$, made evident by whether I placed that current on the left or right side of an equation. The only rule is that I am consistent about it. Here, I've decided that the current flows out of the (+) terminal of a voltage source.
Now, it's at this point that it would appear that there are six unknowns, \$V_A\$, \$V_B\$, \$V_C\$, \$V_D\$, \$I_{E_2}\$, and \$I_{E_6}\$, and only four equations. One way to resolve this is to have used so-called "supernodes" in the above equation development. But that just introduces another bit of terminology I'd like to avoid here. So let's stick with the above equations.
What else do we know? How about the fact that \$V_A=V_D+V_{E_2}\$ and that \$V_C=V_{E_6}\$? Nice. Now we have six unknowns and six equations. So this works out. We can either substitute in these two equations into the other four, reducing the number of variables to four, or we can keep six unknowns and pile on these two added equations. How you approach this is up to you. But let's perform the substitutions since it yields fewer equations and it's easy to do without much chance for misunderstanding:
$$\begin{align*}
\frac{V_D+V_{E_2}}{R_3} &= \frac{V_{E_6}}{R_3} + I_{E_2} + I_{A_1}\tag{$V_A$}\\\\
\frac{V_B}{R_4} + \frac{V_B}{R_6} + I_{A_1} &= \frac{V_D}{R_4}\tag{$V_B$}\\\\
\frac{V_{E_6}}{R_3} + \frac{V_{E_6}}{R_5} &= \frac{V_D+V_{E_2}}{R_3} + \frac{V_D}{R_5} + I_{E_6}\tag{$V_C$}\\\\
\frac{V_D}{R_4} + \frac{V_D}{R_5} + I_{E_2} &= \frac{V_B}{R_4} + \frac{V_{E_6}}{R_5}\tag{$V_D$}
\end{align*}$$
Now the unknowns are just \$V_B\$, \$V_D\$, \$I_{E_2}\$, and \$I_{E_6}\$.
The matrix solution is then:
$$\begin{align*}
\begin{bmatrix}V_B \\ V_D \\ I_{E_2}\\I_{E_6}\end{bmatrix} &=\begin{bmatrix}0 & \frac{1}{R_3} & -1 & 0 \\ \frac{1}{R_4}+\frac{1}{R_6} & \frac{-1}{R_4} & 0 & 0 \\ 0 & \frac{-1}{R_3}+\frac{-1}{R_5} & 0 & -1 \\ \frac{-1}{R_4} & \frac{1}{R_4}+\frac{1}{R_5} & 1 & 0\end{bmatrix}^{-1}
\begin{bmatrix}\frac{V_{E_6}-V_{E_2}}{R_3} + I_{A_1} \\ - I_{A_1} \\ \frac{V_{E_2}-V_{E_6}}{R_3} - \frac{V_{E_6}}{R_5}\\\frac{V_{E_6}}{R_5}\end{bmatrix}
\end{align*}$$
If you stick those equations into some solver, or do it manually, you should get:
$$\begin{align*}
V_B &=-\frac{5}{8}\:\textrm{V}\\
V_D &=8\frac{3}{4}\:\textrm{V}\\
I_{E_2} &=-8\frac{1}{8}\:\textrm{A}\\
I_{E_6} &=-\frac{5}{8}\:\textrm{A}
\end{align*}$$
And from there you should be able to answer any quantitative questions about the rest of the circuit, such as the value for \$V_A-V_B\$.

A: Thanks to @jonk to its answer that was very helpful, but for study purpose I need a matrix based solution and at the end I got it using the (as we call it in Italy) Net currents method
Net equations
\begin{equation}
 \begin{cases}
  \text{N1: } V_1-E_2-V_4=0 \newline \\
  \text{N2: } E_2-V_3+V_5=0 \newline \\
  \text{N3: } V_4-V_5-E_6+V_6=0
 \end{cases}
\end{equation}
That is
\begin{equation}
 \begin{cases}
  \text{N1: } V_1-V_4=E_2 \newline \\
  \text{N2: } -V_3+V_5=-E_2 \newline \\
  \text{N3: } V_4-V_5+V_6=E_6\\
 \end{cases}
\end{equation}
Bipoles characteristics are

*

*\$V_3=R_3\cdot I_3\$

*\$V_4=R_4\cdot I_4\$

*\$V_5=R_5\cdot I_5\$

*\$V_6=R_6\cdot I_6\$

Nets currents are

*

*\$I_1=J_1\$

*\$I_2=J_2-J_1\$

*\$I_3=J_2\$

*\$I_4=J_1-J_3\$

*\$I_5=J_3-J_2\$

*\$I_6=-J_3\$

So substituting characteristics into equations
\begin{equation}
 \begin{cases}
  V_1-(R_4\cdot I_4)=E_2 \newline \\
  -(R_3\cdot I_3)+(R_5\cdot I_5)=-E_2 \newline \\
  (R_4\cdot I_4)-(R_5\cdot I_5)+(R_6\cdot I_6)=E_6
 \end{cases}
\end{equation}
Substituting net currents
\begin{equation}
 \begin{cases}
  V_1-(R_4\cdot (J_1-J_3))=E_2 \newline \\
  -(R_3\cdot J_2)+(R_5\cdot (J_3-J_2)=-E_2 \newline \\
  (R_4\cdot (J_1-J_3))-(R_5\cdot (J_3-J_2))+(R_6\cdot -J_3)=E_6
 \end{cases}
\end{equation}
That is
\begin{equation}
 \begin{cases}
  -R_4J_1 +R_4J_3 +V_1=E_2 \newline \\
  J_2(-R_3-R_5)+R_5J_3=-E_2 \newline \\
  R_4J_1+R_5J_2+J_3(-R_4--R_5-R_6)=E_6
 \end{cases}
\end{equation}
Adding a 4th equation \$J_1=A_1\$ the system is
\begin{equation}
 \begin{cases}
  -R_4J_1 +R_4J_3 +V_1=E_2 \newline \\
  J_2(-R_3-R_5)+R_5J_3=-E_2 \newline \\
  R_4J_1+R_5J_2+J_3(-R_4--R_5-R_6)=E_6  \newline \\
  J_1=A_1
 \end{cases}
\end{equation}
So solution will be retrieved using the following matrices
$$
\begin{bmatrix}
    J_1\\
    J_2 \\
    J_3\\
    V_1
\end{bmatrix}=
\begin{bmatrix}
    -R_4 & 0 & R_4 & 1 \\
    0 & (-R_3-R_5) & R_5 & 0 \\
    R_4 & R_5 & (-R_4-R_5-R_6) & 0\\
    1 & 0 & 0 & 0
\end{bmatrix}^{-1}\cdot
\begin{bmatrix}
    E_2\\
    -E_2 \\
    E_6\\
    A_1
\end{bmatrix}
$$


text:
Q: Breaking Lines in PDF whose value is from MYSQL I'm trying to find a solution for my PDF problem. I'm inserting a value into my PDF from mysql database but the problem is that the value is going over the cells instead of breaking line.
Here's snippet:
include 'restaurantconnect.php';
$count=0;
$sql="SELECT * FROM `restaurant`";
$result = $conn->query($sql);
 while($inventory = $result->fetch_assoc()){

 $concat = $inventory['first_name'] . " " . $inventory['last_name'];

 $pdf->Cell(25,5,"{$inventory['food_id']}",1,0,"R");
 $pdf->Cell(50,5,"{$concat}",1,0,"C");
 $pdf->Cell(20,5,"{$inventory['package']}",1,0,"L");
 $pdf->Cell(100,5,"{$inventory['orders']}",1,0,"L");
 $pdf->Cell(70,5,"{$inventory['addons']}",1,1,"L");

The values on my orders are from mysql database which has
rice,pork,seafood,vegetables, desserts
What it shows in the pdf is like this
   food_id | concat | package | orders | addons
      1    | John   |   1     | rice, seafood vegetables, desserts | extras

What I want to happen is
   food_id | concat | package | orders | addons
      1    | John   |   1     | rice,se| extra
                               afood,ve
                               getables


text:
Q: Unusual password protect software Is there software that will do this:

*

*Create a folder and name it.

*Password protect that folder.

*Folder is empty.

*Now drop a file to be password protected into that folder without having to go through the trouble of password protecting it, i.e. it is automatically password protected.

*Other files to be added in the same way.

To retrieve a file either:

*

*password unprotect the folder and choose the file, or,

*open up the folder, choose a file and unprotect that.

A: This post probably needs to be moved to SE Software Recommendations, but I'm not a mod here.
At any rate, (assuming your OS of choice is Windows) the functionality you're looking for can be realized with a BitLocker encrypted external drive or flash drive, via "BitLocker to go."

A: Closest off the shelf offering would probably be veracrypt
https://www.veracrypt.fr/
If you wanted that precise functionality, you would likely need to build it.


text:
Q: Как правильно добавить запись в БД Как правильно добавить запись в БД , если есть две связанные таблицы?
Добавлять по какому то событию? То есть, когда в одной таблице появилась запись только тогда добавляем запись в втрою? При попощи чего это делается?
Интересует вопрос как по yii2 так и по чистому php
И ошибки:
Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

A: В чистом PHP это делается вручную - то-есть событий нет. Но для начало тебе необходимо определить какая зависимость между таблицами. Например если первая таблица зависит от второй то вначале добавляешь вторую запись, а потом первую.
Например если ты добавил запись в вторую таблицу то, как правило, как в PDO так и встроенные mysql библиотеки возвращают первичный ключ записи (если конечно ты используешь InnoDB). Если первичный ключ возвращен то это значит запись удачно добавлена смело добавляй зависимую от нее следующею запись.
Если хочешь автоматизировать это на уровне mysql то копай в направлении триггеров mysql. Можешь начать вот отсюда . Но использовать триггеры mysql крайне не рекомендуется поскольку желательно не вносить на уровень баз данных логику!


text:
Q: como Criar Array que atualiza a lista localStorage com Angular? Olá pessoal boa Tarde como posso esta atualizando uma lista de dados no localstorage com Angular?
exemplo se na lista esta escrito 'Bruno' e não era 'Bruno' mas sim 'Paulo' como posso esta atualizando...

A: O LocalStorage funciona com base em salvar informações com chave e valor.
lembrando que os valores somente pode ser strings.
O método setItem armazena uma informação no localStorage
ex:
localStorage.setItem('professor', 'Eduardo antonio');

O método getItem recupera o valor salvo através do nome da chave
ex:
localStorage.getItem('professor');

O método removeItem remove o item através do nome da chave
localStorage.removeItem('professor');

Se pretende salvar um array no localStorage o ideal será transformar o array em string antes de salvar no storage e reverter quando pegar o item.
ex:
public getItemArray(chave) {
  let valor = localStorage.getItem(chave);
  if(!valor){
    return valor
  }
  let valorJson = JSON.parse(valor);
  return valorJson;
}

public setItemArray(chave, valor){
  if(!Array.isArray(valor)){
    return
  }
  let valorString = JSON.stringify(valor);
  localStorage.setItem(chave, valorString);
}

Com o array em maos você pode editar como quiser os itens e salvar o novo array modificado.


text:
Q: Woocommerce - Keep terms and conditions checked on cart update Good morning everyone.
I have a kind of strange request, in my woocommerce website I gave the option to take orders manually through phone calls, so there is a person that answer the calls and create orders for various customers.
This person use a custom made page to register orders, with the possibility to select an existing user or to create a new one, to add items to cart and to fill the shipping/billing address.
In this page there is also the order review section with the checkbox of terms and conditions that everytime must be checked to complete the order.
Since this is waste of time in this case I'm looking for a way to keep this checkbox always checked.
Currently I'm using this code in my functions.php to show the terms and conditions as checked
function check_terms() {
if(is_page('custom-page')) {
    return true;
}

add_filter( 'woocommerce_terms_is_checked', 'check_terms', 10 );
add_filter( 'woocommerce_terms_is_checked_default', 'check_terms', 10 );

This works until I add or remove a product in the cart, after that the checkbox is resetted to empty and I go back to the starting point.
So I'm here to ask if any of you know a trick to keep this checkbox checked.
I've already tried JS but without success since it's not fired after the update.
Thank you in advance and sorry for my english.
Have a nice day.

A: function patricks_wc_terms( $terms_is_checked ) {
    return true;
}
add_filter( 'woocommerce_terms_is_checked', 'patricks_wc_terms', 10 );
add_filter( 'woocommerce_terms_is_checked_default', 'patricks_wc_terms', 10 );

Put this in your function.php file and try if any error then only replace function name


text:
Q: Does anyone know what the problem is for this code I am trying to run on arduino? I already installed pip, python3, uploaded standard firmata, and I installed pyfirmata. But I always get this error code
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/serial/serialposix.py", line 322, in open
    self.fd = os.open(self.portstr, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
FileNotFoundError: [Errno 2] No such file or directory: 'COM8'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Users/lelandwang/Documents/blink.py", line 3, in <module>
    board=pyfirmata.Arduino('COM8')
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyfirmata/__init__.py", line 19, in __init__
    super(Arduino, self).__init__(*args, **kwargs)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/pyfirmata/pyfirmata.py", line 89, in __init__
    self.sp = serial.Serial(port, baudrate, timeout=timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/serial/serialutil.py", line 244, in __init__
    self.open()
  File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/serial/serialposix.py", line 325, in open
    raise SerialException(msg.errno, "could not open port {}: {}".format(self._port, msg))
serial.serialutil.SerialException: [Errno 2] could not open port COM8: [Errno 2] No such file or directory: 'COM8'

I expected the led on my light to light up, which is at gpio 13


text:
Q: Difference between  and ? Guys What is a difference between both??
if I set <table runat=server> I can use it at server side also.
Is there any differnce between both??
Thanx

A: <asp:Table> is a .Net object that has specific properties and capabilities that can be utilized through .Net scripting or code behind logic. <table> is an Html element that can be accessed through scripting and code behind logic, but it has no native .Net capabilities and can only be output as is.

A: asp:table lives in the System.Web.UI.WebControls namespace - these are components that wrap around the different HTML controls and provide a familiar interface and usage to winforms developers (for a table, it will have a Columns attribute).
table lives in the System.Web.UI.HtmlControls namespace and is a direct analogue to the actual HTML controls and provides an interface more familiar to HTML developers (for a table, it will have a Cols attribute).
In terms of output, these pretty much behave the same way.

A: *

*A <asp:Table> is an ASP.NET control

*A <table> is HTML.

Whenever you create an aspx, you're actually modify an XML document that has the representation of HTML - this can include both server side and client side tags.
Your typical web browser has no idea what a <asp:Table> is because it only understands HTML.  Therefore the server (ASP.NET) converts all server side tags into its HTML representation.  Therefore if you use your browser to view the source of a page that includes <asp:Table> you will only see <table> tags.

A: The <asp:table> represents the declarative syntax for the System.Web.UI.WebControls.Table class which is a WebControl. Being a WebControl, it has a much more powerful programming interface and
provides a more object like interface providing for a high level of control.
The <table> tag on the other hand when used with the runat="server" attribute represents the
System.Web.UI.HtmlControls.HtmlTable class which is a HtmlControl. Being a HtmlControl, it is very basic and provides much lesser programmatic control over it's properties.

A: HTML elements in ASP.NET files are treated as text, server controls are treated as objects. To make these HTML elements server side programmable you can add a runat="server" attribute to the HTML element. The main difference between HTML table and <asp:Table> is the way they can be nested, created, bound and controlled at runtime as an object rather than a string of text.
More information can be found here.


text:
Q: log4j2 XML Rolling File Appender - Slight changes in appender makes a working xml file code not work I have a log4j2 xml file appender that is completely working and rolls back the files after every minute. I tried to change that rollback to once per day with some tweaks on the code but now it's not working. What am I missing?
This is the old XML file appender(the working one):
        <!-- Rolling File Appenders -->
    <RollingFile name="RollingFile" fileName=".\logs\log${date:yyyyMMdd}.log"
    filePattern=".\logs\oldLogs\log_%d{yyyyMMdd-HHmm}.log">
        <PatternLayout
            pattern="%d{yyyy-MM-dd HH:mm:ss:SSS} [%t] %-3level %logger{36} - %msg%n" />

        <Policies>
            <TimeBasedTriggeringPolicy interval="1" modulate="true"/>
        </Policies>

        <DefaultRolloverStrategy max="3">
            <Delete basePath=".\logs\oldLogs" maxDepth="2">
            <IfAccumulatedFileCount exceeds="3" />
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>

This is the new one for daily rolling (does not work):
        <!-- Rolling File Appenders -->
    <RollingFile name="RollingFile" fileName=".\logs\log${date:yyyyMMdd}.log"
    filePattern=".\logs\oldLogs\log_%d{yyyyMMdd}.log">
        <PatternLayout
            pattern="%d{yyyy-MM-dd HH:mm:ss:SSS} [%t] %-3level %logger{36} - %msg%n" />

        <Policies>
            <OnStartupTriggeringPolicy/>
            <TimeBasedTriggeringPolicy interval="1" modulate="true" />
        </Policies>

        <DefaultRolloverStrategy max="10">
            <Delete basePath=".\logs\oldLogs" maxDepth="2">
            <IfAccumulatedFileCount exceeds="10"/>
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>

Edit:
Behavior I'm Expecting:
~Will generate logs per day and store the logs the day before in this folder: ".\logs\oldLogs\"
~Keeps only the 10 most recent logs and deletes the older logs
Current Behavior:
~Generates log per day but by tomorrow, does not roll the file to this folder: ".\logs\oldLogs\"
~Does not delete any log files

A: I think the easiest solution would be to make the fileName attribute of the RollingFile a constant. The most recent logs will always be contained in this file, so I don't really see it being necessary to put a date on the file name. When the log is archived the date will be added to the file name per the filePattern.
Additionally, you can remove the OnStartupTriggeringPolicy and the max attribute of the DefaultRolloverStrategy. The max attribute is used with the "integer counter" mentioned in description of the RollingFileAppender filePattern parameter and since you're not using that counter the max won't help you.
I believe this should work for you:
    <RollingFile name="RollingFile" fileName=".\logs\applog.log"
        filePattern=".\logs\oldlogs\applog_%d{yyyyMMdd}.log">
        <PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss:SSS} [%t] %-3level %logger{36} - %msg%n" />
        <Policies>
            <TimeBasedTriggeringPolicy interval="1"
                modulate="true" />
        </Policies>
        <DefaultRolloverStrategy>
            <Delete basePath=".\logs\oldlogs" maxDepth="2">
                <IfAccumulatedFileCount exceeds="10" />
            </Delete>
        </DefaultRolloverStrategy>
    </RollingFile>


text:
Q: testing app not running -showing error in device manager illegal char*> at index0:*.lock
above phrase is appearing  on my screen.
I tried running again and again but the above error is appearing again and again.


text:
Q: How to test browser functionality of popups using Chromedriver (such as for Payment Request API) How can I write browser tests for modals like this?

In case it matters, I'm using Laravel 5.6 Dusk for browser testing, and my payment request modal is generated via a Stripe Payment Request Button.
Stripe's Payment Request Button uses the cross-browser Payment Request API from W3C.
Chrome doesn't let me "inspect" the HTML of the elements of the modal, so I'm not sure how to write compatible commands in the form of $browser->click('.selector');.


text:
Q: Can someone please help me understand why this code is not turning the Android Action Bar yellow? I followed the Google's tutorial for changing the color of the Action Bar and wrote the code shown below, but the Action Bar still shows up as per the Holo Light theme.
styles.xml:
    <style name="CustomActionBarTheme" parent="@style/Theme.AppCompat.Light">

    <!-- Support library compatibility -->
    <item name="actionBarStyle">@style/MyActionBar</item>
</style>
<!-- ActionBar styles -->
<style name="MyActionBar" parent="@style/Widget.AppCompat.Light.ActionBar">

    <!-- Support library compatibility -->
    <item name="background">@color/yellow</item>
</style>

Android Manifest:
    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/Theme.AppCompat.Light" >
    <activity
        android:name="com.example.labside.MainActivity"
        android:label="@string/app_name"
        android:theme="@style/CustomActionBarTheme" >

The colors.xml has yellow defined as #FFFF00. Please let me know what I am doing wrong as this whole stuff about Action Bar styling with support for API level 8 is starting to get very confusing! As always, many thanks for all your help!! :)

A: What android version are you using? Take a look at this post: custom style action bar not working in android 4
Following this post, you need to declare your custom style twice. It looks like you are missing the declaration with the android: prefix.
So I guess, you'll have to add:
<item name="android:background">@color/yellow</item>


text:
Q: Explain this terminal command please Can someone please explain the following terminal command in Ubuntu:-
mount -o rw, remount

A: -o means "options will follow"
rw mounts read and write
remount, well, remount an already mounted system
this command won't work though as you need to provide more details regarding device filesystem, etc.
check man mount


text:
Q: Play a ogg file in Unity3d says "Streaming of 'ogg' on this platform is not supported" I'm using Unity3d 5.3.4f1 and I want to play a ogg file from a direct url. Target platform is Android.
Example:
https://upload.wikimedia.org/wikipedia/commons/6/65/Star_Spangled_Banner_instrumental.ogg
My code:
public void PlayAnthem()
{
    WWW wwwAnthem = new WWW(AnthemURL);

    StartCoroutine (WaitForRequestplay (wwwAnthem));

//This works:
//      AudioAnthem.clip = Resources.Load ("Japan") as AudioClip;
//      AudioAnthem.Play ();

}

private IEnumerator WaitForRequestplay(WWW www){
    yield return www;

    AudioAnthem.clip = www.audioClip;

    AudioAnthem.Play();

}

My error:
Streaming of 'ogg' on this platform is not supported
UnityEngine.WWW:get_audioClip()
How can I play a ogg file in my app? Do I have to download it before?
Thank you.

A: You cannot stream an ogg file while it still downloading. You have to finish downloading it before playing but I don't think this is the problem because you had yield return www; which waits until it's done downloading.
Try   www.GetAudioClip(true,false,AudioType.OGGVORBIS);. Sometimes, this seems to solve the this platform is not supported error.
private IEnumerator WaitForRequestplay(WWW www){
    yield return www;

    AudioAnthem.clip = www.GetAudioClip(true,false,AudioType.OGGVORBIS);

    AudioAnthem.Play();

}

Also make sure that you have permission to access that ogg file you posted. To verify that this is not a permission problem, host a simple ogg file in a local server then try to access it. If it doesn't work in the Editor, try it in the Android.


text:
Q: Laravel 5.4 search query for multiple checkbox values I'm new to checkboxes. I want to let users do a search based on three possible filters represented by checkbox lists.
    users can search different way.
        please help me.
            Here is my Html Code
{!! Form::open(['url' => 'search-job']) !!}

    Hours:

    <input type="checkbox" name="jobs_type[]" value="Part Time">Part Time
    <input type="checkbox" name="jobs_type[]" value="Full Time">Full Time
    <input type="checkbox" name="jobs_type[]" value="Temporary">Temporary

    category:

    @foreach($job_function as $job_category)

                <input type="checkbox" name="job_function[]" value="{{ $job_category->id }}">{{$job_category->name}}

    @endforeach

    salary

    <input type="checkbox" name="salary[]" value="1000"/> upto $1000

    <input type="checkbox" name="salary[]" value="1000-1999">$1,000- 2,000

    <input type="checkbox" name="salary[]" value="2000-3999">$2,000 - 4,000

<input type="submit" value="Search">

{!! Form::close() !!}

A: public function job_search(Request $request){

$builder = Job::query();
$term = Request::all();

if(!empty($term['job_function'])){
   $builder->whereIn('category_id',$term['job_function']);

}
if(!empty($term['jobs_type'])){
   $builder->orWhereIn('jobs_type',$term['jobs_type']);
}
if(!empty($term['salary'])){
    $builder->orWhereIn('salary','=',$term['salary']);
}

$result = $builder->orderBy('id')->get();

return view('frontend.pages.job.find_jobs')->withResult($result);
    }


text:
Q: WPF Datagrid scrollbar does not appear This is my XAML code:
<DockPanel Grid.Row="0" MaxWidth="2048" MinWidth="989" Width="Auto" x:Name="dockPanelGrid" Grid.Column="2"  ScrollViewer.VerticalScrollBarVisibility="Auto" VerticalAlignment="top" Background="Red">
    <DataGrid x:Name="GridData" MaxWidth="2048" IsReadOnly="True"
        HorizontalAlignment="Stretch"
        HorizontalContentAlignment="Stretch"
        IsSynchronizedWithCurrentItem="True"
        SelectionMode="Extended"
        SelectionUnit="FullRow"
        Style="{StaticResource DataGridStatStyle}"
        DockPanel.Dock="Left"
        Margin="0"
        ScrollViewer.CanContentScroll="false"
        VirtualizingPanel.ScrollUnit="Item"
        VirtualizingPanel.IsVirtualizingWhenGrouping="True"
        EnableRowVirtualization="false"
        EnableColumnVirtualization="False"
        CanUserResizeColumns="False"
        Loaded="GridData_Loaded">
    </DataGrid>
</DockPanel>

I noticed that when I have no records bound to the DataGrid, the last columns are not shown and scrollbar does not appear. If I have at least one row, everything works fine.
In order to be sure about the size of my DataGrid and its container I wrote this:
double antani = 0;
foreach (DataGridColumn col in GridData.Columns)
    antani += col.ActualWidth;

if (antani > GridData.ActualWidth)
    ScrollViewer.SetHorizontalScrollBarVisibility(dockPanelGrid, ScrollBarVisibility.Visible);
else
    ScrollViewer.SetHorizontalScrollBarVisibility(dockPanelGrid, ScrollBarVisibility.Auto);

And I see that antani (which is the "real" width of Datagrid) is greater that the container, but I'm not be able to show the horiziontal scrollbar. Any help?


text:
Q: similarity word with Trigram how i make a function for word similarity in search result.
For example if i write in my search form "ugo" or "hugo". i try this :
("contenue" is my column for txt files in db postgresql)
views.py
class SearchResultsList(ListView):
    ...
    ...
    ...
    def get_queryset(self):
        query = self.request.GET.get("q")
        vector_column = SearchVector("contenue", weight="A", config='french')
        search_query = SearchQuery(query)
        search_headline = SearchHeadline("contenue", search_query)
        result1 = Q(contenue__search=query)
        result2 = Q(SearchVector("contenue"))
        return Actes.objects.filter(result1).annotate(headline=search_headline)
        .annotate(similarity=TrigramSimilarity('contenue', query) ,)
        .filter(similarity__gte=0.6).order_by('-similarity')

when i don't add trigram i have a result but not work if i write "ugo" instead of "hugo" or "higo" instead of "hugo".
Thank and sorry for my bad english


text:
Q: What better ways are there to add a column to a pandas.Series? import pandas
series1 = pandas.Series({
   'a':1,
   'b':2,
})

dict = series1.to_dict()
dict['c'] = 3
series2 = pandas.Series(dict)

I need to add a column/index onto series1. Current, as shown above, I'm creating series2 by making a dictionary from series1's data, adding an index, then creating a new series using that dictionary.
Is there a way to add a column or merge two series' columns similar to pandas.DataFrame.join() or pandas.DataFrame.assign()?

A: You can do it via the append function.
series2 = series1.append(pd.Series({'c':2}))

If you wanna use all the dataframe methods then you can convert series object to dataframe objects via -
series1.to_frame()

A: It solves this task "I need to add a column/index onto series1"
series1.loc['c'] = 3


text:
Q: Detecting System.setProperty method invocations I'm facing a conundrum here.
One of the applications that I've developed is loading an incorrect implementation of the DocumentBuilderFactory class of JAXP. This behavior was later deduced to be resulting from another class in different application built by a different team/company. The said class had changed the preferred DocumentBuilderFactory class upon loading, by inclusion of a static block similar to the one below:
  static
  {
    System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "a new factory");
  }

If one goes by the Javadocs of the DocumentBuilderFactory.newInstance method, it would be quite obvious that the above code was responsible for changing the parser implementation returned to all applications, when the newInstance method is invoked.
A patch was applied, which corrected this problem, but it leads me to ask this question - how does one determine which class is performing the System.setProperty call at runtime?
We had produced a custom build of OpenJDK with a modified System class that was responsible for nailing the culprit, for the very simple reason that we did not have access to all the sources for all the applications deployed on the server. But this was possible only due to the fact that the production environment was replicated in its entiriety. The question therefore, could also be interpreted as -  how does one determine which class is performing the System.setProperty call at runtime, in a production environment?

A: System.setProperty is checked by a SecurityManager, if installed.
You can create your own MySecurityManager and deploy at runtime. Your own SecurityManager can log some information like the current stacktrace, when the method checkPropertyAccess is called:
public class MySecurityManager extends SecurityManager
{

    public MySecurityManager()
    {
        super();
    }

    @Override
    public void checkPropertyAccess(String key)
    {
        if ("javax.xml.parsers.DocumentBuilderFactory".equals(key))
        {
            System.err.println("checkPropertyAccess(String :" + key + "): ");
            Thread.currentThread().dumpStack(); // or anything useful for
                                                // logging the context.
            new Throwable().printStackTrace(); // whatever, or use it with
            // PrintStream/PrintWriter, or some logging framework if configured.
        }
        super.checkPropertyAccess(key);
    }

    @Override
    public void checkPermission(Permission perm)
    {
        if (perm instanceof PropertyPermission)
        {
            PropertyPermission propPerm = (PropertyPermission) perm;
            System.err.println("checkPropertyAccess(String:" + propPerm.getName() + "):");
            Thread.currentThread().dumpStack(); // or anything useful for
                                                // logging the context.
            new Throwable().printStackTrace(); // whatever, or use it with
            // PrintStream/PrintWriter, or some logging framework if configured.
        }
        super.checkPermission(perm);
    }
}

A: String literals are UTF8-encoded in the class file format and since there is no reason to assume that the offending invoker is using code to concatenate the property name, I would simply have unpacked all JARs from the classpath into one directory and tried a recursive grep for "javax.xml.parsers.DocumentBuilderFactory" through the class files. You would have at least found all class files containing this String as a literal and hopefully not to many false positives.
If the class name of the incorrect implementation is easier to identify, it would perhaps been more clever to search for that instead.

A: Just start you application in debug mode, connect to it with eclipse, set breakpoint and look what class do it in  call hierarchy http://www.eclipsezone.com/eclipse/forums/t53459.html

A: I know 2 solutions

*

*use aspect framework (aspectJ or so)

*Modify System class (add logging to setProperty() method) new Throwable().printStacktrace();
will report you where the method was called from.

Now run your application with option -Xbootclasspath/p and put your version System class there.
-Xbootclasspath/p:<directories and zip/jar files separated by ;>
                  prepend in front of bootstrap class path
I prefer the second solution because it is very simple.

A: Seems like some use case for aspect frameworks, no ?


text:
Q: DbContext prematurely disposing when passed into another `using` block I have one function that requires an active dbContext that is used in multiple places.  In some places the DbContext already exists so I pass it in and use it if it does:
public void DoStuff(){
     using (var db = new dbContext()){
         DoThings(db);
         db.SaveChanges(); // breaks, context was disposed
     }
  }

public void DoThings(DbContext optionalContext = null){
     using (var db = optionalContext ?? new dbContext()){
         DoInternalThings(db);
     }
  }

Is there any way to make this pattern work, or should I just make the optionalContext required and spin up the contexts from the calling functions?  Because then I end up with a bunch of this:
public void DoStuff(){
     using (var db = new dbContext()){
         DoThings(db);
         db.SaveChanges(); // breaks
     }
 }

 public void DoThings(){ // version without dbContext passed in - solely a wrapper - yuck!
     using (var db = new dbContext()){
         DoThings(db);
     }
 }

  public void DoThings(DbContext db){
       DoInternalThings(db);
  }

A: You should not dispose an object that is passed into a function, because you do not own it and don't control its lifetime. Yes, spin up a context in a calling function and makes the context required, and it's up to you how to design that in a beautiful and convenient to use way.

A: You don't need to create another context for the inner function.Use already created one if that one is already exist else create a new one as shown below.
 public void DoStuff(){
         using (var db = new dbContext()){
             DoThings(db);
             db.SaveChanges();
         }
      }

    public void DoThings(DbContext db){
        if (db =null){
           using (var db = new dbContext()){
              DoInternalThings(db);
             }
           }else{
              DoInternalThings(db);
           }
      }

Good explanation about the behavior of DbContext and the Using statement from the Program Manager of the Entity Framework team.
Rowan Miller (MSFT)

The default behavior of DbContext is that the underlying connection is
  automatically opened any time is needed and closed when it is no
  longer needed. E.g. when you execute a query and iterate over query
  results using "foreach", the call to IEnumerable.GetEnumerator()
  will cause the connection to be opened, and when later there are no
  more results available, "foreach" will take care of calling Dispose on
  the enumerator, which will close the connection. In a similar way, a
  call to DbContext.SaveChanges() will open the connection before
  sending changes to the database and will close it before returning.
Given this default behavior, in many real-world cases it is harmless
  to leave the context without disposing it and just rely on garbage
  collection.
That said, there are two main reason our sample code tends to always
  use "using" or dispose the context in some other way:

*

*The default automatic open/close behavior is relatively easy to override: you can assume control of when the connection is opened and
  closed by manually opening the connection. Once you start doing this
  in some part of your code, then forgetting to dipose the context
  becomes harmful, because you might be leaking open connections.

*DbContext implements IDiposable following the recommended pattern, which includes exposing a virtual protected Dispose method that
  derived types can override if for example the need to aggregate other
  unmanaged resources into the lifetime of the context.

Here is the original article of it : Do I always have to call Dispose() on my DbContext objects

A: You can transfer dbcontext, but why? Why not something like
public enum thingsToDo  {myStuff, yourStuff, otherStuff };
    public void doThings(thingsToDo whatToDo)
    {
        using (SqlConnection conn = new SqlConnection(""))
        {
            switch (whatToDo)
            {
                case thingsToDo.myStuff:
                    //this is what's indside the USING statement in doStuff
                    break;
                case thingsToDo.yourStuff:
                    //this is what's inside the USING statement in yourStuff
                    break;
                case thingsToDo.otherStuff:
                    //this is in method 3
                    break;
            }

            db.SaveChanges();
        }
    }

Then one or all of the following:
doThings(thingsToDo.myStuff); doThings(thingsToDo.otherStuff);doThings(thingsToDo.yourStuff);

A: As per my thinking your code is doing what is asked to do. If you use "Using" block then it will call dispose method when it get over. I also suggest that there is something wrong with your design of code. If Dbcontext is being created somewhere else then its lifetime also controlled by some other function that creating it.
Here problem is that second using does not know that there is already one using block over there. This is how compiler is designed. Also I am agree with @Sampath code as well.


text:
Q: duplicate ajax calls when include jquery ujs in rails application i am developing a basic depot application with rails
i have added a button
<%= button_to 'Add to Cart', line_items_path(product_id: product) , remote: true %>

when i click on home page hyperlink then click on the button again , ajax gets duplicated , if i click on home page 3 times , the button ajax call 3 times and so on
Note : the problem disappear when i remove jquery-ujs from application.js
line_item controller
def create
@cart = current_cart
product = Product.find(params[:product_id])
@line_item = @cart.add_product product
@line_item.save
respond_to do |format|
  if @line_item.save
    format.html { redirect_to store_url }
    format.js { @current_item = @line_item }
    format.json { render :show, status: :created, location: @line_item }
  else
    format.html { render :new }
    format.json { render json: @line_item.errors, status: :unprocessable_entity }
  end
end
end

home page action
def index
@products = Product.order(:title)
@cart = current_cart
end

application.js
// This is a manifest file that'll be compiled into application.js,
// listed below.
//
//= require jquery
//= require turbolinks
//= require jquery-ui
//= require jquery_ujs
//= require_tree .

ajax response should render this js file
show.js.erb
$('#cart').html("<%=j render @cart %>");
//#START_HIGHLIGHT
$('#current_item').css({'background-color':'#88ff88'})
.animate({'background-color':'#114411'} , 1000);

using gem jquery rails 4.0.4

A: i found the problem . using turbolink with javascript link tags outside head load an extra jquery script every time i click on home page , a dummy  solution is to put javascript link tag inside the head itself


text:
Q: Oracle 9 - Resetting Sequence to match the state of the table I have a sequence used to seed my (Integer based) primary keys in an oracle table.
It appears this sequence has not always been used to insert new values into the table. How do I get the sequence back in step with the actual values in the table?

A: Declare
  difference INTEGER;
  sqlstmt varchar2(255);
  sequenceValue Number;
begin
sqlstmt := 'ALTER SEQUENCE YOURSEQUENCE INCREMENT BY ';
select YOURSEQUENCE.NEXTVAL into sequenceValue from dual;
select  (nvl(Max(YOURID),0) - sequenceValue)+1 into difference from YOURTABLE;
if difference > 0 then
  EXECUTE IMMEDIATE sqlstmt || difference;
  select  YOURSEQUENCE.NEXTVAL INTO sequenceValue from dual;
  EXECUTE IMMEDIATE sqlstmt || 1;
end if;
end;

A: I made this script as I did not find a script online that dynamically sets all my sequences to the current highest ID. Tested on Oracle 11.2.0.4.
DECLARE
  difference         INTEGER;
  sqlstmt            VARCHAR2(255) ;
  sqlstmt2           VARCHAR2(255) ;
  sqlstmt3           VARCHAR2(255) ;
  sequenceValue      NUMBER;
  sequencename       VARCHAR2(30) ;
  sequencelastnumber INTEGER;
  CURSOR allseq
  IS
     SELECT sequence_name, last_number FROM user_sequences ORDER BY sequence_name;
BEGIN
  DBMS_OUTPUT.enable(32000) ;
  OPEN allseq;
  LOOP
    FETCH allseq INTO sequencename, sequencelastnumber;
    EXIT
  WHEN allseq%NOTFOUND;
    sqlstmt  := 'ALTER SEQUENCE ' || sequencename || ' INCREMENT BY ';
    --Assuming: <tablename>_id is <sequencename>
    sqlstmt2 := 'select (nvl(Max(ID),0) - :1)+1 from ' || SUBSTR(sequencename, 1, LENGTH(sequencename) - 3) ;
    --DBMS_OUTPUT.PUT_LINE(sqlstmt2);
    --Attention: makes use of user_sequences.last_number --> possible cache problems!
    EXECUTE IMMEDIATE sqlstmt2 INTO difference USING sequencelastnumber;
    IF difference > 0 THEN
      DBMS_OUTPUT.PUT_LINE('EXECUTE IMMEDIATE ' || sqlstmt || difference) ;
      EXECUTE IMMEDIATE sqlstmt || difference;
      sqlstmt3 := 'SELECT ' || sequencename ||'.NEXTVAL from dual';
      DBMS_OUTPUT.PUT_LINE('EXECUTE IMMEDIATE ' || sqlstmt3 || ' INTO sequenceValue') ;
      EXECUTE IMMEDIATE sqlstmt3 INTO sequenceValue;
      DBMS_OUTPUT.PUT_LINE('EXECUTE IMMEDIATE ' || sqlstmt || 1) ;
      EXECUTE IMMEDIATE sqlstmt || 1;
      DBMS_OUTPUT.PUT_LINE('') ;
    END IF;
  END LOOP;
  CLOSE allseq;
END;

A: If ID is the name of your PK column and PK_SEQ is the name of your sequence:

*

*Find the value of the highest PK by
SELECT MAX(ID) FROM tableName

*Find the value of the next PK_SEQ by
    SELECT PK_SEQ.NEXTVAL FROM DUAL

*If #2 > #1 then nothing needs to be
    done, assuming you treat these
    values as true surrogate keys

*Otherwise, alter the sequence to
    jump to the max ID by ALTER SEQUENCE
    PK_SEQ INCREMENT BY [#1 value - #2
    value]

*Bump the sequence by SELECT
    PK_SEQ.NEXTVAL FROM DUAL

*Reset the sequence increment value
    to 1 by ALTER SEQUENCE PK_SEQ
    INCREMENT BY 1
This all assumes that you don't have new inserts into the table while you're doing this...

A: In short, game it:
-- Current sequence value is 1000

ALTER SEQUENCE x INCREMENT BY -999;
Sequence altered.

SELECT X.NEXTVAL FROM DUAL;
1

ALTER SEQUENCE x INCREMENT BY 1;
Sequence altered.

You can get the max sequence value used within your table, do the math, and update the sequence accordingly.

A: In some cases, you may find it easier to simply get the current max value and then
drop sequence x;
create sequence x start with {current max + 1};

The app will be broken after you do the drop. But that will keep anybody from inserting rows during that period, and creating a sequence is quick. Make sure you recreate any grants on the sequence since those will be dropped when the sequence is. And you may want to manually recompile any plsql that depends on the sequence.

A: Adding up to https://stackoverflow.com/a/15929548/1737973, but without resorting to SEQUENCENAME.NEXTVAL hence not resulting in one position over it should be:
DECLARE
  difference INTEGER;
  alter_sequence_statement VARCHAR2 (255);
  sequence_value NUMBER;
BEGIN
  --   Base for the statement that will set the sequence value.
  alter_sequence_statement :=
      'ALTER SEQUENCE SEQUENCENAME INCREMENT BY ';

  --   Fetch current last sequence value used.
  SELECT
    --   You could maybe want to make some further computations just
    -- below if the sequence is using caching.
    last_number
  INTO sequence_value
  FROM all_sequences
  WHERE sequence_owner = 'SEQUENCEOWNER' AND sequence_name = 'SEQUENCENAME';

  --   Compute the difference.
  SELECT max(id) - sequence_value + 1 INTO difference
  FROM SCHEMANAME.TABLENAME;

  IF difference <> 0 THEN
    --   Set the increment to a big offset that puts the sequence near
    -- its proper value.
    EXECUTE IMMEDIATE alter_sequence_statement || difference;

    --   This 'sequence_value' will be ignored, on purpose.
    SELECT SEQUENCENAME.NEXTVAL INTO sequence_value FROM dual;

    --   Resume the normal pace of incrementing one by one.
    EXECUTE IMMEDIATE alter_sequence_statement || 1;
  END IF;
END;

Disclaimer: if the sequence is using caching (all_sequences.cache_size set to bigger than 0) you are probably wanting to take it into consideration in the Compute the difference step.
Oracle documentation for all sequences....

A: *

*select max value from table & set sequence value to it.

SELECT setval( 'table_id_seq_name', (SELECT MAX(id) FROM table_name ) );


text:
Q: Receiving an error when trying to backup bitlocker key to Azure AD with PowerShell We are trying to create a script within our environment to upload bitlocker keys to Azure AD using powershell and BackupToAAD-BitLockerKeyProtector
But we receive an error message on all PCs we have tried so far, error message:
BackupToAAD-BitLockerKeyProtector : JSON value not found. (Exception from HRESULT: 0x83750009)
At line:1 char:1
+ BackupToAAD-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyPr ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], COMException
    + FullyQualifiedErrorId : System.Runtime.InteropServices.COMException,BackupToAAD-BitLockerKeyProtector

I have tried the following and multiple other scripts:
BackupToAAD-BitLockerKeyProtector -MountPoint $env:SystemDrive -KeyProtectorId ((Get-BitLockerVolume -MountPoint $env:SystemDrive ).KeyProtector | where {$_.KeyProtectorType -eq "RecoveryPassword" }).KeyProtectorId

When checking with (Get-BitLockerVolume -MountPoint $env:SystemDrive ).KeyProtector it does output a KeyRrotectorID and RecoveryPassword.
Do anyone have any idea what's going on, or why it's not working?
Any help would be very much appreciated.

A: I Tried to reproduce the same in my environment to backup bit locker key to Azure AD with PowerShell
You can use below PowerShell script to backup Bit locker key to Azure AD with PowerShell.
Connect-AzureAD

$BitlockerVol = Get-BitLockerVolume -MountPoint $env:SystemDrive
        $BPID=""
        foreach($BP in $BitlockerVol.KeyProtector){
            if($BP.KeyProtectorType -eq "RecoveryPassword"){
                $BPID=$BP.KeyProtectorId
                break;
            }
        }
       BackupToAAD-BitLockerKeyProtector -MountPoint "$($env:SystemDrive)" -KeyProtectorId ((Get-BitLockerVolume -MountPoint $env:SystemDrive ).KeyProtector | where {$_.KeyProtectorType -eq "RecoveryPassword" }).KeyProtectorId

Once ran the above PowerShell code, it got executed successfully.

To check the Bit locker Keys in Azure AD,
Got to Azure Active Directory > Devices > All devices >Search your Device >BitLocker keys (Preview) > Show Recovery Key.

l


text:
Q: How to list all categories and tags in a page? Suppose we have few categories, tags and custom post type and taxonomies. How can we list all categories, tags in a page? Something like;

Page
Category Thumbnail and Category Name 1(link to category page)
  Description
Category Thumbnail and Category Name 2(link to category page)
  Description
Category Thumbnail and Category Name 3(link to category page)
  Description
Divider
Tag Thumbnail and Tag Name 1(link to Tag page) Description
Tag Thumbnail and Tag Name 2(link to Tag page) Description
Tag Thumbnail and Tag Name 3(link to Tag page) Description

Same with custom post type and taxonomies.
And if the description and thumbnail are not possible then only a name with link will be adequate.
Most of this is achievable by these plugins.

*

*https://wordpress.org/plugins/multi-column-taxonomy-list/

*https://wordpress.org/plugins/multi-column-tag-map/
Right now I'm looking in plugin code to achieve what I want.

A: TERM METADATA
It's possible to get thumbnails for terms using the new Term Metadata in 4.4. You just also need to define those ahead of time yourself.

*

*add_term_meta( int $term_id, string $meta_key, mixed $meta_value, bool $unique = false )

*get_term_meta( int $term_id, string $key = '', bool $single = false )

*update_term_meta( int $term_id, string $meta_key, mixed $meta_value, mixed $prev_value = '' )

CATEGORIES
get_categories ( ) Returns an array of category objects matching the query parameters.
echo "Categories:
";

$args = array(
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'public'                   => true,
);

$categories = get_categories( $args );

foreach ( $categories as $category ) {
     echo '' . $category->name . '
';
}

echo "
"; // divider

TAGS
get_tags ( ) Retrieves an array of objects for each term in post_tag taxonomy.
echo "Tags:
";

$args = array(
    'orderby'                  => 'name',
    'order'                    => 'ASC',
    'public'                   => true,
);

$tags = get_tags( $args );

foreach ( $tags as $tag ) {
     echo '' . $tag->name . '
';
}

TAXONOMIES
get_taxonomies ( ) Get a list of registered taxonomy objects.
echo "Taxonomies:
";

$args = array(
    '_builtin'                 => false,
    'public'                   => true,
);

$taxonomies = get_taxonomies( $args, 'objects' );

foreach ( $taxonomies as $taxonomy ) {
    echo '
' . $taxonomy->labels->name . '
';
}

POST TYPES
get_post_types ( ) Returns the registered post types as found in $wp_post_types. get_posts ( ) creates an array of posts based on a set of parameters so use it with your post_type_list.
echo "Post Types:
";

$args = array(
    'public'   => true,
    '_builtin' => false,
);
$output = 'names'; // names or objects, note names is the default
$operator = 'and'; // 'and' or 'or'
$post_types = get_post_types($args, $output, $operator);

// get all the posts for all post_types

$posts = get_posts(array(
                           'post_type'   => $post_types,
                           'numberposts' => - 1,
                           'orderby'     => 'post_type',
                           'order'       => 'ASC',
                           'post_status' => array( 'publish' ),
                           'public'      => true,
                       ));

foreach($posts as $post) {

    $link = get_permalink($post);
    $title = $post->post_title;

    if($post_type !== $post->post_type) {
        $post_type = $post->post_type;
        echo '

' . $post_type . '

';
    }

    // show link to post

    echo "
$title
";
}

TRANSIENT CACHING
If you want to cache the results of all these queries then consider the Transients API. This will store the result into the database for a limited time (which you ~request~). It's not a certain timeframe because plugins like WP Optimize can clear the cache anytime.
// check if the value exists using the key -- if it fails then we'll generate the content

if(false === ($trans_value = get_transient($trans_key = 'my_transient_key'))) {

    print_r('NO CACHE FOR ' . $trans_key); // (debug output)

    // start the output buffer to capture our generated content

    ob_start();

    // run your expensive operations -- data sent to the screen will be captured

    print_r('This is an expensive operation!');

    // using ob_get_clean we'll store the results and set the value variable.

    // double check the amount of time you want to keep the data cached
    // set to 0 for auto loading on every page hit.

    set_transient($trans_key, $trans_value = ob_get_clean(), 1 * MINUTE_IN_SECONDS);
}
else {
    print_r('THIS IS A CACHED RESULT FOR ' . $trans_key); // (debug output)
}

// value is ready and cached
print_r("
$trans_value
");

To clear the value just delete using the key.
delete_transient ( $trans_key );


text:
Q: How to gracefully shutdown a thread in C I have something like this:
DWORD WINAPI test(LPVOID lpParam) {
    while (1) {
        /*DO STUFF*/
    }
}

int main() {
    ...
    hThread = CreateThread(NULL,0,test,NULL,0,&dwThreadId);
    ...
}

How can i shutdown the Thread without TerminateThread()?
My first idea was creating a global variable (shouldshutdown = 0/1), set it in the main() when the Thread should shutdown. Then call ExitThread() in the Thread. Therefore i have to check for this variable in the while loop of the thread which is bad style i guess.

A: You an event that the thread can check to see if it needs to stop. For example (without error handling):
DWORD WINAPI test(LPVOID lpParam)
{
    HANDLE hEvent = (HANDLE)lpParam

    while (WaitForSingleObject(hEvent, 0) == WAIT_TIMEOUT)
    {
        /*DO STUFF*/
    }
}

int main() {
    hEvent = CreateEvent(NULL, TRUE, FALSE, NULL)
    hThread = CreateThread(NULL,0,test,(LPVOID)hEvent,0,&dwThreadId);
    // Do
    // Stuff
    // Tell the thread to exit
    SetEvent(hEvent)

    // Wait for the thread to exit
    WaitForSingleObject(hThread, INFINITE);
}

The general pattern is to give the thread some sort of alertable object that it can monitor and something else can set. In this case I've used a manual reset event. The while loop checks to see if the event has been signaled, and if not it does stuff. When it is signaled then WaitForSingleObject will return WAIT_OBJECT_0 and the loop will exit and you'll fall out of the thread function.
In the main function all you need to do after signalling the event is wait for the thread to exit.

A: If you need to send messages between your main thread and your worker threads - for example the work to do consists of tasks that you are placing on some queue, the simplest option might be to simply simply give the worker thread a message loop.
The PostThreadMessage API can be used to post WM_APP messages to the thread with tasks to perform, and a WM_QUIT message when the thread should exit. This saves you building your own thread safe signalling mechanisms.
It has the side benefit that, if your worker thread is instantiating COM objects, all you need to do is add an initial call to CoInitialize and the thread is a valid STA.

A: If you want to shutdown a thread you have two options:
1. Force the thread to terminate (with TerminateThread).
2. Ask the thread to shutdown (for this to work the thread has to cooperate).
If you choose the second option you have some choices about how to do it. One choice is to use a global flag to tell the thread to terminate (I'm not sure why you think that is bad style). The best choice will probably depend on what your thread is doing.