text:
Q: move xcode project causes red text (missing files from project) When I move iphone project directory to a new path.
There are some red texts indicate the missing files from the project source codes.
How to avoid these?

A: Here is how to locate the missing (red) files using the Xcode 4 interface:

*

*Select the file or files in the left hand Project Navigator (the folder icon)

*In the right sidebar click on "File Inspector" which is the leftmost icon resembling a page

*In the "Identity and Type" section, there is a grey box labeled "Location".

*Click on the small icon to the lower left that resembles a file browser - this will come up with a file browser to locate the file.

Voila, you are done.

A: I had the same problem, when I changed the permission on the files/folders to everyone read/write they then appeared in Xcode.

A: This worked on a Pod project. Quit XCode.
rm -rf project.xcworkspace/xcuserdata/*

Restart XCode and reopen project.

A: Xcode 7
1.) Right click on the red (missing) file.
2.) Select "Show File Inspector"
3.) Look at the right hand side of the screen under "Identity and Type" between "Location" and "Full Path"
4.) Click on the folder icon to the right of the file name.
5.) Navigate to the file's new location in the pop-up window and select the file.

A: I encountered this issue when copying my project from one mac to another.
The solution for me:
assuming your files are grouped (in folder)

*

*from xcode open the group in file inspector

*The group will probably be missing the absolute path.

*press the little icon nearby to pick the folder to associate the group with.

*restart xcode to see the changes.

A: *

*In Finder, create a duplicate of the project directory just in case all goes squiffy.

*In Finder, open the project directory that contains all the files with red references

*For all the red files you see in XCode, except the info.plist file (see step 5 below), highlight them in Finder and drag them from Finder to XCode's project navigator. i.e. import them.

*In XCode's "Choose options for adding these files" window: a) Select Copy items into Destination's group folder (if needed)
b) Select Create groups for any added folder
c) Select Add to Targets, and press Finish

*Highlight and drag the info.plist file from Finder to Project Navigator and repeat step 4 WITHOUT selecting Add to Targets

*If you had groups in Project Navigator (e.g. Supporting Files), reorder the files to be in the right places.

*Delete the original bad red references in Project Navigator, and Cmd-Shift-K to clean for good measure.

*Build and run on a device to remove the bad reference to the .app file

A: you just have to locate the missing file press in file icon in the identity and type  you will find the full path just locate your file where do you move it click the file icon

A: When you create these files be sure to save in your app directory. Or if you import classes from other project be sure to check the copy option.

A: I dont know if this is the main reason but when you are importing files to the application, do you mary the "Copy items in to destination group's folder (if needed)" ?
this make sure the file is not only referenced but added to your project folder and ir will move any where you move your project.

A: Did you move files in to folders directly in your project folder and not in xcode?

A: This worked on a Pod project.

*

*go into finder and project.

*right click on your project .xcworkspace and click show package contents

*right click on contents.xcworkspacedata and open with textEdit then make sure file path is correct. If project has been moved this can change

I also did this below but now sure if you need it
Quit XCode.
rm -rf project.xcworkspace/xcuserdata/*
Restart XCode and reopen project.

A: It's too simple to do :
Close the project that includes the missed files and open the Xcode, go to "Organizer">"Projects" and remove the project from the list there. Open your project from Finder and that's it.
hope this help.

A: If you create an Xcode project, then move the .xcodeproj file or the newly created project folder to a different folder using Finder, subsequent builds may show many missing files which still reference the original folder locations (which no longer exist because you moved them).  These missing files can appear as red text or as issues in the Issue Navigator.
This can happen when Xcode is configured to automatically add or remove files to/from source control (under Xcode > Preferences > Source Control).  When configured this way, simply creating a project in Xcode causes new project folders and files to be marked for addition to source control.  When you later move the project folder or .xcodeproj file these pending adds now point to missing files.
To resolve this issue when Subversion is the source control program, revert the pending adds for the phantom items from your local working copy folder.  In my case this requires dropping into a Terminal window, navigating to the parent of the phantom project folder, then reverting the automatic add, e.g.
cd /my-working-copy-folder
svn status --depth infinity
svn status --depth infinity existing-parent-folder/phantom-project-folder/
svn revert --depth infinity existing-parent-folder/phantom-project-folder/

Note that the first svn status command will list both missing files as well as properly added, modified or deleted files which you must take care to avoid reverting.  The second status command is "practice" for the final revert command, to ensure you've specified the proper path to revert.
I do not know git but I assume it offers corresponding commands.


text:
Q: Damage replacement plan / Insurance for Mac Book Pro? I used to own a Dell with a pretty beefy replacement plan.  When I bought my MBP, I asked if there was any similar coverage and the "genius" said no.  I search around online and found a company called Safeware, but it would be hard for me to believe that this would be the only company around doing this.
Does anyone own insurance like what Dell offers for their Mac?  Has anyone ever destroyed their computer and got a replacement?

A: Apple does not offer any insurance like that with Applecare. I think Dell only offers it because replacing a piece of equipment is ultimately really cheap for them, but Apple doesn't play Dell's game (and that is probably part of the reason why you purchased an Apple product).
Going by the fact that you are in the USA, I think this would depend on the type of damages for which you are seeking insurance, which you don't specify in your question. Renter's or home insurance would protect against theft from your home (rent or own, respectively). Damage incurred while being on the road would probably fall under some kind of business insurance, though I'd imagine you would pay a pretty hefty penny for that level of care no matter who you call.
I think your best course action would be to call your insurance company and see what they have to offer that best suits your particular needs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how to make single function here used two time In this code :
if (!parms.script) { // no script... load filename
            execscript(parms, function (data){
                var text={'result':'success', 'response':data };
                if(typeof(data)!='object') {
                    try {
                        text.response=JSON.parse(text.response);
                    } catch(e) {
                        text={'result':'success','response':data};
                    }
                }
                responsehttp.end(JSON.stringify(text));

            });
    } else {
        //parameterised input will replace in script
        if(query.paraminput!=undefined) {
            var paraminput=qs.parse(query.paraminput);
            parms=merge_options(parms, paraminput);
        }
        execscript(parms, function (data){
            var text={'result':'success', 'response':data };
            if(typeof(data)!='object') {
                try {
                    text.response=JSON.parse(text.response);
                } catch(e) {
                    text={'result':'success','response':data};
                }
            }
            responsehttp.end(JSON.stringify(text));

        });
    }

in execscript callback it is called two times , i want to make a single function for executing both call back in if and else .
how can i achieve this .
i tried making seperate function but responsehttp undefinded error camed.

A: The problem is (I suspect) is that you had your common function declared outside the context of your http response handler and, therefore, responsehttp wasn't defined.  Instead create it as a closure function inside your outer function's scope:
function someCallbackYouDontShowInYourQuestion(req, responsehttp) {
  // Declare your callback as a closure inside this function, so it
  // captures responsehttp state
  function callback(data) {
    var text={'result':'success', 'response':data };
    if(typeof(data)!='object') {
      try {
        text.response=JSON.parse(text.response);
      } catch(e) {
        text={'result':'success','response':data};
      }
    }
    responsehttp.end(JSON.stringify(text));

  }

  if (!parms.script) { // no script... load filename
    execscript(parms, callback);
  } else {
    //parameterised input will replace in script
    if(query.paraminput!=undefined) {
      var paraminput=qs.parse(query.paraminput);
      parms=merge_options(parms, paraminput);
    }
    execscript(parms, callback);
  }
}

A: callback = function (data){
            var text={'result':'success', 'response':data };
            if(typeof(data)!='object') {
                try {
                    text.response=JSON.parse(text.response);
                } catch(e) {
                    text={'result':'success','response':data};
                }
            }
            responsehttp.end(JSON.stringify(text));

        }

execscript(parms, callback);


text:
Q: Is it possible to deploy only Application Parameters (cloud.xml) in Service Fabric without having to change the Application version? Is there a possibility to deploy only Application Parameters (cloud.xml) somehow without having to redeploy the code or upgrade the application version? For example after deploying the Application on Service fabric cluster, there could be a minor thing I might need to change in one of the parameters in cloud.xml. And it won't make sense to upgrade the version of the Application for this minor change.
I have combed through various sites but did not find anything suitable.

A: I'd say - no, you can't do this. Here is what Service Fabric application upgrade says on this -

During an upgrade, Service Fabric compares the new application manifest with the previous version and determines which services in the application require updates. Service Fabric compares the version numbers in the service manifests with the version numbers in the previous version. If a service has not changed, that service is not upgraded.


text:
Q: Need help for package magento connect extensions I was reading this below article to create package from magento connect.
http://www.magentocommerce.com/wiki/7_-_modules_and_development/creating_magento_connect_extension_package
But I am confused at two points in this article.
First how can I find Dependencies for magento extention.
Second is that, one look on this image
http://www.magentocommerce.com/wiki/detail/general/contents2.jpg?id=7-_modules_and_development%3Acreating_magento_connect_extension_package&cache=cache
According to this article
Magento Community module file - ./app/code/community

And in the image they have used
Magento Community module file - Bloghome
"Bloghome" seems to be module directory than it is okay.
Magento User Interface (layouts, templates) - ./app/design

In the image they have used..
Magento User Interface (layouts, templates) - adminhtml/default/default/layout/bloghome_blog.xml
this also seems okay because this is layout xml file which is in /app/design directory
 Magento Local module file - ./app/code/local

But in the image they have used
Magento Local module file - frontend/base/default/layout/bloghome_blog.xml
Here 'Magento Local module file' is consider to be '/app/code/local' but here path is for '/app/design'. That is the point where I am confused.
Please guide why they have used 'Magento Local module file' for app/design layout xml file.
thank

A: About Dependencies - you have to know what additional library is using your module if using some. If your module is making connection with curl then you have to add curl dependency and so on. This is for Extensions. About Packages you can add Mage_Core_Modules and to specify Magento versions for which you tested your module. For PHP Version - if you used some specific things that are deprecated in the new versions you have to specify some older versions or the opposite - if you used some new features - you have to specify newer versions. If you are not sure which versions to fill in - you can use these from the example (I think they are okay most of the cases).
About the image/screenshot - it's wrong. For these files it should be Magento User Interface. Don't look at the image, read what is written.


text:
Q: How to Restore Previous Desktop Theme after Windows 10 1903 Upgrade I just installed the Windows 10 1903 Feature Upgrade.   My desktop is now a bright light blue.  I want the previous theme back.  I looked at themes and backgrounds, and there's very little there, and the previous option is gone.
Has anyone figured out how to get the previous desktop background back?  (The standard one, from pre-1903 Windows 10).
Thanks.


text:
Q: how to start using ormlite for android coding with a mac? Ok i know i might be flamed  for the noobness of this question but please pardon me! I'm trying to start using ORMLite for my android app but am at a loss even at their documentation. Seems like the documentation is quite abstract as well - I've downloaded the ormlite-android-4.2.3.jar and ormlite-core-4.2.3.jar but cannot run them with my Mac.
I've tried to google for how to set up ormlite but there is no relevant results all pointing to the same document pdf for ormlite. Is there any more detailed steps? How should I be doing it?  Any directions?  Thanks!

A: Ah I've found out how to use it, its by copying and pasting it into the project folder of your android app !
Just in case anyone want to find out how to start using ORMlite ! :)


text:
Q: How to use bluetooth in android and send data to other device I am developing an android application which will send the files to the mobile devices via bluetooth
please anyone can help me out about how to use the bluetooth on emulator for android

A: My experience is that the standard SDK emulator does not support bluetooth.  I ended up buying a used tablet for my bluetooth development.


text:
Q: difference between List and Publication List What is the difference between List and Publication List in Salesforce Marketing cloud??
List:
https://help.exacttarget.com/en/documentation/exacttarget/subscribers/lists/
publication list:
https://help.exacttarget.com/en/documentation/exacttarget/subscribers/publication_lists/

A: You can send to Lists directly.  Publication Lists are only associated with sends and can't be sent to directly.  Publication Lists are normally used for associating a Publication (campaign, segment, etc.) with a send to a Data Extension (DE).
SFMC maintains subscriber status for both.  So if you send to a DE, with an associated Publication List and the subscriber unsubscribes they'd only be unsubscribed from the Publication List (assuming they don't check the global opt-out checkbox).
Both show on the stock Preference/Subscription Center pages if they're marked as public.
"All Subscribers" is the master List.
Both are considered Lists when you're dealing with the API or the System Data Views.


text:
Q: Selecting a number of strings from a vector and passing it to a second vector to display? #include<vector>
#include<iostream>

using namespace std;
class BoxOfProduce
{
    private:
        vector<string>Produce={"Apples", "Peas","Lemons", "Tomatoes","Peaches","Garlic"};
        vector <string>box;//vector to hold the 4 strings
    public:
        BoxOfProduce(){}//default constructor

        void print()
        {
            for (auto& s : Produce) //displays all strings in vector
            {
                cout << s << " ";
            }
            cout<<endl;

        }
};

int main()
{
    BoxOfProduce Box;
    Box.print();//print function
}

Currently trying to figure out a way to pull four random strings from Produce to box. How can I randomize Produce and then send the strings to box?


text:
Q: Async/ Await test using Jest Enzyme Trying to run a test for the following code using Jest and Enzyme. The code is actually passing but not affecting its coverage. Just wondering what i could add into in order to work properly and increase test coverage
here is the function :
async getCurrencies() {
  const { user, services } = this.props;
  let types = response.body ? response.body.value : null;
  let response = await DropdownModels.getCurrencies({ user, services })
  let temp = types.map((type) => {
    return {
     label: type.Name,
     value: type.Currency1,
   }
  })
 this.setState({ CurrencyOptions: temp });
}

Here is my test case:
it ('Test getCurrencies function ',async() => {
 wrapper.setProps({
    user:{},
    serviceS:{},
  })
 wrapper.find('TransactionForm').setState({
    CurrencyOptions:[[]]
   });
 wrapper.update();
 await expect(wrapper.find('TransactionForm').instance().getCurrencies('test')).toBeDefined();
});

Also tried the following
const spy = jest.spyOn(wrapper.find('TransactionForm').instance(), 'getCurrencies');
await expect(spy).toBeCalled()

But get the following error using spy :
   expect(jest.fn()).toBeCalled()
   Expected mock function to have been called.

A: First of all, let's start with the basic concepts of writing tests.
What should I test?
All the lines of code should be tested so that achieve as high coverage as possible - ~100% for sure. On the other hand, the percentage might be unreliable in some cases.
Why should I deal with tests?
Tests help determine whether the previous implementations are broken due to the new functionalities. You just have to "press the button" instead of verifying it manually.
There're many other concepts both at the basic and high level, but let's try to keep this list brief and jump back into the details of the issue.

To stick with your example above, let me leave some observations.
it('Test getCurrencies function', async () => { ... });

This test description doesn't tell anything about the intention of this case. It tests the function, but how? What parts of the function does it cover? It's really difficult to answer these questions without specific details in the description.
const spy = jest.spyOn(wrapper.find('TransactionForm').instance(), 'getCurrencies');

I'm not sure what TransactionForm is, but according to the official documentation, it accepts the following parameters:
jest.spyOn(object, methodName)

Are you sure that wrapper.find('TransactionForm').instance() returns an object and also contains the getCurrencies function?
let response = await DropdownModels.getCurrencies({ user, services });

It's pretty odd - and also confusing - that DropdownModels also has a getCurrencies method. This might not be a problem, but I'd rather consider renaming it.

Finally, here are some example test cases that might be a good starting point in your case:
describe("getCurrencies", () => {
   it("calls `DropdownModels.getCurrencies` with `user` and `services` props", () => {
      // Don't forget to set the desired props as you did it in your samples.
      // Simply mock `DropdownModels.getCurrencies` with `jest.spyOn`.
   });

   it("sets `temp` into the state", () => {
      // Test whether the expected data is set into the state.
   });
});


text:
Q: Issue with gradle job in jenkins with JDK 1.8 I am able to run gradlew test clean in the command prompt where Jenkins is running. When I use Gradle Wrapper and run clean test in Jenkins, the job is failing with:
   Execution failed for task ':compileJava'.
   > invalid source release: 1.8

My wrapper is using gradleVersion = 1.10 and the gradlew -v shows the following:
  C:\Program Files (x86)\Jenkins\jobs\CDS-UnitTest\workspace>gradlew -v

  ------------------------------------------------------------
  Gradle 1.10
  ------------------------------------------------------------

  Build time:   2013-12-17 09:28:15 UTC
  Build number: none
  Revision:     36ced393628875ff15575fa03d16c1349ffe8bb6

  Groovy:       1.8.6
  Ant:          Apache Ant(TM) version 1.9.2 compiled on July 8 2013
  Ivy:          2.2.0
  JVM:          1.8.0_05 (Oracle Corporation 25.5-b02)
  OS:           Windows Server 2012 R2 6.3 amd64

I'm not able to figure out why it is failing in Jenkins for JDK 1.8 while it works in the command line.
Jenkins console:
 [workspace] $ cmd.exe /C '""C:\Program Files (x86)\Jenkins\jobs\CDS-UnitTest\workspace\gradlew.bat" -DSOURCE_BUILD_NUMBER=14 clean test && exit %%ERRORLEVEL%%"'
 ...

 FAILURE: Build failed with an exception.

 * What went wrong:
 Execution failed for task ':compileJava'.
 > invalid source release: 1.8


text:
Q: Get-ADUser properties in specific order to export into CSV Semi-Newbie here.  I'm trying to use Get-ADUser to display user information in a specific order.  It appears Get-ADUser property listing has a default order that is not intuitive for our needs.  So far I have;
$Users = Get-ADUser -Filter * -SearchBase $treeview.SelectedNode.Name -Properties Name, CN, SamAccountName, DisplayName, sn, GivenName, Initials, `
OtherName, mail, EmailAddress, EmployeeNumber, Company, StreetAddress, POBox, City, State, PostalCode, Country, Department, HomePhone, `
telephoneNumber, OfficePhone, MobilePhone, Fax, info, physicalDeliveryOfficeName, Title, Office, EmployeeID, Description, DistinguishedName, `
CanonicalName, AccountExpirationDate, Created, Enabled, HomeDirectory, HomeDrive, HomePage, LastLogonDate, LockedOut, logonCount, Manager, `
Modified, msNPAllowDialin, ObjectClass, objectSid, PasswordLastSet, UserPrincipalName, whenChanged |
Select-Object Name, CN, SamAccountName, `
DisplayName, sn, GivenName, Initials, OtherName, mail, EmailAddress, EmployeeNumber, Company, StreetAddress, POBox, City, State, PostalCode, `
Country, Department, HomePhone, telephoneNumber, OfficePhone, MobilePhone, Fax, info, physicalDeliveryOfficeName, Title, Office, EmployeeID, `
Description, DistinguishedName, CanonicalName, AccountExpirationDate, Created, Enabled, HomeDirectory, HomeDrive, HomePage, LastLogonDate, `
LockedOut, logonCount, Manager, Modified, msNPAllowDialin, ObjectClass, objectSid, PasswordLastSet, UserPrincipalName, whenChanged `
| Export-Csv -NoTypeInformation -Path $LogFile

Although the below code works fairly quickly (4 sec. for 1758 users), this seems a bit long winded and I'm sure there are more efficient methods.  I've looked into hash tables but even that is as long as above doubling the effort.

A: If we are to follow Lee_Dailey's advice, you can store the properties you want to filter into an array variable. Then pass that variable into the -Property/-Properties parameters.
$properties = "DisplayName","sn","GivenName","Initials","OtherName","mail","EmailAddress","EmployeeNumber","Company","StreetAddress","POBox","City","State","PostalCode","Country","Department","HomePhone","telephoneNumber","OfficePhone","MobilePhone","Fax","info","physicalDeliveryOfficeName","Title","Office","EmployeeID","Description","DistinguishedName","CanonicalName","AccountExpirationDate","Created","Enabled","HomeDirectory","HomeDrive","HomePage","LastLogonDate","LockedOut","logonCount","Manager","Modified","msNPAllowDialin","ObjectClass","objectSid","PasswordLastSet","UserPrincipalName","whenChanged"

$Users = Get-ADUser -Filter * -SearchBase $treeview.SelectedNode.Name -Properties $properties |
    Select-Object -Property $properties


text:
Q: using Inflate with a null parent viewGroup is discouraged ,strange exception in Xamarin Android +MVVM Cross I am new to Xamarin development.I know following question is a well known problem and discussed in lot of forums.But i couldn't find an exact solution for this problem.So please note that this is not a duplicate question.
I am trying to add a fragment to an android Layout.I am getting the following exception when i inflate the fragment.
"using Inflate with a null parent viewGroup is discouraged - see https://github.com/MvvmCross/MvvmCross/issues/507"

I have checked the given Url which is attached with the exception. Actually there is no an overloaded method for "Binding Inflate" in the assembly which i am using. At this moment i can only access a method which has only two input parameters(Layout,View group) .The issue in Github was closed and noted that this exception is no longer in latest MVVM cross (3.1.1) .But still getting the same exception in the latest stable version.Mvvm Cross 3.1.2 beta has an overloaded method with three parameters where we can pass a Boolean value if the view group is null .But I am getting the same exception even I pass a false for last parameter.What is the wrong i am doing here?Can any one help me out?
Activity
[Activity(Label = "HomeView", MainLauncher = true)]
public class HomeView : MvxFragmentActivity
{
//Fragment
private HomeFragment _homeFragment;

    public new HomeViewModel ViewModel
    {
        get { return (HomeViewModel) base.ViewModel; }
    }

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);
        SetContentView(Resource.Layout.HomeView);
        this.AddFragment(_homeFragment);
    }

    protected override void OnViewModelSet()
    {
        base.OnViewModelSet();
        //Create the Home Fragment
        _homeFragment = new HomeFragment {ViewModel = ViewModel};

    }

    //Add the Fragments to View
    private void AddFragment(MvxFragment fragment)
    {
        var fragmentTrasaction = SupportFragmentManager.BeginTransaction();
        fragmentTrasaction.Replace(Resource.Id.HomeContainer, _homeFragment);
        fragmentTrasaction.Commit();
    }
}

Fragment
public class HomeFragment : MvxFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
var ignore = base.OnCreateView(inflater, container, savedInstanceState);
return this.BindingInflate(Resource.Layout.HomeFragment, null);//Here i am getting the exception
}
}

Activity Layout
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res/Test.Droid"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:minWidth="25px"
android:minHeight="25px">
android:id="@+id/HomeContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />

Fragment Layout
<?xml version="1.0" encoding="utf-8"?>
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:local="http://schemas.android.com/apk/res/Test.Droid"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
android:text="Home"
android:layout_width="wrap_content"
android:layout_weight="1" />

MVVM packages which I am using
"MvvmCross.HotTuna.CrossCore" version="3.1.1" targetFramework="MonoAndroid42"
"MvvmCross.HotTuna.Droid.Fragging" version="3.1.1" targetFramework="MonoAndroid42"
"MvvmCross.HotTuna.MvvmCrossLibraries" version="3.1.1" targetFramework="MonoAndroid42"
"MvvmCross.HotTuna.Plugin.Json" version="3.1.1" targetFramework="MonoAndroid42"
"MvvmCross.HotTuna.StarterPack" version="3.1.1" targetFramework="MonoAndroid42"
"MvvmCross.PortableSupport" version="3.1.1" targetFramework="MonoAndroid42"
"Xamarin.Android.Support.v4" version="20.0.0" targetFramework="MonoAndroid42"

Thanks in Advance

A: I was looking at debug trace.Actually there was an exception which is not handled at on Create method since oncreate doesn't have the Try Catch block.Actually exception was "Binary XML file line #1: You must supply a layout_height attribute" .I didn't put the height for Text box which is inside the Fragment.Now it is fixed.

A: You seem to have found the issue, here but you should still not pass a null parent into the inflator. If you do then any theme settings etc you put on the parents are not going to effect the view you inflate. Instead pass false as a third argument so that the view doesn't get attached to the parent, but does get the options from it.


text:
Q: What is the BIOS key for lenovo G500? I am trying to enable intel VT through BIOS but can't access.
I read that the small button next to power button can be used but a system restore is needed ...
Is it safe or is there any other way to enter the BIOS?

A: This answer was provided by ParrotMac in the  comments to the question.  His answer probably saved me a few minutes of searching all around for the right Function key to enter the bios, therefore I think his answer deserves to be in the answers provided.
The Lenovo G500 actually provides a small button just to the right of the power button with a curving arrow on it.  First shutdown the machine and then press the button.  The machine will turn on and you'll be able to choose between:
- Normal Start up
- BIOS
- Boot Sequence
- System Recovery
Or, in the words of ParrotMac:

Newer Lenovos have a very small button that's usually somewhat recessed... From an off state, simply press this button and your computer will either boot to the BIOS, or to a menu allowing you to choose the BIOS

A: Take a look at this site: there are mostly the keys F1, F2, Ctrl+Alt+F11* or " Access IBM "
And yes, it is safe to try all of them out :)

A: Try to do it.
Lenovo (formerly IBM)
ThinkPad, IdeaPad, 3000 Series, ThinkCentre, ThinkStation
Press F1 or F2 after powering on the computer.
Older Lenovo products allow access to BIOS using Ctrl+Alt+F3, Ctrl+Alt+Ins, or Fn+F1.
Source: http://pcsupport.about.com/od/fixtheproblem/a/biosaccess_pc.htm


text:
Q: C# - Implementing Enum / Combobox I have a local database for a system / application I'm doing.
Within this DB I have Books & Category Columns - CategoryID also makes part of the Books table as a Foreign Key, and I have 10 Category Records, for book genre, like 'Comics' (ID: 1), 'Crafts' (ID: 2), 'Education' (ID: 3), etc.
I am currently implementing an Add Book Record function in the application, so that when I save, a new book record is inserted in my DB with the details given, however, for CategoryID (in Books table), I can only input integers, which I don't want (as explained below)
(BTW, apologies but I'm still a coding newbie)
I have seen some tutorials on Enums, but I can't seem to find anything on how to combine an Enum with a combobox.
What I want is to have the combobox show something like:
1 - Comics,
2 - Crafts,
3 - Education,
etc.
The above combobox dropdown list would point out to (for example) '1 - Comics' for CategoryID: 1, '2 - Crafts' for CategoryID: 2, and so on.
This is what I currently have outside of the Add New Record button
public partial class AddBookRecordForm : Form
{
    public AddBookRecordForm()
    {
        InitializeComponent();
    }

    enum BookCategory
    {
        Comics = 1,
        Crafts = 2,
        Education = 3,
        History = 4,
        Entertainment = 5,
        Thriller = 6,
        Religion = 7,
        Romance = 8,
        Fantasy = 9,
        Sports = 10
    }

Not sure how to proceed now - I'm assuming that the next part of code would need to be implemented within the Save Button Code.
For Reference, the below is the DB connection I did within the Save Button method.
 string ConnectionString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=
 C:\Program Files\Microsoft SQL
 Server\MSSQL14.SQLEXPRESS\MSSQL\DATA\Library System Project.mdf
 ;Integrated Security=True;Connect Timeout=30";

        string Query = "insert into Books (BookName, BookAuthor, CategoryID, ClassificationID, BookAvailabilityQuantity, Price) values ('" + this.txtName.Text.Trim() + "','" + this.txtAuthor.Text.Trim() + "','" + this.txtCategory.Text.Trim() + "','" + this.txtClassification.Text.Trim() + "','" + this.txtAvailabilityQuantity.Text.Trim() + "','" + this.txtPrice.Text.Trim() + "');";

        SqlConnection DBCon = new SqlConnection(ConnectionString);
        SqlCommand DBCommand = new SqlCommand(Query, DBCon);
        SqlDataReader DBReader;

        try
        {
            DBCon.Open();
            DBReader = DBCommand.ExecuteReader();
            MessageBox.Show("New book record added to the system.", "Library System", MessageBoxButtons.OK);

            while (DBReader.Read())
            {

            }
        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

        finally
        {
            // *** If you're going to be opening a connection be sure to close it ***
            // *** Finally blocks work well for this ***
            DBCon.Close();

            this.txtName.ResetText();
            this.txtAuthor.ResetText();
            this.txtCategory.ResetText();
            this.txtClassification.ResetText();
            this.txtAvailabilityQuantity.ResetText();
            this.txtPrice.ResetText();
        }
    }

A: For simplicity I would suggest this as my quick soluction.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    enum BookCategory
    {
        Comics = 1,
        Crafts = 2,
        Education = 3,
        History = 4,
        Entertainment = 5,
        Thriller = 6,
        Religion = 7,
        Romance = 8,
        Fantasy = 9,
        Sports = 10
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        var values = Enum.GetValues(typeof(BookCategory));

        var dataSource = new List<BookCategoryData>();

        foreach (var bookCatergory in values)
        {
            dataSource.Add(new BookCategoryData() { Id = (int)bookCatergory, Name = bookCatergory.ToString() });
        }

        comboBox1.ValueMember = "Id";
        comboBox1.DisplayMember = "Name";
        comboBox1.DataSource = dataSource;

    }

    private void ComboBox1_SelectedIndexChanged(object sender, EventArgs e)
    {

    }
}

public class BookCategoryData
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Also as metioned here for other members please take a look on SQL Injection and use Sql Parameters in order to use concatenated text. Your code will looks like something below:
string query = "insert into Books (BookName, BookAuthor, CategoryID, ClassificationID, BookAvailabilityQuantity, Price) " +
"values (@BookName, @BookAuthor, @CategoryID, @ClassificationID, @BookAvailabilityQuantity, @Price)";

SqlCommand command = new SqlCommand(query, connection);
command.Parameters.Add("@BookName", this.txtName.Text.Trim());


text:
Q: DirectX & Oculus setup inside Visual Studio, main, precompiled headers, linker and files Goal: I'm trying to develop my first simple Oculus rift application using visual studio.
Background: Computer Engineer/programmer of arbitrary languages-rusty at C++/very rusty at visual studio/inexperienced with 3D balls to the wall programming.
DirectX Progress: I found this excelent tutorial (http://3dgep.com/introduction-to-directx-11/) and I rebuilt it walking thru the code; this taught me a lot. My code never actually would run though, likely an issue with linkers or precompiled headers, so I reverted back to the original Demo File.
Oculus Progress: I've learned a lot about using the LibOVR, successfully compiled my first program which was to gather sensor data. Never ran it though.
Visual Studio: I currently have one solution setup, with two projects (DirectXTemplate and LibOVR). I'm thinking I should merge the two projects and turn the DirectXTemplate into a library so I can access all the functions defined in these files (though I will likely need to modify them as development progresses). How do I go about doing this? Is this the right thing to do?
I also have some general questions:

*

*List item
Projects/Solutions: what is the difference and how should I lay things out to achieve my goal?

*List item
My winAPI main function is in my own cpp file, it calls functions from directXtempalte... most of these are working except the LoadContent function fails about half way thru, I think due to the shaders. I'm really confused about the shaders in the tutorial, particularly walking about at compile time vs. at run time shaders and suspect its an issue with the Linker, precompiled headers, include directories or something like that. There are so many views of the properties tab in VS its causing more confusion and errors. So my real question here is how do I control this better? I mean, the properties window changes depending on what project/solution/file I select and it also changes based on the mode selected in the properties window... getting the properties window right for all these objects has proven to be a highly error prone process requiring iterative trial and error... this really really sucks and wastes tons of time... How can it be avoided?

*List item
How do I turn the directX template in to a library like the LIBOVR and should I? Keep in mind the directX template/library will be updated massively as the project progresses but LIBOVER will not be. When all things are done, I'll be using the LIBOVR functions for to deal with the oculus (this is static but is updated by the Vendor) and DirectXTemplate/Library functions to deal with direct X (this will be custom build, using the template as the starting point.


text:
Q: Stuck without Qt4 in Ubuntu 20.04 I just upgraded to Ubuntu Focal Fossa and found that the lack of Qt4 means it isnt possible to build antimicro
I noticed this post saying it would work with libqt4-dev, and I'm sure would as it compiled fine on earlier versions of Ubuntu.
Is there any way to install Qt4 on Focal Fossa?
With Qt5 it reaches 100%, but fails at 100% and gives lots of errors:
Scanning dependencies of target antimicro_autogen
[  1%] Automatic MOC for target antimicro
[  1%] Built target antimicro_autogen
[  2%] Generating qrc_resources.cpp
[  2%] Generating ui_mainwindow.h
[  3%] Generating ui_axiseditdialog.h
/home/...../Desktop/antimicro-master/src/axiseditdialog.ui: Warning: Z-order assignment: '' is not a valid widget.
/home/...../Desktop/antimicro-master/src/axiseditdialog.ui: Warning: Z-order assignment: 'verticalSpacer' is not a valid widget.
/home/...../Desktop/antimicro-master/src/axiseditdialog.ui: Warning: Z-order assignment: 'verticalSpacer_2' is not a valid widget.
[  4%] Generating ui_advancebuttondialog.h
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: 'verticalSpacer_5' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: '' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: 'verticalSpacer_6' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: 'verticalSpacer_2' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: '' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: 'verticalSpacer' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: '' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: 'verticalSpacer_4' is not a valid widget.
/home/...../Desktop/antimicro-master/src/advancebuttondialog.ui: Warning: Z-order assignment: '' is not a valid widget.

[100%] Linking CXX executable bin/antimicro
/usr/bin/ld: CMakeFiles/antimicro.dir/src/main.cpp.o: in function `QtPrivate::MetaObjectForType<JoyButtonSlot*, void>::value()':
main.cpp:(.text._ZN9QtPrivate17MetaObjectForTypeIP13JoyButtonSlotvE5valueEv[_ZN9QtPrivate17MetaObjectForTypeIP13JoyButtonSlotvE5valueEv]+0xb): undefined reference to `JoyButtonSlot::staticMetaObject'
/usr/bin/ld: CMakeFiles/antimicro.dir/src/main.cpp.o: in function `QtPrivate::MetaObjectForType<SetJoystick*, void>::value()':
main.cpp:(.text._ZN9QtPrivate17MetaObjectForTypeIP11SetJoystickvE5valueEv[_ZN9QtPrivate17MetaObjectForTypeIP11SetJoystickvE5valueEv]+0xb): undefined reference to `SetJoystick::staticMetaObject'
/usr/bin/ld: CMakeFiles/antimicro.dir/src/main.cpp.o: in function `QtPrivate::MetaObjectForType<InputDevice*, void>::value()':

collect2: error: ld returned 1 exit status
make[2]: *** [CMakeFiles/antimicro.dir/build.make:1804: bin/antimicro] Error 1
make[1]: *** [CMakeFiles/Makefile2:165: CMakeFiles/antimicro.dir/all] Error 2
make: *** [Makefile:130: all] Error 2

Any help much appreciated!

A: It is simply available with actual Qt5 dependency in the universe pocket for focal. Install with:
sudo add-apt-repository universe
sudo apt-get install antimicro


text:
Q: Where are passwords stored? How do you figure out where are user's passwords stored, for users that can login? I know the system is using LDAP for users (username, home path, etc.), but it doesn't contain any kind of passwords. I have access to a configured machine, so how do I figure out where are passwords? (which config file?)

A: Passwords aren't stored themselve. They are transformed by a function, and the so produced value, which is called hash, is stored.
If you login, the same function is performed on your input, and the generated value compared with the one in the stored value in the /etc/shadow file.
The function is of a kind, which is hard to invert. So with the value in /etc/shadow, you can not calculate the original password, and the key in there is not helpful for login - you need the password.
With brute force, you can try to generate such a password, and for common names like 123456, password, asdf, secret, 1111 and so on, the shadow-values are already well known, and stored in so called rainbow-tables.
To prevent attacks with rainbow-tables, the password-function can use a salt, which influences the result, which means that every password uses a different salt, stored in the first two bytes of the password hash string (thanks to psusi, who corrected me), so that you would need a different rainbow-table for every password, which is not very practical - it takes too long to generate them, and is expensive.
I'm not sure, whether ubuntu uses a salt. We can wait for somebody who explains it to us, or you could generate the same user with the same password on two machines, and compare the value in /etc/shadow.

A: The passwords (or better hashes) are most probably stored in the LDAP server. "Most probably" means that you could have a very strange setup where they are not. LDAP configuration is very flexible, but that also means that without inspecting the config files a clear answer on how it is done in your situation cannot be given. You probably have looked into /etc/ldap.conf on the client for details of the configuration?
One possible setup for LDAP authentication is like this: the client box takes username and password from the login, and performs a bind to the LDAP server with this information. The LDAP server verifies username & password and either returns success or failure. In this setup, the client box never sees the stored password hash from the LDAP server.
Do you know the type of LDAP server used? Whether you can see the hashed user passwords depends on the setup of the LDAP server. See as an example http://www.faqs.org/docs/securing/chap26sec213.html on what you could configure on an OpenLDAP server.
The answer on password hashing from "user-unknown" is correct, it is only that the hashes are not stored in /etc/shadow but in the LDAP server. The hashing itself might also be performed by the LDAP server and not the client box.

A: Did you try
- phpldapadmin?
- ldapsearch -LLL -x -b "dc=your,dc=domain" uid=* (or replace * by username, maybe it's cn instead of uid)
If the passwords are stored within ldap, you should see them with this methods.

If the computer is a domain controller, maybe it has smbldap-tools installed, so you can just reset passwords with smbldap-passwd username

You might also want to check your pam.d config (/etc/pam.d/common-*) to find out what login mechanism your computer is using.


text:
Q: How to generate and load test data in amazon RDS for Oracle For a POC, we need 10 GB of data to be available in Oracle RDS instance. Any test data is ok ( like TPC for benchmarking ) , for this requirement is there any specific way to create database and pump the sample data ?

A: Assuming you have opened the firewall port 1521 to the RDS server, you should be able to use sqlplus, sqlci, sqlldr to connect to the RDS instance as follows:
USER/PASSWORD@//hostName:port/SID
e.g.
sqlplus scott/tigerD@//myhost.this.that.amazon.com:1521/THE_SID
Once you prove this works, use this in the tools to squirt data into the RDS instance.
E.g. .sql INSERT scripts, sqlldr scripts etc.


text:
Q: How to hide div content but leave some content in JQuery I have a div like this:

This content should remain
 The rest of this content needs to be hidden (Faded out)

I can't change the actual structure of the HTML.

A: Use the visibility CSS attribute:
$('.someDiv').css('visibility','hidden')
    .find('span').css('visibility','visible');

http://jsfiddle.net/mblase75/WtMea/
I don't think it's possible to fade the outer div without also fading everything inside of it, but  visibility can be overridden.

A: I would do something like this:
$('.someDiv').append('</span').find('#fade').html($('.someDiv').contents().filter(function(){ return this.nodeType == 3; })).fadeOut(1000);

Fiddle : http://jsfiddle.net/adeneo/gdNue/1/


text:
Q: Virtual inheritance and function members Let's consider the following code snippet:
struct A { void f(); };
struct B : virtual A {};
struct C : virtual A {};
struct D : B, C {};

What can I say? that D has two different member functions B::A::f and C::B::f which are called over a same object? or they are just aliases of a same member function?
For example, for the non-virtual case,
struct A { void f(); };
struct B : A {};
struct C : A {};
struct D : B, C {};

D has two different member functions B::A::f and C::A::f because they just have different names, so, calling D().f() is an ambigüity because I have to specify to which member I want to call.
However, in the virtual inhericante case, that isn't required anymore because calling by one path or another resolves to call the function over a same object, and I don't know anymore if, in the virtual inheritance case, I have two different member functions which resolves or are executed over a same object, or they are just aliases of a same member function.
Anyway, from a practical point of view that difference doesn't matter, but from a more formal point of view I'm not sure about what to say.

A: In the virtual inheritance case you have D::A::f() and no specific overridden versions in the two middle inheritance levels.
D().B::A::f() works for the same reason that it works in this straightforward case (it inherits the parent version):
struct A { void f(); };
struct B : A {};
struct D : B {};


text:
Q: How to start activity on item selected? I created a drop-down menu and i overrided the onItemSelected method:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String item = parent.getItemAtPosition(position).toString();

    Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();
}

With the above code if i select an item then it shows a toast with selected item.
I tried to edit the code in this way:
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
    String item = parent.getItemAtPosition(position).toString();

    Toast.makeText(parent.getContext(), item, Toast.LENGTH_LONG).show();

    Intent intent = new Intent(Selection.this, MainActivity.class);
    startActivity(intent);
}

Why it doesn't allow me to select an item and go to MainActivity instead?

A: slm;according to the docs :
"Spinners provide a quick way to select one value from a set.In the
default state, a spinner shows its currently selected value. Touching the spinner displays
a dropdown menu with all other available values, from which the user can select a new one."
so it's normal to trigger the callback on the first item shown in your list and implement
it;;you  can handle that by ignoring the first callback and put the first item shown in two
different positions.OR see more in this link " How to keep onItemSelected from firing off on a newly instantiated Spinner? ".


text:
Q: Having issues understanding the notion of 2D volume in Measure Theory. So the exercise I'm trying to solve goes like this:
P ⊂ $R^2$ is the interior of a parallelogram defined by its' corners coordinates:
(-2,1), (-1,3), (-3,3), (-4,1)
I need to find out $vol_2 (P)$
Now I found somewhere in a book that if the set I'm looking at is
$P=[a_1,b_1] \times [a_2,b_2]  \times ... \times [a_n,b_n]$ ⊂ $R^n$
then
$vol_n (P)$=$|b_1-a_1| |b_1-a_1|...|b_n-a_n|$
And I believe this finding may prove to be useful in what I need to solve, but I fail to identify the terms $[a_1,b_1]$ and $[a_2,b_2]$ in my scenario. Also, I don't really understand the concept of having a volume if this is a 2 dimensional figure.


text:
Q: How to implement what I call a "wraparound sort" around an arbitrary value in C++? Given a vector of ints, I would like to implement what I am calling in my mind a "wraparound sort."  Basically, given an arbitrary value, all of the values greater than or equal to that value are listed first in ascending order, and than all values less than the arbitrary value, again in ascending order.  For a value of 12, a wraparound sorted array would look like:
[13, 15, 18, 29, 32, 1, 3, 4, 8, 9, 11]

What would be a way to implement such a sort?  I am fine assuming as a starting point a vector that is already sorted in ascending order without the wraparound characteristic, since it's easy enough to get to that state, if such an assumption is useful.

A: You can do this combining std::partition and std::sort.  std::partition will split the vector around the partition point and then you can use std::sort to sort both halves.  That would look like
int main()
{
    std::vector vec = {1,3,4,8,9,11,13,15,18,29,32};
    // all elements >= 12 come first, return value is end iterator of that set
    auto front_end = std::partition(vec.begin(), vec.end(), [](auto elm){return elm >= 12;});
    // sort first half
    std::sort(vec.begin(), front_end);
    // sort second half
    std::sort(front_end, vec.end());
    for (auto e : vec)
        std::cout << e << " ";
}

which outputs
13 15 18 29 32 1 3 4 8 9 11

From PaulMcKenzie's comment you can reduce the code size a little bit by using std::stable_partition on a sorted vector.  That would look like
int main()
{
    std::vector vec = {1,3,4,8,9,11,13,15,18,29,32};
    // sort the vector
    std::sort(vec.begin(), vec.end());
    // all elements >= 12 come first in the order they had in the sorted vector
    std::stable_partition(vec.begin(), vec.end(), [](auto elm){return elm >= 12;});
    for (auto e : vec)
        std::cout << e << " ";
}

It should be noted that std::stable_partition does try to do an allocation to be as efficient as std::partition and if it can't do that then it falls back to a less efficient O(NlogN) algorithm.

A: You can use lower_bound and rotate on the sorted array:
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    int pivot = 12;
    std::vector<int> vec = {1,3,4,8,9,11,13,15,18,29,32,12};

    // sort the array
    std::sort(vec.begin(), vec.end());

    // find the first element >= the pivot
    auto it = std::lower_bound(vec.begin(), vec.end(), pivot);

    // rotate so that it's in the first position
    std::rotate(vec.begin(), it, vec.end());

    for (auto v : vec)
        std::cout << v  << " ";
}

or you can use sort with a custom comparator:
#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    int pivot = 12;
    std::vector<int> vec = {1,3,4,8,9,11,13,15,18,29,32,12};

    std::sort(vec.begin(), vec.end(), [pivot](int lhs, int rhs) {
        if ((lhs <= pivot && rhs <= pivot) || (lhs > pivot && rhs > pivot))
        {
            // on the same side wrt pivot -> true if lhs is smaller than rhs
            return lhs < rhs;
        }
        // either (lhs <= pivot) && (rhs > pivot)
        // or (lhs > pivot) && (rhs <= pivot)
        // -> true if rhs is smaller than lhs
        return rhs < lhs;
    });

    for (auto v : vec)
        std::cout << v  << " ";
}


text:
Q: How to send byte string as header value in cpprestsdk (C++ REST SDK) I am trying to send encrypted string (byte data) as header value using cpprestsdk..
I realize that it is not able to understand encrypted byte string as header value and gives me the error:  Error: 87 : WinHttpAddRequestHeaders: 87: The parameter is incorrect.
Encrypted string e.g: "«ZáqÏkGk"«ZáqÏkGkr\bør6\x18¤Å(ˆ™HŽB\af=6«ŠÄäi\x1aì"
Now my question is, is there any other way to encode the encrypted string so that it will send the headers across to the server?
I am using AES encryption to encrypt plain text for the header value. I need to send the data in encrypted format to the server and not as plain text and it needs to be sent in the header.
Can anyone throw light on whether there is any way to send the encrypted byte string in header ?


text:
Q: How to squash a div vertically in center? I need to squash a div in vertically, using css3, the div need to have 100% width to fit in full window, but i don't know how. Thanks.
http://i.stack.imgur.com/vqUs8.png

A: (Updated, due to the request with an image behind the <div>)
A possible way if the background has only one color (white in this case)
div {
    background-color: #000;
    height: 200px;
    margin: 40px 0 0;
    position: relative;
    overflow: hidden;
    width: 100%;
}

div::before,
div::after {
    border-radius: 140px / 20px;
    content: "";
    display: block;
    height: 100px;
    position: absolute;
    width: 100%;
}

div::before {
    box-shadow: 0 50px 0 10px #FFFFFF inset;
    bottom: -80px;
}

div::after {
    box-shadow: 0 -50px 0 10px #FFFFFF inset;
    top: -80px;
}

http://jsfiddle.net/kmjLqrq2/
The css above uses two pseudoelements to make two ellipses above the <div>.
The problem now, if we have a background-image hiding behind the <div> is that our two ellipses will overlap our image.
Enter radial-gradient:
We can change our two pseudoelements now and give them an transparent ellipse as a background-image which will "fade" to black.
div::before,
div::after {
    background-size: 100% 50px;
    background-repeat: no-repeat;
    content: "";
    display: block;
    height: 25px;
    position: absolute;
    width: 100%;
}

div::before {
    background-image: -webkit-radial-gradient(center center, ellipse cover, rgba(0,0,0,0) 75%, #000 76%);
    background-position: center bottom;
    top: -25px;
}

div::after {
    background-image: -webkit-radial-gradient(center center, ellipse cover, rgba(0,0,0,0) 75%, #000 76%);
    background-position: center top;
    bottom: -25px;
}

http://jsfiddle.net/kmjLqrq2/1/
(Note that the example above is only for Webkitbrowsers to keep it simple, please remember to use all vendor prefixes)


text:
Q: What is the search scope of CDI in case of injectable bean lookup? I have a multi module maven project (a Java EE app with ear, persistence, web, ejb, api, bl and other modules), where I'd like to use Weld CDI.
When I try to inject a bean, where will Weld search for injectable beans? Will Weld search in all the modules, where a beans.xml is placed to WEB-INF or META-INF regardless from their dependencies (or dependencies matter somehow?), or will Weld be able to inject a bean from an other deployment? I tried to find a document, which describes the mechanism and boundaries of bean lookup, but I haven't found anything yet.

A: What you're describing is part of the overall EE spec, not the CDI spec.  but yes, in general the contents of your EAR will be discovered as distinct applications (per the EE spec).  This means that you may not be able to access individual beans across JARs.  It is highly recommended to use WAR deployment with CDI.


text:
Q: Google Analytics Funnel Visualization Not Reporting Magento OnePage Checkout Process Correctly I'm running a Magento website which uses the OnePage checkout method. I've added the following script to /app/design/frontend/< my site >/template/checkout/onepage.phtml:-
<script type="text/javascript">
Checkout.prototype.gotoSection = function(section) {
try {
_gaq.push(['_trackPageview', 'checkout/onepage/' + section]);
} catch(err) { }
section = $('opc-'+section);
section.addClassName('allow');
this.accordion.openSection(section);
};
</script>

and I've set up within Google Analytics a goal which does the following:-
Goal URL: /checkout/onepage/success/
Match Type: Head Match
Step 1: /checkout/cart/ - Cart
Step 2: /checkout/onepage/ - Login or Register
Step 3: /checkout/onepage/billing - Billing Address
Step 4: /checkout/onepage/shipping - Shipping Address
Step 5: /checkout/onepage/shipping_method/ - Shipping Method
Step 6: /checkout/onepage/payment/ - Payment Details
Step 7: /checkout/onepage/review/ - Review

The issue I'm having is that whilst goal conversions are being correctly reported I receive incorrect reporting results via the funnel visualization such as /checkout/onepage/billing appearing at the Login or Register stage which means I'm losing data after this stage as to where people have exited. Can anyone help please?

A: This is my current setup that work without any issues


text:
Q: Why reading integers from file into a 2d vector is resulting all values to be zero? I am trying to read a matrix of integer values from a text file into a 2d vector.
Input Data:

4 5
0 -0.5 -3 -1 -4
40 1 1 1 1
10 -2 -1 1 1
10 0 1 0 -1

My code:
    ifstream InFile("Simplex_EX1.txt");

    if (!InFile.is_open())
        cout << "File could not be opened correctly";

    vector<vector<int>> MyData;
    int Rows, Columns;
    InFile >> Rows >> Columns; // read first line - working

    MyData.resize(Rows);
    for (int i = 0; i < Rows; i++)
        MyData[i].resize(Columns);

    for (int i = 0; i < Rows; i++)
        for (int j = 0; j < Columns; j++)
            InFile >> MyData[i][j]; // read the rest - not working

    InFile.close();

So I successfully read the first line, hence I resize the vector correctly. However, final vector is just zeros. Could any one tell me what am I doing wrong? Please and thanks

A: You are trying to read a floating point number -0.5 into an integer, which fails. Once the stream fails it will not read anything else until the error is cleared.


text:
Q: Adding a new XML element using python ElementTree library I'm trying to add a new element to an xml file using the python ElementTree library with the following code.
from xml.etree import ElementTree as et
def UpdateXML(pre):
    xml_file = place/file.xml
    tree = et.parse(xml_file)
    root = tree.getroot()
    for parent in root.findall('Parent'):
        et.SubElement(parent,"NewNode", attribute=pre)
    tree.write(xml_file)

The XML I want it to render is in the following format
<Parent>
            <Child1 Attribute="Stuff"/>
            <NewNode Attribute="MoreStuff"/> <--- new
            <Child3>
            <Child4>
            <CHild5>
            <Child6>
    </Parent>

However the xml it actually renders is in this incorrect format
<Parent>
                <Child1 Attribute="Stuff"/>
                <Child3>
                <Child4>
                <CHild5>
                <Child6>
                <NewNode Attribute="MoreStuff"/> <--- new
        </Parent>

What do I change in my code to render the correct xml?

A: You want the insert operation:
node = et.Element('NewNode')
parent.insert(1,node)

Which in my testing gets me:
<Parent>
            <Child1 Attribute="Stuff" />
            <NewNode /><Child3 />
            <Child4 />
            <CHild5 />
            <Child6 />
    </Parent>


text:
Q: Pop fragment out of the stack. Android I have a navigation drawer that contains FragmentContainer, FragmentMain, FragmentSub.
FragmentContainer automatically adds FragmentMain using getChildFragmentManager.
FragmentMain has a button that replaces current fragment with FragmentSub using getFragmentManager.
The problem is :
Case 1 : If I use getFragmentManager to automatically add FragmentMain, there is an error when I try to rotate the screen.
java.lang.IllegalArgumentException: No view found for id

Case 2 : If I use getChildFragmentManager there is no problem during screen rotation but after that I cannot pop fragment on the backstack.
I have these method on the MainActivity that pops the fragment out of the stack but it doesn't worked.
 @Override
public void onBackPressed() {

    DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
    if (drawer.isDrawerOpen(GravityCompat.START)) {
        drawer.closeDrawer(GravityCompat.START);
    } else {
        FragmentManager fragmentManager = getSupportFragmentManager();

        if (fragmentManager.getBackStackEntryCount() != 0) {
            fragmentManager.popBackStack();
        } else {
           logoutDialog();
        }

    }
}

FragmentContainer
FragmentMain fragmentMain = new FragmentMain();
    FragmentManager fragmentManager = getChildFragmentManager();
    fragmentManager.beginTransaction().add(R.id.fragmentContainer, fragmentMain).commit();

FragmentMain
getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragmentMain).addToBackStack(null).commit();

FragmentSub
getFragmentManager().beginTransaction().replace(R.id.fragmentContainer, fragmentSub).addToBackStack(null).commit();

A:  android:configChanges="keyboardHidden|orientation"

try this in your manifest file. for rotation problem


text:
Q: linq to sql with multiple aggregators I want to translate this simple SQL statement to linq-to-sql:
SELECT SUM(field1), SUM(field2)
FROM TableName

The closest linq-to-sql is (i think) using the group by clause:
from tbl in TableName
group tbl by (1) into g
select new{ value1= g.Sum(p => p.field1), value2 = g.Sum(p => p.field2)};

As this does not produce the expected outcome, what must be changed??
Thanks in advance

A: That should produce the same result. In what way does it not?

A: You want it without the group by.
The only way I can think of is this:
var result =  new {value1 = Table1.Sum(a => a.field1), value2 = Table1.Sum(a => a.field2)};

Which is a bit of a bummer as it emits 2 separate queries.
You can use linqpad: http://www.linqpad.net/ to find out what sql your linq is emitting.


text:
Q: Angular2 http interceptor modify response I would like to create an http interceptor that modifies all date values returned from an http get from datetime to just date, removing the time portion.
The code below is doing a search and replace on the response["_body"] to replace DateTime and removing the Time portion, but I'm not sure how to modify the response within convertDateTimeToDate() so that the changes are returned in the response. Can you modify the response so that the datetime values are replaced with date values? Thanks for any help.
The JSON being returned via Web API is an array employee[] where each record looks like the following:
{ "employeeID":1, "firstName":"Nancy", "lastName":"Davolio",
"title":"Sales Representative", "birthDate":"1948-12-08T00:00:00",
"hireDate":"1992-05-01T00:00:00", "city":"Seattle", "region":"WA",
"postalCode":"98122", "country":"USA", "homePhone":"(206) 555-9857",
"extension":"5467" }

http-interceptor.service.ts
import { Injectable } from '@angular/core';

import {
    Http,
    ConnectionBackend,
    RequestOptions,
    RequestOptionsArgs,
    Request,
    Response,
    Headers
} from '@angular/http';

import { Observable } from 'rxjs/Observable';

import 'rxjs/Rx';

@Injectable()
export class HttpInterceptor extends Http
{
    constructor(
        backend: ConnectionBackend,
        defaultOptions: RequestOptions,
    ) {
        super(backend, defaultOptions);
    }

    /**
     * Performs a request with http get method.
     * @param url
     * @param options
     * @returns {Observable<>}
     */
    get(url: string, options?: RequestOptionsArgs): Observable<any> {
        this.beforeRequest();
        return super.get(url, this.requestOptions(options))
            .catch(this.onCatch)
            .do((res: Response) => {
                res = this.onSuccess(res);
            }, (error: any) => {
                this.onError(error);
            })
            .finally(() => {
                this.onFinally();
            });
    }

    //
    // Implement POST, PUT, DELETE HERE
    //

    /**
     * Request options.
     * @param options
     * @returns {RequestOptionsArgs}
     */
    private requestOptions(options?: RequestOptionsArgs): RequestOptionsArgs {
        if (options == null) {
            options = new RequestOptions();
        }
        if (options.headers == null) {
            options.headers = new Headers({
                'Content-Type': 'application/json',
                'Accept': 'application/json'
            });
        }
        return options;
    }

    regexdatetime: RegExp = /T\d{2}:\d{2}:\d{2}/g;  // YYYY-MM-DDT24:00:00

    private convertDateTimeToDate(input) {
        // Ignore things that aren't objects.
        //if (typeof input !== "object") return input;

        //if (input["_body"] != null)
        //console.log("_body: " + input["_body"]);
        var value = input["_body"];
        var newvalue = value.replace(this.regexdatetime, "");
        //console.log("_body replace: " + newvalue);
        input["_body"] = newvalue;
        return input;
    }

    /**
     * Error handler.
     * @param error
     * @param caught
     * @returns {ErrorObservable}
     */
    private onCatch(error: any, caught: Observable<any>): Observable<any> {
        return Observable.throw(error);
    }

    /**
     * onSuccess
     * @param res
     */
    private onSuccess(res: Response): Response {
        //console.log(this.constructor.name + ".onSuccess " + res);
        return this.convertDateTimeToDate(res);
    }

    /**
     * onError
     * @param error
     */
    private onError(error: any): void {
    }

    /**
     * onFinally
     */
    private onFinally(): void {
    }
}

employee-list.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';

import { Employee } from './employee';
import { EmployeeService } from './employee.service';

@Component({
    selector: 'employee-list',
    templateUrl: './employee-list.component.html',
})
export class EmployeeListComponent implements OnInit {
    title = 'Northwind Employees';
    employees: Employee[];
    isLoading: boolean = false;
    selectedEmployee: Employee;
    errorMessage: string;

    // dependency injection
    constructor(
        private _router: Router,
        private _service: EmployeeService
    ) { }

    getEmployees(): void {
        this.isLoading = true;
        this._service.getEmployees()
            .then((employees) =>
            {
                this.employees = employees;
                console.log(this.toString());
                this.isLoading = false;
            },
                error => this.errorMessage = <any>error
            )
    }

    ngOnInit(): void {
        this.getEmployees();
    }
}

app.module.ts
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';

import { Http, HttpModule, XHRBackend, RequestOptions } from '@angular/http';
import { HttpInterceptor } from './http-interceptor.service';

import { UniversalModule } from 'angular2-universal';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './components/app/app.component'

import { NavMenuComponent } from './components/navmenu/navmenu.component';
import { HomeComponent } from './components/home/home.component';

import { NorthwindModule } from './components/northwind/northwind.module';

@NgModule({
    declarations: [
        AppComponent,
        NavMenuComponent,
        HomeComponent
    ],
    bootstrap: [ AppComponent ],
    providers: [
        {
            provide: Http,
            useClass: HttpInterceptor,
            useFactory: (backend: XHRBackend, options: RequestOptions) => {
                return new HttpInterceptor(backend, options);
            },
            deps: [ XHRBackend, RequestOptions ]
        }
    ],
    imports: [
        // Must be first import.
        // This automatically imports BrowserModule, HttpModule, and JsonpModule too.
        UniversalModule,
        CommonModule,
        FormsModule,
        HttpModule,
        AppRoutingModule
    ]
})

export class AppModule {
}

A: You should be using a private method inside your service to handle this as below
private stripTime(temp:User[]):User[]{
      temp.forEach(item=>{
          item.birthDate = new Date(item.birthDate).toISOString().slice(0,10).replace(/-/g,"");;
      }))
      return temp;

   }

LIVE DEMO


text:
Q: 1 centered button, how can I put another button 10dp above the centered button? Android, IntelliJ I have a view with two buttons. One (button2) Ive put android:layout_centerInParent="true" and it is in centered in the screen where it should be. Now I want the other (button1) to be placed above button 2 with a margin of 10dp. I am using a relative layout. How can I write this in xml? Should I use some other layout to make it work?
My .xml code:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bakgrundsbild"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <Button
            android:id="@+id/button1"
            android:layout_width="280dp"
            android:layout_height="50dp"
            android:background="@drawable/nybutton"
            android:text="@string/las_sollefteabladet"
            android:layout_centerHorizontal="true"/>

    <Button
        android:id="@+id/button2"
        android:layout_width="280dp"
        android:layout_height="50dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/nybutton"
        android:text="@string/annonsorer"
        android:layout_centerInParent="true"/>

</RelativeLayout>

A: Use your layout like this..
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin" >

<Button
    android:id="@+id/button2"
    android:layout_width="280dp"
    android:layout_height="50dp"
    android:layout_centerInParent="true"
    android:layout_marginTop="10dp"
    android:text="annonsorer" />

<Button
    android:id="@+id/button1"
    android:layout_width="280dp"
    android:layout_height="50dp"
    android:layout_above="@+id/button2"
    android:text="las_sollefteabladet" /></RelativeLayout>

Add images to that..

A: android:layout_above="@+id/button2"
use this in Button1(centered position) code


text:
Q: PHP not displaying errors - Internal Server Error (500) I've set up a fresh install of Ubuntu Server 12.04 LTS on Amazon AWS with *Apache2/MySQL/PHP5. When I run a PHP script and it encounters an error I don't see any error reporting from PHP, all I see is
HTTP Error 500 (Internal Server Error): An unexpected condition was encountered while the server was attempting to fulfil the request.

I have checked my /etc/php5/apache2/php.ini file and as far as I can tell error reporting should be set up. The contents of the file (regarding errors) are:
;    display_errors
;      Default Value: On
;      Development Value: On
;      Production Value: Off

;    display_startup_errors
;      Default Value: Off
;      Development Value: On
;      Production Value: Off

;    error_reporting
;      Default Value: E_ALL & ~E_NOTICE
;      Development Value: E_ALL | E_STRICT
;      Production Value: E_ALL & ~E_DEPRECATED

Can anyone advise? If I try something like $obj = new ObjectDoesntExist; it doesn't tell me Fatal error: Class 'ObjectDoesntExist' it gives me a server 500 error.
Any advise?
* The modules I have installed are: mysql-server mysql-client apache2 php5 libapache2-mod-php5 phpmyadmin. Other than that it is a completely base install of Ubuntu Server 12.04 LTS
EDIT:
If I use ini_set('display_errors', '1'); at the start of my script it displays errors as normal, but how do I enable this site wide?

A: please edit  the php.ini file by using the sudo gedit /etc/php5/apache2/php.ini and  on the Production Value,or you can also use the ini_set('display_errors', '1'); at the top of your php file

A: The php.ini snippet you pasted has a semicolon (the ; character) in each line. The semicolon is the start of a comment in php.ini, so everything in a line following a semicolon is not used. Try manually setting display_errors to on and error_reporting to E_ALL, or removing the appropriate semicolons to fix this.
Furthermore, check your apache's error log, php might be logging its errors there.

A: I had the same problem but unrelated with php.ini
if you have same error, before you begin snipping on your server, first check your code.
Mistake can be a missing } ) or ; or something like that.
this is just reference what to do first.

A: // Disable displaying errors, enable logging
ini_set('display_errors', 0);
ini_set('log_errors', 1);
ini_set('error_log', '/var/log/php_error.log');

// Handle errors and exceptions
set_error_handler(function($errno, $errstr, $errfile, $errline) {
    error_log(sprintf("[%s] %s in %s on line %d", date('Y-m-d H:i:s'), $errstr, $errfile, $errline));
    http_response_code(500);
    exit();
});

set_exception_handler(function($exception) {
    error_log(sprintf("[%s] Uncaught exception '%s' with message '%s' in %s:%d\nStack trace:\n%s\n",
        date('Y-m-d H:i:s'),
        get_class($exception),
        $exception->getMessage(),
        $exception->getFile(),
        $exception->getLine(),
        $exception->getTraceAsString()
    ));
    http_response_code(500);
    exit();
});

*

*set_error_handler to handle PHP errors, and set_exception_handler to handle exceptions. When an error or exception occurs, the message is logged to the error log file using the error_log function, and the response code is set to 500 to indicate a server error. Finally, an example error is triggered by attempting to use an undefined variable.


text:
Q: Hibernate, Extending Entity - "java.lang.IllegalArgumentException: Unknown entity" I have a Hibernate Entity, BaseEvent, which works fine:
import javax.persistence.*;

@Entity
@Table(name = "base_event")
@SequenceGenerator(name = "seq", allocationSize = 1, sequenceName = "seq")
public class BaseEvent
{
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
    @Column(name = "id")
    protected Long id = null;

    @Column(name = "my_field", nullable = false)
    protected String myField;

    public Long getId()
    {
        return id;
    }

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

    public String getMyField()
    {
        return myField;
    }

    public void setMyField(final String myField)
    {
        this.myField = myField;
    }
}

I want to identify when this object is changed and update some Map in my application. The easiest way I could think of doing this was to extend BaseEvent and override the setter:
import java.text.MessageFormat;

public class ExtendedEvent extends BaseEvent
{
    @Override
    public void setMyField(final String myField)
    {
        System.out.println(MessageFormat.format("Setting myField to {0}", myField));
        super.setMyField(myField);
    }
}

This works fine in my application, but then when I come to persist the Entity, Hibernate complains it doesn't know what an ExtendedEvent is.
java.lang.IllegalArgumentException: Unknown entity: my.package.ExtendedEvent

I can see that extending Hibernate Entities is a non-trivial problem, especially when you start adding fields - but all I want is for Hibernate to treat ExtendedEvent as a BaseEvent (because it is). Is there a simple solution for this?

A: Make base event @MappedSuperclass and extending class @Entity
so
@MappedSuperclass
public class BaseEvent

and
@Entity
@Table(whatever)
public class ExtendedEvent extends BaseEvent

A: If you want to update your map only when changes are updated in the data store, I would recommend implementing onFlushDirty in a Hibernate Interceptor. This method gets called whenever the Session is flushed to the database for every entity change. You can check the object type in the onFlushDirty method for your entity of interest and property of interest.


text: Q: passing data directly from one PC to another connected to the internet what are the ways in which we can share data/messages/information from one PC to another directly without the need of an intermediary server which are connected to the internet?


text:
Q: Candy Crush level 210: how to clear licorice? I understand you have to get two candy bombs together. When I do this they only clear the right side, and not the licorice on the left side.  What am I doing wrong?
Level 210:

A: I think you are confused with what are candy bombs and what are color bombs. You should combine two of these:

A candy bomb is something like this:

Obviously nothing happens if you combine two of those, If you combine two of the first (the candy bombs), the whole field should be lasered, and you get rid of all the licorice on the left side. Although some people are complaining this is not working (source), but this should be the way to do it. So if it is not working, try again, it should work in the end.

A: Combining the color bombs works on the mobile version but not the pc version. I have tried multiple times on pc and they only clear the right side. Try playing on the mobile version. The combined color bombs do clear both sides on mobile.


text:
Q: How to keep language after restart device? i have problem with language change in my app. this is how i change language on button clic in my app
        Locale locale = new Locale("en");
    Locale.setDefault(locale);
    Configuration config = new Configuration();
    config.locale = locale.ENGLISH;
    getBaseContext().getResources().updateConfiguration(config, getBaseContext().getResources().getDisplayMetrics());
    Intent i = new Intent(v.getContext(), HomeActivity.class);
    startActivity(i);

and work good but when i change language, my keyboard dont change in the new language and keep the system language and when i restart my device, my app doesn't keep the language changed.
how can i keep language after restart and make keyboard change language after language change.
Excuse me for my english.
thks

A: Use shared Preference
class my_activity extends Activity
 {
     SharedPreferences prefs;
     String lang;

        onCreate(Bundle savedInstance)
        {
            //to retrieve the saved language
          prefs = PreferenceManager.getDefaultSharedPreferences(this);
          lang =prefs.getString("lang", "en");
           //lang = "en"or whatever the saved language before restarting the device
           //if there is no saved string with this key "lang" lang variable will be
            equal "en"
        }

And when the language changes in the app on button click
{
    prefs.edit().putString("lang", lang).commit();
}


text:
Q: Python Combobox values not filtering after binding I am working on a project where i need to provide 3 drop down list which should be dependent on each other and should filter values based on selections made on each drop down.
I have used Combobox function in python and have bind them to filter based on selection. This works perfect for the first 2 drop downs, but the 3rd drop down is not showing values as defined to show based on first 2 drop downs.
I am sure i am making some mistake, but not able to find it. Need some expert help.
Below is my sample code which describes my requirement.
from tkinter import *
from tkinter import ttk

root =Tk()
root.geometry("500x400")

sizes =["small","medium","large"]

small_colors = ["red","green"]

medium_colors = ["blue","black"]

large_colors = ["yellow","pink"]

red_numbers = ["one","two"]

green_numbers = ["three","four"]

blue_numbers = ["five","six"]

black_numbers = ["seven","eight"]

yellow_numbers = ["nine","ten"]

pink_numbers = ["eleven","tweleve"]

def pick_color(event):
    if my_combo.get()=="small":
        color_combo.config(value=small_colors)
        color_combo.current(0)
    if my_combo.get()=="medium":
        color_combo.config(value=medium_colors)
        color_combo.current(0)
    if my_combo.get()=="large":
        color_combo.config(value=large_colors)
        color_combo.current(0)
    if color_combo.get()=="red":
        num_combo.config(value=red_numbers)
        num_combo.current(0)
    if color_combo.get()=="yellow":
        num_combo.config(value=yellow_numbers)
        num_combo.current(0)
    if color_combo.get()=="green":
        num_combo.config(value=green_numbers)
        num_combo.current(0)
    if color_combo.get()=="blue":
        num_combo.config(value=blue_numbers)
        num_combo.current(0)
    if color_combo.get()=="black":
        num_combo.config(value=black_numbers)
        num_combo.current(0)
    if color_combo.get()=="pink":
        num_combo.config(value=pink_numbers)
        num_combo.current(0)

my_combo = ttk.Combobox(root, value=sizes,state="readonly")
my_combo.current(0)
my_combo.pack(pady=20)
my_combo.bind("<<ComboboxSelected>>",pick_color)

color_combo = ttk.Combobox(root, value=[" "],state="readonly")
color_combo.current(0)
color_combo.pack(pady=20)

num_combo = ttk.Combobox(root, value=[" "], state="readonly")
num_combo.current(0)
num_combo.pack(pady=20)
num_combo.bind("<<ComboboxSelected>>",pick_color)

def ans():
    print(my_combo.get())
    print(color_combo.get())
    print(num_combo.get())

sub_butn = Button(root, text="SUBMIT", command = ans)
sub_butn.pack(pady=20)

root.mainloop()

its just the 3rd value which is not sorting as expected. When i select "green" in 2nd dropdown it should values as "three","four" in 3rd down down which its not showing.

A: This would work. Just replacing if with elif
def pick_color(event):
    if my_combo.get()=="small":
        color_combo.config(value=small_colors)
        color_combo.current(0)
    elif my_combo.get()=="medium":
        color_combo.config(value=medium_colors)
        color_combo.current(0)
    elif my_combo.get()=="large":
        color_combo.config(value=large_colors)
        color_combo.current(0)
    if color_combo.get()=="red":
        num_combo.config(value=red_numbers)
        num_combo.current(0)
    elif color_combo.get()=="yellow":
        num_combo.config(value=yellow_numbers)
        num_combo.current(0)
    elif color_combo.get()=="green":
        num_combo.config(value=green_numbers)
        num_combo.current(0)
    elif color_combo.get()=="blue":
        num_combo.config(value=blue_numbers)
        num_combo.current(0)
    elif color_combo.get()=="black":
        num_combo.config(value=black_numbers)
        num_combo.current(0)
    elif color_combo.get()=="pink":
        num_combo.config(value=pink_numbers)
        num_combo.current(0)

A: First you should bind the event on color_combo, not num_combo.  Second suggest to use different callbacks for my_combo and color_combo:
def pick_color(event):
    mapping = {
        "small": small_colors,
        "medium": medium_colors,
        "large": large_colors,
    }
    size = my_combo.get()
    if size in mapping:
        # update color_combo
        color_combo.config(value=mapping[size])
        color_combo.set("")
        # clear num_combo
        num_combo.set("")
        num_combo["value"] = []

def pick_number(event):
    mapping = {
        "red": red_numbers,
        "yellow": yellow_numbers,
        "green": green_numbers,
        "blue": blue_numbers,
        "black": black_numbers,
        "pink": pink_numbers,
    }
    color = color_combo.get()
    if color in mapping:
        # update num_combo
        num_combo.config(value=mapping[color])
        num_combo.set("")
...
my_combo.bind("<<ComboboxSelected>>", pick_color)
...
color_combo.bind("<<ComboboxSelected>>", pick_number)
...
#num_combo.bind("<<ComboboxSelected>>",pick_color) # not required
...


text:
Q: member functions with same name C++ I found an example where in the a class definition, there were 2 member functions defined, but with the same name and same number of arguments:
const MyClass& operator [] (int index) const;
MyClass& operator [] (int index);

My question is how will the compiler know which operator definition it needs to use?

A: They are different methods, primarily due to the const suffix.
The return value (alone) cannot be used to resolve overloaded methods or operators.
Edit 1:
You understanding is not correct.
The first function returns a reference, which cannot be modified, to an object.  It does not return a copy. The method is not allowed to modify class members.
The second function returns a reference to an object, the object can be modified.  The method is allowed to modify class members.

A: If you attempt to use the operator in a constant function, the constant operator will be called, otherwise, the non-constant one will be called. This is a subtlety that often trips people up as if you only define the non-constant operator but attempt to use it in a constant function it will result in errors.

A: When two methods differ only in the declaration of const, the const version will be selected if it is called from a pointer or reference that is also declared const. Otherwise you will get the non-const version.
This is most commonly seen in the implementation of vector. If you have a const vector, you don't want to be able to change any of the elements, so a const reference to an element is returned.


text:
Q: Latex and variables in plot label in R? How do I use variables in Latex expressions in R?
For example:
plot(X, Y, main=expression(R^2))

Will put R with a nice superscripted 2 as main title.
But let's say I want it to say 'R^2: 0.5', with 0.5 coming from a R variable. How do I do that?

A: Well this works...
call(':', quote(R^2), a)

though it feels a little hacky to me since it's using R's : operator, whereas you just want to stick some text on the end. Maybe there's a better way?

A: tikz and psfrag allow you to use actual LaTeX code and output instead of plotmath's, resulting in better typographic consistency.
See this question for details. Getting LaTeX into R Plots

A: Another variation on @Joris' theme is substitute(). You give substitute() an expression and an environment or list within which to evaluate the expression. Passing a list is usually easiest, especially for jobs such as the one posed here.
plot(X,Y, main = substitute(R^2 : a, list(a = a)))

We can see why this works, by looking solely at the substitute() call:
> substitute(R^2 : a, list(a = a))
R^2:0.8

The a in the expression is replace with the value of a in the list.

A: The hack of Owen is pretty cool, but not really the common way to do that. If you use bquote, this is actually pretty easy. bquote will do the same as quote, with the exception that everything between .() will be evaluated in a specified environment (or the global, if nothing is specified).
A trivial example :
X <- 1:10
Y <- 1:10
a <- 0.8
plot(X,Y,main=bquote(R^2 : .(a)))

Gives :

See also ?bquote and ?plotmath for more examples and possibilities


text:
Q: I cannot send a message using the Twilio API in Kotlin, as an error shows and crashes my app I have been trying to make my app send me SMS messages for a while now, but have not been able to figure anything out. I have been trying to use Twilio's 2 official tutorials for sending SMS messages in Kotlin. This is my code:
Twilio.init("mytwiliosid", "mytwilioauth")

        val message = Message.creator(
                PhoneNumber("mynumber"),
                PhoneNumber("twilionumber"),
                "Hello from Starfruit!"
        ).create()

        print(message.sid)

I have this on my OnCreate function to test. However, whenever I try to run my app, it crashes. My code runs fine if I take this out, but whenever I have it in my app, it immediately crashes when opened, and shows this error message in LogCat:
2020-10-21 22:54:05.302 7120-7120/com.gradient.starfruit E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.gradient.starfruit, PID: 7120
    java.lang.NoSuchFieldError: No static field INSTANCE of type Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; in class Lorg/apache/http/conn/ssl/AllowAllHostnameVerifier; or its superclasses (declaration of 'org.apache.http.conn.ssl.AllowAllHostnameVerifier' appears in /system/framework/framework.jar!classes3.dex)
        at org.apache.http.conn.ssl.SSLConnectionSocketFactory.<clinit>(SSLConnectionSocketFactory.java:144)
        at org.apache.http.conn.ssl.SSLConnectionSocketFactory.getSocketFactory(SSLConnectionSocketFactory.java:172)
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.getDefaultRegistry(PoolingHttpClientConnectionManager.java:109)
        at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.<init>(PoolingHttpClientConnectionManager.java:116)
        at com.twilio.http.NetworkHttpClient.<init>(NetworkHttpClient.java:58)
        at com.twilio.http.TwilioRestClient$Builder.build(TwilioRestClient.java:102)
        at com.twilio.Twilio.getRestClient(Twilio.java:122)
        at com.twilio.base.Creator.create(Creator.java:45)
        at com.gradient.starfruit.MainActivity.onCreate(MainActivity.kt:41)
        at android.app.Activity.performCreate(Activity.java:8086)
        at android.app.Activity.performCreate(Activity.java:8074)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1313)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3755)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3961)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:91)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:149)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:103)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2386)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:213)
        at android.app.ActivityThread.main(ActivityThread.java:8178)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:513)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1101)

I honestly don't really understand the error message, but I am fairly certain my Message.creator is causing it. If anyone knows what I can do to fix this error, or what I should do instead of what I'm doing now to send a message in Kotlin, your help would be greatly appreciated!
Thank you for any help in advance.

A: It's not exactly what I was originally making, but I found a way to relatively simply send a message from an android app.
val smsManager: SmsManager = SmsManager.getDefault()
        smsManager.sendTextMessage("+19999999999", null, "Message goes here!", null, null);

This will make the phone itself text any number. You'll also need send_sms permissions for this, so you should have a <uses-permission> for that in your manifest file, as well as this code in your MainActivity file to ask for the permission.
if (ContextCompat.checkSelfPermission(this@MainActivity, Manifest.permission.SEND_SMS) !== PackageManager.PERMISSION_GRANTED) {
            if (ActivityCompat.shouldShowRequestPermissionRationale(this@MainActivity, Manifest.permission.SEND_SMS)) {
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.SEND_SMS), 1)
            } else {
                ActivityCompat.requestPermissions(this@MainActivity, arrayOf(Manifest.permission.SEND_SMS), 1)
            }
        }


text:
Q: Can not return a Chars iterator because it "does not live long enough" I want to be able to assign a Chars iterator to a struct, whose String was created inside of the struct's "constructor" method.  How do I do this?
Code (run it):
use std::str::Chars;

fn main() {
    let foo = Foo::new();
}

struct Foo<'a> {
    chars: Chars<'a>
}
impl<'a> Foo<'a> {
    pub fn new() -> Self {
        let s = "value".to_string();
        Foo { chars: s.chars() }
    }
}

Error:
error: `s` does not live long enough
  --> <anon>:13:22
13 |>         Foo { chars: s.chars() }
   |>                      ^
note: reference must be valid for the lifetime 'a as defined on the block at 11:25...
  --> <anon>:11:26
11 |>     pub fn new() -> Self {
   |>                          ^
note: ...but borrowed value is only valid for the block suffix following statement 0 at 12:36
  --> <anon>:12:37
12 |>         let s = "value".to_string();
   |>

(In my real code, the constructor reads text from a file)

A: You can't. Chars does not take ownership of the string, so once you go out of Foo::new, the string does not exist anymore. You need to store the string itself. Chars really is just a small utility type that's meant to be used on site, not stored somewhere to be used later.


text:
Q: How do I create a dynamic endorsement policy (ESCC) in Hyperledger Fabric 1.2? Under endorsement policies documentation, the following is stated:

Dynamic addition of endorsement policies (e.g., by deploy transaction on chaincode deploy time) is very sensitive in terms of bounded policy evaluation time (termination), determinism, performance and security guarantees. Therefore, dynamic addition of endorsement policies is not allowed, but can be supported in future.

If I'm interested in having a more fluid endorsement policy whereby we're constantly adding new peers and would like the endorsement policy to be based on a unique set of peers which correlate to specific transactions, would that be possible?
I.e. in some cases a transaction is between two specific peers, so they should both be valid endorsers. Five other peers exist, lets say they're competitors, and they should not be allowed to endorse in that scenario.
In 1.1, it doesn't appear as though you can deploy your own custom ESCC/VSCC as mentioned in https://jira.hyperledger.org/browse/FAB-8729.
With the new 1.2 pluggable architecture, I don't see how I could obtain access to the ChaincodeStubInterface to handle custom logic based on passed transaction params. For example, the old 1.1 pluggable chaincode architecture extended Chaincode interface.
Given the method signatures below, is it possible to gain access to the ChaincodeStubInterface with the data from the new method signatures?
https://hyperledger-fabric.readthedocs.io/en/release-1.2/pluggable_endorsement_and_validation.html
Endorse(payload []byte, sp *peer.SignedProposal) (*peer.Endorsement, []byte, error)
Validate(block *common.Block, namespace string, txPosition int, actionPosition int, contextData ...ContextDatum) error
Specifically, I want access to something like args := stub.GetStringArgs() or even just the payload's composite key / index name.

A: I have tried to develop the similar feature on my own apps recently. Though dynamic endorsement policy is not supported in the current version, we can using dynamic configuration to help us define what endorsement method we expected in our apps.
I am not sure whether we can directly access to the ChaincodeStubInterface with the method signatures, but I will try it and keep updating.
Here is my solution. Hope this can help.

*

*Using Fabric-SDK-Node to create my apps, and make sure the fabric version is above 1.1.0, which provide a more comprehensive configuration file for us.

*Here is part of sample configuration file, provided by official:
orderers:
  - orderer.example.com
peers:
  peer0.org1.example.com:
    endorsingPeer: true
    chaincodeQuery: true
    ledgerQuery: true
    eventSource: true
  peer0.org2.example.com:
    endorsingPeer: true
    chaincodeQuery: true
    ledgerQuery: true
    eventSource: true
chaincodes:
  - mycc:v0

*You can notice that this sample provide four option for us to define which connection policy that you want to use for your transaction. By setting peer0.org2.endorsingPeer as false, when a situation, which someone send a invoke proposal to the fabric network, happens after the user finished setConfigSetting and loaded the connection profile, the transaction can only be endorsed by peer0.org1. The rest of the three option works the same as the endorsingPeer.

*Now that we can create a function to let user dynamic design their desired endorsement policy before sending a transaction.