text:
Q: Changing layout parameters inside a fragment with a button's onClick method I have an activity that bears exactly 5 fragments. In one of these fragments there is a Button and a RelativeLayout. I want my button to be able to change this RelativeLayout's height or width.
my xml:
     <ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content" >

    <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="vertical" >

<Button
    android:id="@+id/sSumBut"
    android:layout_width="250dp"
    android:layout_height="40dp"
    android:layout_gravity="center_horizontal"
    android:layout_marginTop="10dp"
    android:onClick="onClick" >
</Button>

<RelativeLayout
    android:id="@+id/sSum"
    android:layout_width="250dp"
    android:layout_height="0dp"
    android:layout_gravity="center_horizontal"
    android:background="@android:color/black" >

</RelativeLayout>

      </LinearLayout>

         </ScrollView>

As you see the height of the RelativeLayout is 0. I want the button to be able to change it to 100dp.
This is my Fragment class:
  @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View myFragmentView = inflater.inflate(R.layout.up, container, false);

  Button sButton = (Button) myFragmentView.findViewById(R.id.sSumBut);
  final RelativeLayout sSummary = (RelativeLayout) myFragmentView.findViewById(R.id.sSum);

  sButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // When button is clicked.
            sSummary.setLayoutParams(new RelativeLayout.LayoutParams(250, 250));
        }
    });

But this gives out the error  Cannot refer to a non-final variable and if I make the variable final, I normally can't change it inside the onClick method dynamically. Please considering that this class is a Fragment, how can I work around this?
error log:
       11-01 15:07:03.035: E/AndroidRuntime(3048): FATAL EXCEPTION: main
       11-01 15:07:03.035: E/AndroidRuntime(3048): java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:360)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.ScrollView.measureChildWithMargins(ScrollView.java:1284)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.ScrollView.onMeasure(ScrollView.java:354)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.support.v4.view.ViewPager.onMeasure(ViewPager.java:1451)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.View.measure(View.java:8366)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewRoot.performTraversals(ViewRoot.java:847)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.view.ViewRoot.handleMessage(ViewRoot.java:1868)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.os.Handler.dispatchMessage(Handler.java:99)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.os.Looper.loop(Looper.java:130)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at android.app.ActivityThread.main(ActivityThread.java:3693)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at java.lang.reflect.Method.invokeNative(Native Method)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at java.lang.reflect.Method.invoke(Method.java:507)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:907)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:665)
       11-01 15:07:03.035: E/AndroidRuntime(3048):  at dalvik.system.NativeStart.main(Native Method)

A: sSummary.setLayoutParams(new RelativeLayout.LayoutParams(250, 250));

Your sSummary, even if it is a RelativeLayout, is inside a LinearLayout. A view's layout params refer to the parent layout so the correct type of layout params here would be LinearLayout.LayoutParams. This is what causes the class cast exception.
Often a good approach is to just modify the existing layout params as retrieved with getLayoutParams(). After modifying the returned params in-place, request a re-layout with requestLayout() (setLayoutParams() also does this implicitly).

A: The reason why you are getting an error is because you can't reference a variable within the OnClickListener that is instantiated outside of class without it being final.
The fact that it is a Fragment shouldn't change anything, it's just a matter of correctness. you could simply make the following update:
final RelativeLayout Sum = (RelativeLayout) myFragmentView.findViewById(R.id.Sum);

And that should fix the error that you are receiving.

A: Okay, turns out the problem was LinearLayout for some reason. I changed it to RelativeLayout and my problem was fixed. What the hell LinearLayout? I trusted you.


text:
Q: NEW TITLE -- The application called an interface that was marshalled for a different thread After making the project simpler, I believe I identified the problem is actually a result the async marshalling.
UPDATE:  I made the code simpler to try to figure out what was going on.  So here is an update... The Observable collection is being populated on a new thread (async method).  I tried moving the assigning of the ItemsSource to after the ObservableCollection is loaded as seen below
   async void LoadAllData(object sender, EventArgs e)
    {

        if (sender != null)
        {
            App.GeoLocationComplete -= LoadAllData;
        }
await ViewModelObjects.NearbyLocations.LoadLocationData();
lvPlaces.ItemsSource = ViewModelObjects.NearbyLocations.GBSLocationDetails;
}

The definition for the data load method is a follows:
public async Task LoadLocationData()
    {....}

When I run this code I get the following error:
The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))
I know what is causing the error (the data was loaded on a thread other than the UI thread) but I don't know how to fix it.  Suggestions?
UPDATE UPDATE:  So I believe I have identified the root cause of the problem but have not figured out how to fix it.  I started by simplifying my code as follows and it worked.
    public nearbyplaces()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);
        LoadAllData(null, null);
    }

    void LoadAllData(object sender, EventArgs e)
    {

        lobj_Places = new ObservableCollection<GBSLocationDetail>()
        {
            new GBSLocationDetail()
            {
                Title = "Location 1",
                Distance = "20 Miles",
                AddInfo = "Something Else",
                AttributesTexts="Gay, Bar, Dance"
            }
        };

        lvPlaces.ItemsSource = lobj_Places;

    }

HOWEVER, what I need is for the LoadAllData method to be called once I have the GPS location from the device.  So in my App.XAML.cs I have the following delegate event declared:
    public static Plugin.Geolocator.Abstractions.IGeolocator gobj_RealGeoCoordinator;
    public static event GeoLocationCompleteEventHandler GeoLocationComplete;
    public static bool gb_WaitingForLocation = true;

Then I have the following code call the event once I get the location back from the device:
   private async void ProcessStartupandResume()
    {

        if (gobj_RealGeoCoordinator == null)
        {
            gobj_RealGeoCoordinator = CrossGeolocator.Current;

            ViewModelObjects.AppSettings.CanAccessLocation = App.gobj_RealGeoCoordinator.IsGeolocationEnabled;

            if (!ViewModelObjects.AppSettings.CanAccessLocation)
            {
                await MainPage.DisplayAlert(ResourceStrings.GetValue("NoLocationServicesTitle"), ResourceStrings.GetValue("NoLocationServicesMessage"), ResourceStrings.GetValue("OKButtonText"));
            }

            //Only add the events if the object has to be created.
            gobj_RealGeoCoordinator.PositionChanged += gobj_RealGeoCoordinator_PositionChanged;

            gobj_RealGeoCoordinator.PositionError += (sender, e) =>
            {
                ProcessException(new Exception(e.Error.ToString()));
            };
        }

        //Set this to null to trigger the first check
        ib_GPSReenabled = null;

        if (gobj_RealGeoCoordinator.IsListening)
            await gobj_RealGeoCoordinator.StopListeningAsync();

        gobj_RealGeoCoordinator.DesiredAccuracy = 50;

        await gobj_RealGeoCoordinator.StartListeningAsync(10000, 20);

    }

    private static void gobj_RealGeoCoordinator_PositionChanged(object sender, PositionEventArgs e)
    {
        var pos = e.Position;
        ViewModelObjects.AppSettings.Latitude = pos.Latitude;
        ViewModelObjects.AppSettings.Longitude = pos.Longitude;

        if (gb_WaitingForLocation)
        {
            gb_WaitingForLocation = false;
            GeoLocationComplete?.Invoke(new object() , null);
        }
    }

Then  in my page I subscribe to the GeoLocationComplete event using the LoadAllData method as seen below.  Even when I use a local object and try to set the ItemsSource for the ListView in the code when executed as a result of the event being raised, I receive the error.  See code below which subscribed to the event:
    public nearbyplaces()
    {
        InitializeComponent();
        NavigationPage.SetHasNavigationBar(this, false);

        if (App.gb_WaitingForLocation)
            App.GeoLocationComplete += LoadAllData;
        else
            LoadAllData(null, null);
    }

Any suggestions on how to fix this?

A: OK so I figured it out.  I needed to invoke the event on the main thread and I did that with the following code:
      Device.BeginInvokeOnMainThread(() =>
            {
                GeoLocationComplete?.Invoke(new object(), null);
            });

After inserting this code, the error was gone.  Changing the code back to simply
GeoLocationComplete?.Invoke(new object(), null);

cause the error to occur again.  Thus I believe this resolved my problem.  Hope this helps someone else. :)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to copy (not move) one git branch with merges to another I am trying to reorganize GIT repository, which is full of unorganized branches. Now we want to make some structure there (devel, production, features, ...branches) and delete/squash many small changes too. But something is needed to keep yet as it is, as there are people working on it.
So I created the big structure, squashed old things together (nobody longer interested in small typo fixes years old) and basically fixed everything to begin of this year.
But now the problem came - some branches are active, cannot be squashed fully, cannot be deleted/moved (until new schema proves to work for some time) and contains a lot of small merges inside, like this:
  jacks_branch
    A-B-C-F-G-H-I-J-M-N-O-P ...
            \D-E/    \K-L/

I would like to COPY this on top of appropriate feature branch, like
  feature_123
    XX-YY
  =>
    XX-YY-C'-F'-G'-H'-I'-J'-M'-N'-O'-P' ...
                \D'-E'/     \K'-L'/

(the schema is more complicated, this is the problematic part)
I would like to do something like
git checkout feature_123
git cherry-pick C..P

but it results on conflict on all those merges
error: could not apply E
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

the I commit (merge) solves all those conflicts, but it is not applied and cherry-picking stops
What is the best way out (except having it good organized from the start) ?

Edit - added example:
I have
* 3b0a2b4 3.line Adam (HEAD, Adam)
*   c04efb0 Just fixed merge from other computer
|\
| * 3e5f111 2.line Adam_a
* | 897bfc3 2.line Adam_b
|/
* 308a3c5 1.line Adam
* 33f3119 === new year ==== (master)
* 436619b 1000.line
.............
* 0a12c01 4.line
* 41d763d 3.line
* dd1feb0 2.line
* 55aa2c2 1.line
* 84b12e9 Point zero

Please see, that the branch Adam have conflict in it (3e5f111 and 897bfc3 adds respectively line Adam_a and Adam_b to the same place), which the developer Adam somehow solved in c04efb0 (by writing there something totally different, like Adam_* # it does not matter or so)
and I want to add new branch develop - that is easy squash of master
* 75675e1 === new_year === squashed 1.000 lines (HEAD, develop)
* 84b12e9 Point zero

and now I want to add branch feature_1 (over develop) with content from Adam (but not have to manually solving all those already solved conflicts, I want the merge (4444567) be just the same as on branch Adam)
* 555567 3.line Adam (HEAD, feature_1)
*   4444567 Just fixed merge from other computer
|\
| * 3334567 2.line Adam_a
* | 2234567 2.line Adam_b
|/
* 1234567 1.line Adam
* 75675e1 === new_year === squashed 1.000 lines (develop)
* 84b12e9 Point zero

to get this:
* 555567 3.line Adam (HEAD, feature_1)
*   4444567 Just fixed merge from other computer
|\
| * 3334567 2.line Adam_a
* | 2234567 2.line Adam_b
|/
* 1234567 1.line Adam
* 75675e1 === new_year === squashed 1.000 lines (develop)
| * 3b0a2b4 3.line Adam (Adam)
| *   c04efb0 Just fixed merge from other computer
| |\
| | * 3e5f111 2.line Adam_a (Adam_a)
| * | 897bfc3 2.line Adam
| |/
| * 308a3c5 1.line Adam
| * 33f3119 === new year ==== (master)
| * 436619b 1000.line
| * 0a12c01 4.line
| * 41d763d 3.line
| * dd1feb0 2.line
| * 55aa2c2 1.line
|/
* 84b12e9 Point zero

(and later I will delete Adam and master )

A: I think that rather than trying to rewrite history, you (and your team) should focus now on using the workflow you want to use going forward. That brings me to my next point, which is that if you move forward with a particular git workflow while other members of your team continue to use your current one, you will probably not be successful.
Assuming that the various branches in your repository have not diverged too much, you and your team should start merging and consolidating towards whatever you want your repository to look like, e.g. a master branch and feature branches.
Rewriting history (e.g. with a rebase) is tricky because it means that every commit since the one you're modifying or squashing must also be rewritten, which means that your new versions of those commits no longer match everyone else's "old" versions. When used sparingly on recent history, it can be useful, but rewriting the history of an entire repository and expecting to reconcile that with active development is not something I would ever attempt.


text:
Q: Grails: does belongsTo create a new column for a back reference? My code looks something like
class Person {
    Nose nose
}

class Nose {
    static belongsTo = [person:Person]
}

This is supposed to create a foreign key column for Nose on the 'person' table and also a back reference column for Person on the 'nose' table right?
There is no column generated for the back reference on the 'nose' table for me right now and I was wondering if this is normal...
http://grails.org/doc/latest/ref/Domain%20Classes/belongsTo.html
(Seems like this is what the documentation is saying, but I'm thinking I'm interpreting it wrong)
edit:
i edited the code snippet because i wrote the wrong thing down (haven't had coffee today)

A: You should reference the Person in the Nose, not Nose itself, like this:
class Person {
    Nose nose
}

class Nose {
    static belongsTo = [person: Person]
}

EDIT AFTER COMMENT: ah, I see.  Now that I am reading your question again, were you expecting to have both a person_id column in Nose and nose_id column in Person? Because that will never happen in GORM, at least not automatically - for your schema, only the Person table will contain a nose_id column per documentation.

A: In grails we use belongsTo for cascading purpose,You should use
class Nose {
belongsTo = [person:Person]
}

and yes in case of belongsTo a back reference will be stored in Nose having the person_id.


text:
Q: Site Cookies - Are there any security issues? I am currently trying to think of a way to keep a user logged in for a certain amount of time. I come across the use of site cookies. My dev-environment as an example is PHP.
addcookie('name', 'value', time() + 3600, '/');
I understand that you can generate a large, unique key as a value for each user which is stored in the Database, for reference for security, and then the only way really to manipulate a user would be to session steal using Cross-Site Scripting.
I am curious to know, due the the final parameter in the addcookie() - where the / is present in the example - is it possible for someone to set-up their own domain and actually add their own cookie to another domain?
I am not sure whether to strip the key before querying it in the Database because I am unsure whether this vulnerability exists - or any like such.
Any references would be great because Security is something that I find interesting, especially unauthorised access prevention.
I merely know anything about Cookie Poisoning and would love to understand more and how to prevent things or build an infrastructure that prevents the attack.
Edit: I am not asking how to Secure anything, just what Cookie Poisoning is and maybe ways that can be used to prevent people actually being able to do this (even if it's just tips!)

A: As you mentioned  session hijacking through cross site scripting (XSS) is common.
To prevent   XSS  you should always filter and escape all user session values before printing them to screen. However some bugs may slip through or a piece of legacy code might be vulnerable so it makes sense to also make use of browser protections against XSS.
By specifying the HttpOnly flag when setting the session cookie you can tell a users browser not to expose the cookie to client side scripting such as JavaScript. This makes it harder for an attacker to hijack the session ID and masquerade as the effected user.
 session.cookie_httponly = 1

It is also a good idea to make sure that PHP only uses cookies for sessions and disallow session ID passing as a GET parameter:
session.use_only_cookies = 1

Another important way to increase the security of PHP sessions in your application is to install an SSL certificate on the web server and force all user interactions to occur over HTTPS only.
Helpfully PHP has one ini setting to assist you in ensuring session cookies are only sent over secure connections:
 session.cookie_secure = 1

Ref:https://www.simonholywell.com/post/2013/05/improve-php-session-cookie-security/


text:
Q: Multidimensional array diff I got 2 arrays:
$big_array = array (
                    array (
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer1'
                            ),
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer2'
                            ),
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer3'
                            ),
                            array (
                                      'correct' => TRUE,
                                      'answer' => 'correct answer'
                            )
                    )
);

$small_array = array (
                    array (
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer1'
                            )
                    )
);

I want to make array_diff($big_array, $small_array) but its not working how i want it to, currently it gives me an empty array as a result, where i want the outcome to be:
$outcome_array= array (
                    array (
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer2'
                            ),
                            array (
                                      'correct' => FALSE,
                                      'answer' => 'false answer3'
                            ),
                            array (
                                      'correct' => TRUE,
                                      'answer' => 'correct answer'
                            )
                    )
);

Any suggestions?

A: yes you can use below function to get you perfect answer
function arrayRecursiveDiff($aArray1, $aArray2) {
  $aReturn = array();

  foreach ($aArray1 as $mKey => $mValue) {
    if (array_key_exists($mKey, $aArray2)) {
      if (is_array($mValue)) {
        $aRecursiveDiff = arrayRecursiveDiff($mValue, $aArray2[$mKey]);
        if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
      } else {
        if ($mValue != $aArray2[$mKey]) {
          $aReturn[$mKey] = $mValue;
        }
      }
    } else {
      $aReturn[$mKey] = $mValue;
    }
  }
  return $aReturn;
}

  $arr1 =    arrayRecursiveDiff($big_array,$small_array);

output
as you need
Array

(
    [0] => Array
        (
            [1] => Array
                (
                    [correct] =>
                    [answer] => false answer2
                )

            [2] => Array
                (
                    [correct] =>
                    [answer] => false answer3
                )

            [3] => Array
                (
                    [correct] => 1
                    [answer] => correct answer
                )

        )

)

check here for more info

A: Edited above code check whether or the the arr1 is bigger or arr2 is bigger
function arrayRecursiveDiff($aArray1, $aArray2) {

if(sizeof($aArray1) > sizeof($aArray2))
{
    $small_arr = $aArray2;
    $big_arr = $aArray1;
    $arr1_is_big = 1;
}
else
{
    $small_arr= $aArray1;
    $big_arr = $aArray2;
    $arr1_is_big = 0;
}
$aReturn = array();

foreach ($big_arr as $mKey => $mValue) {
    if (array_key_exists($mKey, $small_arr)) {
        if (is_array($mValue)) {
            $aRecursiveDiff = arrayRecursiveDiff($mValue, $small_arr[$mKey]);
            if (count($aRecursiveDiff)) { $aReturn[$mKey] = $aRecursiveDiff; }
            }
        else {
            if ($mValue != $small_arr[$mKey]) {
                $aReturn[$mKey] = $mValue;
                }
            }
    } else {
        $aReturn[$mKey] = $mValue;
    }
}
$aReturn["arr1_is_big"] = $arr1_is_big;

return ($aReturn);
}

A: I just edited the function from Murali Kumar cause I needed one more information.
It will check if the arrays are the same size and contains the same values.
function arrayRecursiveDiff($aArray1, $aArray2) {
    if(count($aArray1) > count($aArray2)) {
        $small_arr = $aArray2;
        $big_arr = $aArray1;
        $arr1_is_big = 1;
        $arr2_is_big = 0;
    } elseif(count($aArray1) < count($aArray2)) {
        $small_arr = $aArray1;
        $big_arr = $aArray2;
        $arr1_is_big = 0;
        $arr2_is_big = 1;
    } else {
        $small_arr = $aArray1;
        $big_arr = $aArray2;
        $arr1_is_big = 0;
        $arr2_is_big = 0;
    }
    $aReturn = array();

    foreach($big_arr as $mKey => $mValue) {
        if(array_key_exists($mKey, $small_arr)) {
            if(is_array($mValue)) {
                $aRecursiveDiff = arrayRecursiveDiff($mValue, $small_arr[$mKey]);
                if(count($aRecursiveDiff)) {
                    $aReturn[$mKey] = $aRecursiveDiff;
                }
            } else {
                if($mValue != $small_arr[$mKey]) {
                    $aReturn[$mKey] = $mValue;
                }
            }
        } else {
            $aReturn[$mKey] = $mValue;
        }
    }
    if($arr1_is_big)
        $aReturn["arr1_is_big"] = $arr1_is_big;

    if($arr2_is_big)
        $aReturn["arr2_is_big"] = $arr2_is_big;

    return ($aReturn);
}


text:
Q: CTS-Search unique element values for specific attribute I'm looking for a search routine to give me a list of all unique values of element Brand with attribute 'Heineken'. So in this case; Can, Crate.
I try to do this:
let $query := cts:element-attribute-values(xs:QName("p:brand"), xs:QName("name"), 'Heineken')

for $temp in cts:search(fn:doc(), (cts:query($query)))

return fn:distinct-values($temp)

For this I create a: range element attribute index on brand/name.
My ultimate goal is to create a list of unique values of Merlot for every document with Heineken/Can. In the example below; Glass.

saturday.xml
<thedrinksihad>
    <brand name='Heineken'>Can</brand>
    <brand name='Grolsch'>Bottle</brand>
    <brand name='Merlot'>Glass</brand>
</thedrinksihad>

sunday.xml
<thedrinksihad>
    <brand name='Heineken'>Crate</brand>
    <brand name='Grolsch'>Can</brand>
    <brand name='Merlot'>Bottle</brand>
</thedrinksihad>

A: There are probably several ways to do this, but since you are starting out using a range index, this answer will use them. You'll need another range index on xs:QName('p:brand').
This query will return all of the documents that contain a <brand name='Heineken'>Can</brand> and any <brand name='Merlot'>. Then it filters the output to select only the Merlot brands and takes the distinct-values of that sequence:
let $merlots :=
  cts:search(//p:thedrinksihad,
      cts:and-query((
        cts:element-query(xs:QName('p:brand'),
          cts:element-attribute-range-query(xs:QName("p:brand"), xs:QName("name"), '=', 'Merlot')),
        cts:element-query(xs:QName('p:brand'),
          cts:and-query((
            cts:element-attribute-range-query(xs:QName("p:brand"), xs:QName("name"), '=', 'Heineken'),
            cts:element-range-query(xs:QName("p:brand"), '=', 'can'))))
      ))
    )/p:thedrinksihad/p:brand[@name eq 'Merlot']
return distinct-values($merlots)

Just a note that cts:*-values functions can be tricky. This is a scenario where it seems like it might be ideal, since they only return distinct values. However, the query passed to a  cts:*-values function runs "unfiltered", which means it will return all values from any matching fragments. In this case that means all the <brand> values in a matching doc, including ones besides those from <brand name='Merlot'>.


text:
Q: Sending only specified javascript files to the front-end I have an app like this
/app
    /views
        index.jade
    /controllers
        controllers1.js
        controllers2.js
server.js

Inside server.js I use app.use(express.static(path.join(__dirname, 'app'))); and all requests render index.jade. Inside index.jade I call the controllers with regular <script> tags.
My Problem
I'm uncomfortable with exposing all my scripts to the front-end. e.g.: I don't want people to type www.myurl.com/controllers/controllers1.js and see the script, because I don't want to show all my business logic right away, especially to users who aren't logged in.
Question
Having deactivated express.static(), is it possible through express Middleware to get the contents a certain javascript files and include/send them to index.jade? Ideally I want to control which script files the front-end can receive/see.
There's probably many ways to do this. Should I be using some kind of library for this (maybe Requirejs, idk much about it)?

A: deactivating express.static is not required
use public folder for all the content which you want to expose to users
like
app
->controllers
public
->js
->->jQuery.js
->->abc.js
->css
->->bootstrap.css
htmls goes here
and use express.static(__dirname,'public') to expose public folder.

A: One strategy I've used is to separate the public and private node files. The public libraries implement dual purpose node/browser code. I use a folder structure that looks something like this:
/app
    /lib
        /public
            public_library.js
        private_library.js

Then it's simple to expose the public directory so that you can do both:
var mylib = require('public/public_library.js');

in your node files and
<script src="lib/public/public_library.js"></script>

in your browser facing code.
Put all libraries you want to expose in the public directory. Put all libraries you want to keep private outside of the public directory.


text:
Q: Possible to have Communities Header Image change based on user profile? I'm on a project to create our company's employee intranet and have a branding inquiry. Without having to create communities for each division (total of 3 divisions for now), I'd like to know if there is any way to swap either the company logo and/or the header image based on the end-user's profile?

A: As of winter'17, Not possible Out of the box. But you could have a custom theme layout built for a community that could change the logo based on logged in user profile.
https://developer.salesforce.com/docs/atlas.en-us.lightning.meta/lightning/components_config_for_builder_theme_layout.htm
Theme Layout is a lightning component and you can call apex to find out image to use based on user profile.
Images can either be stored in documents or site.com assets.


text:
Q: BackboneJS with normal php server I'm new to backboneJS so i have a problem sync the data from PHP server with backbone that i dont even get the json data from the php server to backbone model!Help me
Here is my php code
$data = array('1'=>array('id'=> 1, 'description'=>'Pick up milk', 'status'=> 'incomplete' ));
echo json_encode($data);

and the backbone js code
<html>
    <head>
        <script src="jquery-1.9.0.min.js" type="text/javascript"></script>
        <script src="underscore-min.js" type="text/javascript"></script>
        <script src="backbone.js" type="text/javascript"></script>
    </head>
    <script type="text/javascript">
         var TodoItem = Backbone.Model.extend({});
         var todoItem = new TodoItem();
         todoItem.url = '/backboneJS/todo.php';
         console.log(todoItem.fetch());
    </script>
    <body>

    </body>
</html>

I cant get the json data from the php to the backbone.What wrong with my code ?

A: <!doctype html>
<html>
<head>
    <script src="http://code.jquery.com/jquery-2.0.3.min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.5.1/underscore-min.js" type="text/javascript"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.0.0/backbone-min.js" type="text/javascript"></script>
</head>
<body>

</body>
<script type="text/javascript">
    var TodoModel = Backbone.Model.extend({
        urlRoot: '/backboneJS/todo.php',
        initialize: function(){
            // Place init message or else
        }
    });

    var todoItem = new TodoModel();

    todoItem.fetch({
        success: function(todoResult){
            console.log(todoResult);
            console.log(todoItem.get(1));
        }
    });

</script>
</html>

Sticking to design pattern also, if you call your todoItem outside of nested function its likely to be executed before the actual fetch() is performed. Tested locally.


text:
Q: how to display datepicker in android Fragment I am using Fragment which is an instance of Fragment and not of DialogFragment
I am displaying form inside this fragment, and one of the field is DateField
I want to have date picker component for that field in Fragment
I did google most of the search result shows how to use DialogFragment to have  DatePicker and then use show() method of Fragment
which isn't working in my case because of type mismatch of Fragment and DialogFragment
Any example or idea would be helpful

A: use this code . I used this datepicker in my fragment ACTIVITY
final Calendar c = Calendar.getInstance();
        mYear = c.get(Calendar.YEAR);
        mMonth = c.get(Calendar.MONTH);
        mDay = c.get(Calendar.DAY_OF_MONTH);

        DatePickerDialog dpdFromDate = new DatePickerDialog(getActivity(), mDateSetListener, mYear, mMonth,
                  mDay);
        dpdFromDate.show();

        dpdFromDate.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
               if (which == DialogInterface.BUTTON_NEGATIVE) {
                    //et_to_date.setText("");
                    et_from_date.setText("");
               }
            }
        });


text:
Q: gdb on macOS Sierra 10.12.4 There are lots of help around regarding the incompatibility of Sierra and gdb, and everyone says that the best solution is waiting.
The problem seems to still persist, could anyone please help me how I can solve it?
I have already tried this and it does not work on my Sierra.
GDB kind of doesn't work on macOS Sierra
Thanks

A: A fix has been created, but not merged and released yet.  In the meantime, I have patched the most recent release of GDB with the changes and have things working with the latest version of Sierra.  You can access my repo below and compile from scratch.  Be sure to code sign the new binary and "set startup-with-shell off" in .gdbinit.
https://github.com/joshwells/binutils-gdb

A: None GDB 7.11 or 7.12.1 will not work on Sierra 10.12.4 In short it's  because of Apple security upgrade. We need to wait for re-enabling when some new version will shows up.
Easy WA is to use LLDB as a debugger for now. Sample instructions here
Another LLDB instruction here


text:
Q: how to save my image while changing the orientation of my phone in androidStudio using Kotlin how to save the image while changing the orientation of my android app And this is basically a simple roll dice app i.e. base on the random number  and on the basis of this we can easily choose image using when() in kotlin
package com.example.rollingdice
    import android.location.Address
    import android.media.Image
    import androidx.appcompat.app.AppCompatActivity
    import android.os.Bundle
    import android.os.PersistableBundle
    import android.widget.Button
    import android.widget.ImageView
    import android.widget.TextView
    import javax.crypto.KeyGenerator
    import kotlin.properties.Delegates
    import kotlin.random.Random

    abstract class MainActivity : AppCompatActivity() {
        lateinit var showingResult:ImageView
        lateinit var diceButton:Button
        lateinit var result
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            diceButton=findViewById(R.id.rollDice)
            showingResult=findViewById(R.id.iv)
            diceButton.setOnClickListener {
                rollingDice()
            }
        }
 // accordin to me this function is use to save the data or image while changing the
    orientation
        override fun onSaveInstanceState(outState: Bundle, outPersistentState: PersistableBundle) {

            super.onSaveInstanceState(outState, outPersistentState)
            outState.putInt("img",result)
        }
      //private function named as rollingDice()

        private fun rollingDice() {
           var number : Int= Random.nextInt(6)+1
       // taking random number input in when()
            when (number){
              // taking number in when() statement to choose the image
               1 -> R.drawable.dice_1
               2 -> R.drawable.dice_2
               3 -> R.drawable.dice_3
               4 -> R.drawable.dice_4
               5 -> R.drawable.dice_5
               else -> R.drawable.dice_6
             // else condition give the dice_6 name image as a result
           }
            showingResult.setImageResource(result)
        //i'm taking the result as  aimage in the image view
        }

    }


text:
Q: ansible: lineinfile for several lines? The same way there is a module lineinfile to add one line in a file, is there a way to add several lines?
I do not want to use a template because you have to provide the whole file.
I just want to add something to an existing file without necessarily knowing what the file already contains so a template is not an option.

A: It's not ideal, but you're allowed multiple calls to lineinfile. Using that with insert_after, you can get the result you want:
- name: Set first line at EOF (1/3)
  lineinfile: dest=/path/to/file regexp="^string 1" line="string 1"
- name: Set second line after first (2/3)
  lineinfile: dest=/path/to/file regexp="^string 2" line="string 2" insertafter="^string 1"
- name: Set third line after second (3/3)
  lineinfile: dest=/path/to/file regexp="^string 3" line="string 3" insertafter="^string 2"

A: I was able to do that by using \n in the line parameter.
It is specially useful if the file can be validated, and adding a single line generates an invalid file.
In my case, I was adding AuthorizedKeysCommand and AuthorizedKeysCommandUser to sshd_config, with the following command:
- lineinfile: dest=/etc/ssh/sshd_config line='AuthorizedKeysCommand /etc/ssh/ldap-keys\nAuthorizedKeysCommandUser nobody' validate='/usr/sbin/sshd -T -f %s'

Adding only one of the options generates a file that fails validation.

A: Here is a noise-free version of the solution which is to use with_items:
- name: add lines
  lineinfile:
    dest: fruits.txt
    line: '{{ item }}'
  with_items:
    - 'Orange'
    - 'Apple'
    - 'Banana'

For each item, if the item exists in fruits.txt no action is taken.
If the item does not exist it will be appended to the end of the file.
Easy-peasy.

A: You can use the lineinfile built-in in a loop. Here's an example:
- name: Set some kernel parameters
  lineinfile:
    dest: /etc/sysctl.conf
    regexp: "{{ item.regexp }}"
    line: "{{ item.line }}"
  loop:
    - { regexp: '^kernel.shmall', line: 'kernel.shmall = 2097152' }
    - { regexp: '^kernel.shmmax', line: 'kernel.shmmax = 134217728' }
    - { regexp: '^fs.file-max', line: 'fs.file-max = 65536' }

A: If you need to configure a set of unique property=value lines, I recommend a more concise loop. For example:
- name: Configure kernel parameters
  lineinfile:
    dest: /etc/sysctl.conf
    regexp: "^{{ item.property | regex_escape() }}="
    line: "{{ item.property }}={{ item.value }}"
  with_items:
    - { property: 'kernel.shmall', value: '2097152' }
    - { property: 'kernel.shmmax', value: '134217728' }
    - { property: 'fs.file-max', value: '65536' }

Using a dict as suggested by Alix Axel and adding automatic removing of matching commented out entries,
- name: Configure IPV4 Forwarding
  lineinfile:
    path: /etc/sysctl.conf
    regexp: "^#? *{{ item.key | regex_escape() }}="
    line: "{{ item.key }}={{ item.value }}"
  with_dict:
    'net.ipv4.ip_forward': 1

A: You can try using blockinfile instead.
You can do something like
- blockinfile: |
    dest=/etc/network/interfaces backup=yes
    content="iface eth0 inet static
        address 192.168.0.1
        netmask 255.255.255.0"

A: To add multiple lines you can use  blockfile:
- name: Add mappings to /etc/hosts
  blockinfile:
    path: /etc/hosts
    block: |
      '10.10.10.10  server.example.com'
      '10.10.10.11  server1.example.com'

to Add one line you can use lininfile:
- name: server.example.com in /etc/hosts
  lineinfile:
    path: /etc/hosts
    line: '192.0.2.42 server.example.com server'
    state: present

A: To add multiple lines you can use lineinfile module with with_items also including variable vars here to make it simple :)
---
- hosts: localhost  #change Host group as par inventory
  gather_facts: no
  become: yes
  vars:
    test_server: "10.168.1.1"
    test_server_name: "test-server"
    file_dest: "/etc/test/test_agentd.conf"

  - name: configuring test.conf
    lineinfile:
      dest: "{{ item.dest }}"
      regexp: "{{ item.regexp }}"
      line: "{{ item.line }}"
    with_items:
      - { dest: '"{{ file_dest }}"', regexp: 'Server=', line: 'Server="{{test_server}}"' }
      - { dest: '"{{ file_dest }}"', regexp: 'ServerActive=', line: 'ServerActive="{{test_server}}"' }
      - { dest: '"{{ file_dest }}"', regexp: 'Hostname=', line: 'Hostname="{{test_server_name}}"' }

A: To add multiple Lines in a configuration file you can use " " instead of ' ' and escape sequence \n for the new line in lineinfile ansible module:
- name: Configure core-site.xml
  lineinfile:
    path: /etc/hadoop/core-site.xml
    insertafter: '^<configuration>'
    line: "Line 1 \n Line 2 \n Line 3"

A: The solution that fit my use-case (network automation):
- name: "create block in own file per host"
  blockinfile:
     path: "/dir/logs/{{ inventory_hostname }}.txt"
     create: true
     block: "some commands"
     ...

- name: "add more line in block (even if already executed on another host)"
  lineinfile:
     line: "{{ item }}"
     ...
  loop: "{{ more_commands_1 | default([]) +
    more_commands_2 | default([]) }}"

- name: "assemble all files in one"
  assemble:
    src: "/dir/logs/"
    dest: "/dir/logs/all_hosts.txt"
    ...

note: I used those modules with "check_mode: false" and "delegate_to: localhost"
Would be glad to use a more clever solution if it exists.


text:
Q: How to localize pimcore? I need to localize pimcore .I have read the help on that, from the pimcore wiki:
http://www.pimcore.org/wiki/display/PIMCORE/Website+Translations
But i don't get it(since i am a newbie to development or what ever it is i'm doing!!).
It says something about registering locale in php file named action.
it seems so complicated .
Can anybody help?

A: It is pretty easy to localize your website actually.

*

*First add all languages you want to support, this is done in the admin panel by going to Settings -> System, expand "Localization & Internationalization" and there you will have textbox for adding languages. Enter all languages and the press "Save" at the bottom right.

*Next step is to add the translations, this is done by opening the Extras -> Translations -> Shared Translations in the admin panel. Press the + at top to add a word or sentence used for translation, give it a name and then enter the translation for all chosen languages:

*Time to code, in your view or layout files (for example: /website/views/scripts/default/default.php), where you want a translation add the following code:
<?php echo $this->translate("hello"); ?>

*Set the language of the documents, this is done by opening a document in Pimcore admin, go to the tab "Properties", and on the right side there will be a language setting, select the language for this document and press "Save & Publish":

Now when you navigate to this document (or look at the preview tab) you will see your translated word where you placed the translate code.
Translate the Admin UI
To translate the Admin UI, go to Extras > Download System Languages in Pimcore, and there press the "+" on the language you want to download. To add to those translations you go to: http://www.pimcore.org/en/community/translations. (Read more here: http://www.pimcore.org/wiki/display/PIMCORE/Translations)
You then choose which language to use in the admin UI by going to Settings -> System and then expanding the "General" section, and there you will find "Default Language in Admin-Interface:".


text:
Q: Git clone error warning: refname '' is ambiguous. Git normally never creates a ref that ends with 40 hex characters Got this error during cloning
remote: warning: refname '4e810d87701e09df2949cb33e731052aa05d2c76' is ambiguous.
remote: Git normally never creates a ref that ends with 40 hex characters
remote: because it will be ignored when you just specify 40-hex. These refs
remote: may be created by mistake. For example,
remote:
remote:   git checkout -b $br $(git rev-parse ...)
remote:
remote: where "$br" is somehow empty and a 40-hex ref is created. Please
remote: examine these refs and maybe delete them. Turn this message off by
remote: running "git config advice.objectNameWarning false"

A: In my case it was a branch and not a tag.
To find if the ref is a tag or branch:
$ git branch -a | grep 4e810d87701e09df2949cb33e731052aa05d2c76
$ git tag | grep 4e810d87701e09df2949cb33e731052aa05d2c76

Be aware you might want to save the branch or tag before you delete it. (Using a different name, of course.)
Here's how I got rid of it:
$ git branch -d 4e810d87701e09df2949cb33e731052aa05d2c76
$ git push origin :4e810d87701e09df2949cb33e731052aa05d2c76

In my case the error only came up during a git clone --mirror--it wasn't a problem normally.

A: During cloning I got this error message and found that a tag was created with this name (like a 40-hex ref).
When you get this error, you can look for branch or tag names with the ambiguous value and remove it if the ref is not required
$ git tag | grep 4e810d87701e09df2949cb33e731052aa05d2c76
4e810d87701e09df2949cb33e731052aa05d2c76

$ git tag -d 4e810d87701e09df2949cb33e731052aa05d2c76


text:
Q: Automation of SQL query I have recently started working as an Analyst.Part of my job is to run SQL queries on a daily basis and paste the results in an Excel sheet. This sometime becomes tedious. I would like to automate this process i.e. the SQL query should run automatically and the result set(s) should be copied automatically into an Excel sheet(path will be specified by me). Can I do this? If yes, then how?
P.S. We use SQLyog(Open Source) to run SQL queries and Microsoft Excel 2010 to paste and show data.

A: You could always export your data as comma separated result and open it in Excel.
Even if your tools does not support it could be easily created a column that is a concatenation of all your columns comma separated.
Then save automatically result as a .csv file to open in Excel.

A: If you want to automate the data publication process, I think a better way is to use 'cron' to schedule you daily query in a shell script, and store the csv data file in a certain directory or send it to your mailbox.


text:
Q: Svelte - ReferenceError: buffer is not defined Trying to setup a WebRtc connection in my new Svelte app, and am hitting this error whenever I try to import a library.

ReferenceError: buffer is not defined

Example Code: https://github.com/nickgrealy/svelte-webrtc (link also below)
Here are the steps to reproduce: install the library, then import it on a *.svelte component.
e.g. peerjs
npm i peerjs
import Peer from "peerjs";

also occurs for this library - simple-peer
npm i simple-peer
import Peer from "simple-peer";

Both give the following error:
Uncaught ReferenceError: buffer is not defined
    at main.ts:14

Not really sure what to try next... writing vanilla Javascript? Try other libraries?
I don't know how to configure rollup... (hoping it's something simple that one of you have come across before!).
N.B. not sure if relevant, I converted the Svelte project to Typescript (using the inbuilt script).
** Added code to reproduce **
https://github.com/nickgrealy/svelte-webrtc/blob/main/src/main.ts#L2
Console logs from yarn dev
yarn run v1.22.10
$ rollup -c -w
rollup v2.56.3
bundles src/main.ts → public/build/bundle.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on "buffer" and "events". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node
LiveReload enabled
(!) Plugin node-resolve: preferring built-in module 'buffer' over local alternative at '/Users/userx/svelte-webrtc/node_modules/buffer/index.js', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning
(!) Circular dependencies
node_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_readable.js
node_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> node_modules/readable-stream/lib/_stream_duplex.js
node_modules/readable-stream/lib/_stream_duplex.js -> node_modules/readable-stream/lib/_stream_writable.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_duplex.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_duplex.js
node_modules/readable-stream/lib/_stream_readable.js -> node_modules/readable-stream/lib/_stream_duplex.js -> /Users/userx/svelte-webrtc/node_modules/readable-stream/lib/_stream_readable.js?commonjs-proxy -> node_modules/readable-stream/lib/_stream_readable.js
(!) Missing global variable names
Use output.globals to specify browser global variable names corresponding to external modules
buffer (guessing 'buffer')
events (guessing 'require$$0$1')
created public/build/bundle.js in 2.9s

[2021-09-05 00:31:10] waiting for changes...

> svelte-app@1.0.0 start
> sirv public --no-clear "--dev"

  Your application is ready~!

  - Local:      http://localhost:5000
  - Network:    Add `--host` to expose

────────────────── LOGS ──────────────────

  [00:31:18] 200 ─ 5.50ms ─ /
  [00:31:18] 200 ─ 0.60ms ─ /global.css
  [00:31:18] 200 ─ 0.71ms ─ /build/bundle.css
  [00:31:18] 200 ─ 1.35ms ─ /build/bundle.js
  [00:31:22] 200 ─ 0.76ms ─ /global.css
  [00:31:22] 200 ─ 1.83ms ─ /build/bundle.css
  [00:31:22] 200 ─ 3.96ms ─ /build/bundle.js.map

** Update **
Added the node plugin, now getting this error...

Uncaught ReferenceError: require$$1$1 is not defined

... with these logs.
yarn run v1.22.4
$ rollup -c -w
rollup v2.56.3
bundles src/main.ts → public/build/bundle.js...
(!) Missing shims for Node.js built-ins
Creating a browser bundle that depends on "buffer". You might need to include https://github.com/snowpackjs/rollup-plugin-polyfill-node
LiveReload enabled
(!) Circular dependency
polyfill-node.global.js -> polyfill-node.global.js
(!) Missing global variable name
Use output.globals to specify browser global variable names corresponding to external modules
buffer (guessing 'require$$1$1')
created public/build/bundle.js in 2.6s

[2021-09-05 00:57:04] waiting for changes...
npm WARN lifecycle The node binary used for scripts is /var/folders/05/qnr367194ss7ktgg_c2r57440000gp/T/yarn--1630767421122-0.4620373266212361/node but npm is using /Users/userx/.nvm/versions/node/v14.17.3/bin/node itself. Use the `--scripts-prepend-node-path` option to include the path for the node binary npm was executed with.

> svelte-app@1.0.0 start /Users/userx/svelte-webrtc
> sirv public --no-clear "--dev"

  Your application is ready~!

A: When using peerjs browserify is not required and change output format to cjs in rollup.config.js.
If you want to keep iife then you need to disable strict mode in rollup.config.js under output property strict: false because the library has some issue.


text:
Q: Drawing Multiple shapes in openGL/GLUT I have this code and I am trying to draw two hexagons but only one will show up. This is my first time using openGL although i've used C++ for some time now. The first hexagon shows up but the second one is nowhere to be seen. sorry for all the comments in there I was trying to draw 121 of the hexagons in a for loop.
#include <iostream>
#include <GL/glut.h>
#include <stdlib.h>
#include <string>
#define _USE_MATH_DEFINES
#include <math.h>
void displayCall(){
    int x = 0;
    int y = 0;
    glClearColor(1, 1, 1, 1);
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(-2.0, 2.0, -2.0, 2.0, -2.0, 500.0);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    glScalef(.005, .005, .005);

// Enable polygon offsets, and offset filled polygons forward by 2.5
glEnable(GL_POLYGON_OFFSET_FILL);
glPolygonOffset(-2.5f, -2.5f);
// Set the render mode to be line rendering with a thick line width
glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
glLineWidth(3.0f);
// Set the colour to be white
//glColor3f(1.0f, 1.0f, 1.0f);

//outline color
glColor3f(0, 0, 0);
//for (int i = 0; i < 11; i++){
//  for (int j = 0; j < 11; j++){
        glTranslatef(-300 + x, 300 - y, 0);
        glBegin(GL_POLYGON);
        for (int i = 0; i < 6; ++i) {
            glVertex2d(50 * sin(i / 6.0 * 2 * M_PI),
                50 * cos(i / 6.0 * 2 * M_PI));
        }
        glEnd();
        glTranslatef(-200 + x, 300 - y, 0);
        glBegin(GL_POLYGON);
        for (int i = 0; i < 6; ++i) {
            glVertex2d(50 * sin(i / 6.0 * 2 * M_PI),
                50 * cos(i / 6.0 * 2 * M_PI));
        }
        glEnd();
    //  x += 50;
//  }
    //y += 50;
    //x = 0;
//  }

glutSwapBuffers();
}

int main(int argc, char **argv){
std::cout << "Test" << std::endl;

char* buf = 0;
size_t sz = 0;
if (_dupenv_s(&buf, &sz, "DISPLAY")){
    std::string display(("DISPLAY"));
    std::cout << display << std::endl;
}
else{
    std::cout << "Empty" << std::endl;
}
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutInitWindowSize(600, 600);
glutCreateWindow("RED");
glutDisplayFunc(displayCall);
glutMainLoop();
return 0;
}

A: You are not resetting transformation matrix.
Try this
   glPushMatrix();
   glTranslatef(-300 + x, 300 - y, 0);
   glBegin(GL_POLYGON);
   for (int i = 0; i < 6; ++i) {
        glVertex2d(50 * sin(i / 6.0 * 2 * M_PI),
            50 * cos(i / 6.0 * 2 * M_PI));
    }
    glEnd();
    glPopMatrix();
    glPushMatrix();
    glTranslatef(-200 + x, 300 - y, 0);
    glBegin(GL_POLYGON);
    for (int i = 0; i < 6; ++i) {
        glVertex2d(50 * sin(i / 6.0 * 2 * M_PI),
            50 * cos(i / 6.0 * 2 * M_PI));
    }
    glEnd();
    glPopMatrix();


text:
Q: Changing Text CSS On Scroll With jQuery I'm trying to implement a header that becomes smaller once a user scrolls on my site. The logo and header part is done, but when I try to resize the text for the navigation, something becomes broken and the header no longer shrinks on scroll. Here is my broken code with the text resize: (#HOME is the ID for styles associated with a navigation link):
$(function () {
    $('#Header').data('size', 'big');
});

$(window).scroll(function () {
    if ($(document).scrollTop() > 0) {
        if ($('#Header').data('size') == 'big') {
            $('#Header').data('size', 'small');
            $('#Header').stop().animate({
                height: '60px'
            }, 600);
            $('#Logo').stop().animate({
                height: '40px',
                width: '40px'
            }, 600);
            $('#Logo:hover').stop().animate({
                height: '40px',
                width: '40px'
            }, 600);
            $('#HOME').stop().animate({
                font - size: '14px',
                top: '20px'
            }, 600);
        }
    } else {
        if ($('#Header').data('size') == 'small') {
            $('#Header').data('size', 'big');
            $('#Header').stop().animate({
                height: '100px'
            }, 600);
            $('#Logo').stop().animate({
                height: '85px',
                width: '81px'
            }, 600);
            $('#Logo:hover').stop().animate({
                height: '40px',
                width: '40px'
            }, 600);
            $('#HOME').stop().animate({
                font - size: '17px',
                top: '40px'
            }, 600);
        }
    }
});

Also, I'd appreciate if someone told me about a neater way to do this :P

A: $(function () {
    $('#Header').data('size', 'big');

    $(window).scroll(function () {
        if ($(document).scrollTop() > 0) {
            if ($('#Header').data('size') == 'big') {
                $('#Header').data('size', 'small');
                $('#Header').stop().animate({
                    height: '60px'
                }, 600);
                $('#Logo').stop().animate({
                    height: '40px',
                    width: '40px'
                }, 600);
                $('#Logo:hover').stop().animate({
                    height: '40px',
                    width: '40px'
                }, 600);
                $('#HOME').stop().animate({
                    font - size: '14px',
                    top: '20px'
                }, 600);
            }
        } else {
            if ($('#Header').data('size') == 'small') {
                $('#Header').data('size', 'big');
                $('#Header').stop().animate({
                    height: '100px'
                }, 600);
                $('#Logo').stop().animate({
                    height: '85px',
                    width: '81px'
                }, 600);
                $('#Logo:hover').stop().animate({
                    height: '40px',
                    width: '40px'
                }, 600);
                $('#HOME').stop().animate({
                    font - size: '17px',
                    top: '40px'
                }, 600);
            }
        }
    });
});

The event needs to be bound in the document.ready or in this implementation $(function () { ... }); method. Else it will likely bind before the control is ready.


text:
Q: How parameter.method() method works? Well, i was thinking about that kind of methods.
They dont recive parameters, but they work with them.
An example: .replace(Char, Char)  of String API, it works with a String followed by a dot.
Like:
String test = "= Text = without = equals";
String output = test.replace("=","");

How it works without  receive the parameter test?
I'm just being curious, want to do a method like these.
Sorry for my bad english!
Thanks.

A: These are instance methods, which means that they require an instantiated class object to operate. So, the string class knows the value of test in your example, because it has access to the instantiated data.
To create these types of methods, simply define them within your class and do not mark them as static.

A: String is an object. The class definition is part of the Java standard library. That definition includes the replace method.
Since String is a final class you can not subclass it to add additional methods. So you can not do what you are trying to do.

A: Let's say you build a new type of String, that only does replace stuff (why not?!):
public class MyString {
    private final String s;
    public MyString(String s) {
        this.s = s;
    }
    public String replace(String search, String replace) {
        return s.replace(search, replace);
    }
}

Now you can call it like this:
MyString myString = new MyString("= Text = without = equals");
String output = myString.replace("=", "");

Et voila, you have done the same "trick"! And you can see how it works: your MyString object keeps some data internally (the s variable) and can access that data from its methods.


text:
Q: How can I move a file to another user's directory? I'm using CentOS 6 and I'm trying to move a file from USER A to USER B but I keep getting permission denied.
What do I need to edit to allow to me to put files from one user's directory into another's?

A: You need the rights to read the file from user A, and to write the file to user B's location.
There are several ways to archive this:
1)
As user A (assumed she can read her own files) get WRITE permission to user B's location.
This means being in a group which is allowed to w to the destination directory and which is allowed to access (x) the directory path to the destination.
Example:
cd /home/user/A/
ls -l testfile
-rw-------  1 userA  users  18 Dec 31 16:31 testfile

Notice the r. User A is allowed to read her own file
cp testfile /home/userB/testdir

User A will need to traverse to the folders /home, /home/userB and /home/userB/testdir. All of these need to be 'x' for her. She wants to write to the folder 'testdir' and thus she also needs 'w' on that folder.
That 'w' can be in the user, group or other part. But if you set it in 'other' then every user can write to it. Thus you usually make shared files or shared folders part of a group. (e.g. in /etc/group create a group 'sales' and add both users to that).

2)
As user B: (which is assumed to be able to write in his own folder).
Get read permission on the file in userA's folder and the right to traverse there. (same as in 1).
You now can copy the file to your own location. You can not delete it from user A's folder unless you also have the rights to do that. So you can copy but not move.

3)
As a user with uid 0 (usually root, toor, admin):
mv /home/userA/testfile /home/userB/
Notice that the file is still owned by userA, and that user B might not have the rights to work on the file. You can correct this with chown.

4)
Without the heavy guns, as often done by two users:
As UserA: cp testfile /tmp/
As userB: cp /tmp/testfile ~
As userA: rm /tmp/testfile

This is not the most secure way (other can see the file while it is in /tmp), but I think that this is the most common solution.

If you want to do this often then I strongly suggest creating a group and giving all users in that group rights to a shared location.
Not asked, but a solution like this is often practical (shown with music, but it might as well be sales reports).
vim /etc/group and add a line like this: shared_music:*:3141:userA,UserB,UserC. This will create a group called shared_music, give it a number, and select which users will belong to that group.
Then make folder owned by that group.
cd /usr/local/
md our_ultimate_shared_music_collection
chgrp shared_music our_ultimate_shared_music_collection
chmod g+rwx our_ultimate_shared_music_collection
chmod g+S our_ultimate_shared_music_collection

Make a folder in a sane location. Set the group and then allow all people in that group to read, write and cd into that folder. The last command (make group setuid) means that newly created subfiles inherit the same group as the directory, and newly created subdirectories inherit the set-group-ID bit of the parent directory. This prevent userA from writing files to that directory which USerB (or anyone but A) could not deleted or rename.

A: You need permissions to access that directory. Both write and execute on the directory in question and write in any files your overwriting.
The easiest way is to sudo mv /dir1/file /dir2/file but you should probably read Quick and Dirty Guide to Linux File Permissions first.

A: Assuming that at least one of the users have sudo privileges, execute the following while logged in as that user (i.e., with sudo privileges):
sudo mv /home/userA/file_name /home/userB

It will prompt you for the corresponding user's password.
Otherwise, login as the root, and execute the above without the "sudo" at the beginning.


text:
Q: Javascript interpreter implementation: what needs to be stored in memory? I'm implementing a Javascript interpreter in a high-level language.  I haven't done this before, so I'm getting my bearings...learning about shunting-yard algorithms and basics like that.  Right now, I'm trying to rough out the implementation of functions, and I want to make sure I'm clear on what needs to be stored in memory.  It seems that the number of things one needs to remember is smaller than one might think:

*

*The statements (what should these look like in memory?)

*The call stack, which is a stack of open contexts.

*Each context contains: 1: Variables, and 2: A pointer to the parent context, and a copy of the statement that triggered the call, with its expressions and their current state of evaluation. 3: an indicator of whether the function was called with new.

*For closures, we also have variables in some closed contexts.  These are contexts that might still be needed even though they are closed, because there is still a pointer into them, in the form of a function which was created within the closed context.  (And contexts enclosing the closed ones.)

*The current statement, with its current state of evaluation.

*What statement is next.

Is this correct?


text:
Q: How to calculate smallest number with certain number of divisors? From Project Euler problem 500

The number of divisors of 120 is 16. In fact 120 is the smallest number having 16 divisors.
Find the smallest number with 2**500500 divisors. Give your answer modulo 500500507.

It's simple enough to count the divisors of n, eg. in Python len([i for i in range(1,n+1) if n % i == 0]). This is O(n).
I tried brute force search and found the smallest number with 32 divisors is 840, but it's much too slow for the problem above. From the inequality count_divisors(n) <= n, the number is going to be massive.
What do you think? Any ideas? How to calculate smallest number with certain number of divisors?

Edit: I don't think this is a duplicate. This question is more specific, it concerns a particular class of much larger numbers. The other question asks generally. Its answers aren't applicable to this problem, it's a different magnitude.

A: You should use the formula for the number of divisors of integer n:
d(n) = (a1+1)(a2+1)...(ak+1)
where
n = p1a1 * p2a2 *p3a3 *...*pkak
is a unique representation of every integer through powers of its prime divisors. This is a well-known formula, but if one wonders how to get it, note that d divides n if and only if d is of the form p1x1 * p2x2 *p3x3 *...*pkxk, where each of xi is between 0 and ai, so there are ai + 1 possibilities for choosing each of xi. Now just apply the product rule and you get the desired formula.
For fixed d(n) (as in your case), the minimum value of n is obviously obtained by carefully selecting powers of existing primes, or by adding new primes. Let's work through this simple example, 16:
d(x) = (a1+1)(a2+1)...(ak+1) = 16 = 24.
This means that you have at most 4 different primes, therefore:
x = 2a1 * 3a2 *5a3 * 7a4
where ai >= 0. The question is now - in order to get minimum value of x, is it better to increase the powers of 2 (i.e., increment a1), or to use 7 (i.e. take a4=1 instead of a4=0)? Well, it's simple to check, 2*3*5*7 > 23 * 3 * 5 = 120, that's why the 120 is answer in this case.
How to generalize this approach? You should create min-heap where you'll put the powers of primes, taking care that the number of divisors reaches the specified value. In case of 16, this min-heap would contain numbers 2, 3, 5, 7, 22, 32, 24 etc. Why? Because 16 = 24, so each of (ai+1) has to divide 16, i.e. it has to be power of 2. Every time when you add new power, it should increase the left hand side (i.e., the variable d(x)) by power of 2, since your final goal is to find the smallest number with 2500500 divisors. Heap is initialized with first k primes (in the problem statement, k = 500500), and in each step, when you pop px from the heap, p2x is returned and result is multiplied by px. Step-by-step solution for d(x) = 16 = 24:
Step    Heap    d(x)    x
==========================
0      2,3,5,7    1     1
1      3,4,5,7    2     2
2      4,5,7,9    4     6
3      5,7,9,16   8     24
4      7,9,16,25  16    120

HTH.

A: Here is the high level gist of my Javascript - where factorCount represents the number of divisors:

*

*Find the prime factor decomposition of the factorCount

*Generate every unique combination of these prime factors

*For each combination, extract these combination values from the original prime factor array and add one value to this array that is the extracted values multiplied together. Then sort elements in descending order.

*For each array created by the previous step, check which yields the minimal number when computing 2^(b1-1)*3^(b2-1)5^(b3-1)...

*This minimum number computed is the smallest number with factorCount number of divisors
Here's a high level code breakdown of my JavaScript functions:
var primeFactors = findPrimeFactors(factorCount);
var primeFactorCombinations = removeDuplicateArrays(generateCombinations(primeFactors, 1));
var combinedFactorCandidates = generateCombinedFactorCombinations(primeFactors, primeFactorCombinations);
var smallestNumberWithFactorCount = determineMinimumCobination(combinedFactorCandidates);

And here's the full sha-bang:
function smallestNumberByFactorCount(factorCount) {

  function isPrime(primeCandidate) {
    var p = 2;
    var top = Math.floor(Math.sqrt(primeCandidate));
    while(p<=top){
      if(primeCandidate%p === 0){ return false; }
      p++;
    }
    return true;
  }

  function findPrimeAfter(currentPrime) {
    var nextPrimeCandidate = currentPrime + 1
    while(true) {
      if(isPrime(nextPrimeCandidate)){
        return nextPrimeCandidate;
      } else {
        nextPrimeCandidate++;
      }
    }
  }

  function findPrimeFactors(factorParent) {
    var primeFactors = [];
    var primeFactorCandidate = 2;
    while(factorParent !== 1){
      while(factorParent % primeFactorCandidate === 0 && factorParent !== 1 ){
        primeFactors.push(primeFactorCandidate);
        factorParent /= primeFactorCandidate;
      }
      primeFactorCandidate = findPrimeAfter(primeFactorCandidate);
    }
    return primeFactors;
  }

  function sortArrayByValue(a,b){
    return a-b;
  }

  function clone3DArray(arrayOfArrays) {
    var cloneArray = arrayOfArrays.map(function(arr) {
      return arr.slice();
    });
    return cloneArray;
  }

  function doesArrayOfArraysContainArray(arrayOfArrays, array){
    var aOA = clone3DArray(arrayOfArrays);
    var a = array.slice(0);
    for(let i=0; i<aOA.length; i++){
      if(aOA[i].sort().join(',') === a.sort().join(',')){
        return true;
      }
    }
    return false;
  }

  function removeDuplicateArrays(combinations) {
    var uniqueCombinations = []
    for(let c=0; c<combinations.length; c++){
      if(!doesArrayOfArraysContainArray(uniqueCombinations, combinations[c])){
        uniqueCombinations[uniqueCombinations.length] = combinations[c];
      }
    }
    return uniqueCombinations;
  }

  function generateCombinations(parentArray, minComboLength) {
    var generate = function(n, src, got, combinations) {
      if(n === 0){
        if(got.length > 0){
          combinations[combinations.length] = got;
        }
        return;
      }
      for (let j=0; j<src.length; j++){
        generate(n - 1, src.slice(j + 1), got.concat([src[j]]), combinations);
      }
      return;
    }
    var combinations = [];
    for(let i=minComboLength; i<parentArray.length; i++){
      generate(i, parentArray, [], combinations);
    }
    combinations.push(parentArray);
    return combinations;
  }

  function generateCombinedFactorCombinations(primeFactors, primeFactorCombinations) {
    var candidates = [];
    for(let p=0; p<primeFactorCombinations.length; p++){
      var product = 1;
      var primeFactorsCopy = primeFactors.slice(0);
      for(let q=0; q<primeFactorCombinations[p].length; q++){
        product *= primeFactorCombinations[p][q];
        primeFactorsCopy.splice(primeFactorsCopy.indexOf(primeFactorCombinations[p][q]), 1);
      }
      primeFactorsCopy.push(product);
      candidates[candidates.length] = primeFactorsCopy.sort(sortArrayByValue).reverse();
    }
    return candidates;
  }

  function determineMinimumCobination (candidates){
    var minimumValue = Infinity;
    var bestFactorCadidate = []
    for(let y=0; y<candidates.length; y++){
      var currentValue = 1;
      var currentPrime = 2;
      for(let z=0; z<combinedFactorCandidates[y].length; z++){
        currentValue *= Math.pow(currentPrime,(combinedFactorCandidates[y][z])-1);
        currentPrime = findPrimeAfter(currentPrime);
      }
      if(currentValue < minimumValue){
        minimumValue = currentValue;
        bestFactorCadidate = combinedFactorCandidates[y];
      }
    }
    return minimumValue;
  }

  var primeFactors = findPrimeFactors(factorCount);
  var primeFactorCombinations = removeDuplicateArrays(generateCombinations(primeFactors, 1));
  var combinedFactorCandidates = generateCombinedFactorCombinations(primeFactors, primeFactorCombinations);
  var smallestNumberWithFactorCount = determineMinimumCobination(combinedFactorCandidates);

  return smallestNumberWithFactorCount;
}

Paste the above code block into your browser console and you can test it out yourself:
> smallestNumberByFactorCount(3) --> 4
> smallestNumberByFactorCount(4) --> 6
> smallestNumberByFactorCount(5) --> 16
> smallestNumberByFactorCount(6) --> 12
> smallestNumberByFactorCount(16) --> 120
> smallestNumberByFactorCount(100) --> 45360
> smallestNumberByFactorCount(500) --> 62370000
> smallestNumberByFactorCount(5000) --> 4727833110000
> smallestNumberByFactorCount(100000000) --> 1.795646397225103e+40

My algorithm starts shitting the bed when the input gets up to around 100 million... so for Project Euler problem 500 where the input would be 2^500500 (a really, really, really big number) you would need another approach. However, this is a good general approach that gets you pretty far. Hope it helps.
Please leave comments with efficiency optimization suggestions. I would love to hear them.

A: The highest divisor any number has, other than itself, is the half of the number. For example, 120 has a max divisor of 60 other than itself. So, you can easily reduce the range from (n+1) to (n/2).
More over, for a number to have m divisors, the number must be atleast ((m-1) * 2) following the above logic (-1 because the m th number is itself). For example, a number with 4 divisors has to be atleast 6. So, your search for n has a smaller range now.
These two will reduce the runtime a little.

A: Not full answer some hints instead:

*

*the max integer divisor of n is n/2
so no need to check all divisors up to n

*can use prime decomposition
max prime divisor is sqrt(n) so no need to test up to n instead test up to sqrt(n) or up to number than has half of the n bits
m=(2^(ceil(ceil(log2(n))/2)+1))-1

that should speed up things a bit but you need to add the computation of non prime divisors

*this looks like some kind of series (prime decomposition)
divisors  | prime_divisors | non_prime_divisors              | LCM(all divisors)
1         | 1               |                                 | 1
2         | 1,2             |                                 | 2
3         | 1,2             | 4                               | 4
4         | 1,2,3           | 6                               | 6
5         | 1,2             | 4,8,16                          | 16
6         | 1,2,3           | 4,6,12                          | 12
7         | 1,2             | 4,8,16,32,64                    | 64
8         | 1,2,3           | 4,6,8,12,24                     | 24
...
16        | 1,2,3,5        |4,6,8,10,12,15,20,24,30,40,60,120 | 120

so try to find the equation that generates this order and then simply compute the n-th iteration in modulo arithmetics (simple PI operation ... modmul). I can see the even and odd elements have separate equation ...
[edit1] decomposition up to 16 divisors
  1:    1
  2:    1,   2
  3:    1,   2,   4
  4:    1,   2,   3,   6
  5:    1,   2,   4,   8,  16
  6:    1,   2,   3,   4,   6,  12
  7:    1,   2,   4,   8,  16,  32,  64
  8:    1,   2,   3,   4,   6,   8,  12,  24
  9:    1,   2,   3,   4,   6,   9,  12,  18,  36
 10:    1,   2,   3,   4,   6,   8,  12,  16,  24,  48
 11:    1,   2,   4,   8,  16,  32,  64, 128, 256, 512,1024
 12:    1,   2,   3,   4,   5,   6,  10,  12,  15,  20,  30,  60
 13:    1,   2,   4,   8,  16,  32,  64, 128, 256, 512,1024,2048,4096
 14:    1,   2,   3,   4,   6,   8,  12,  16,  24,  32,  48,  64,  96, 192
 15:    1,   2,   3,   4,   6,   8,   9,  12,  16,  18,  24,  36,  48,  72, 144
 16:    1,   2,   3,   4,   5,   6,   8,  10,  12,  15,  20,  24,  30,  40,  60, 120

A: As Miljen Mikic explains, the divisor counting function is determined by the prime factorisation. To calculate n, start at 1 and use a greedy algorithm to double the number of divisors k times, choosing the cheapest factor at each step. The initial costs are the prime numbers, replaced by their square when you use them. After precomputing the first k prime numbers, you can do this quickly with a min-heap. In Python
import primesieve # pip install primesieve
import heapq

def solve(k, modulus=None):
    """Calculate the smallest number with 2**k divisors."""
    n = 1

    costs = primesieve.generate_n_primes(k) # more than necessary

    for i in range(k):
        cost = heapq.heappop(costs)
        heapq.heappush(costs, cost**2)
        n *= cost
        if modulus:
            n %= modulus

    return n

assert solve(4) == 120

if __name__ == "__main__":
    print(solve(500500, 500500507))

A: Phew, I just solved it in java. My "smallest number with 2^n divisors" ended up being represented as a map of primes and their powers.
This puzzle is as much about optimization as anything: get your code working and then refactor hard. It's definitely worth testing up to about 2^30 divisors as there is room for all sorts of second-order bugs to creep in when optimizing. Re-use the results of earlier calculations, try not to sort anything, and stop iterating as soon as you can (NavigableSet and LinkedHashMap were useful). I'm not going to teach my grandmother to efficiently test for primality.
I used java long throughout, but with numbers of this size it's easy to go over Long.MAX_VALUE in the middle of a calculation, remember: (A^2 * B) % C = (A * ((A * B) % C)) % C.
Hope all this motivates rather than gives the game away. Keep going!

A: This is my Code. You can use Sieve to generate Prime numbers. If you have any suggestions to my code please suggest.
def findfactors(num):
    list1=[]
    for i in range(num,1,-1):
        if num%i==0:
            list1.append(i)
    return list1

def getcombinations(num):
    factors=findfactors(num)
    list1=[]
    if num==1:
        return 1
    for i in factors:
        if getcombinations(num//i)!=1:
            list1.append([i,getcombinations(num//i)])
        else:
            list1.append(i)
    return list1

def unloadlist(list1):
    list2=[]
    if type(list1).__name__=="list":
        for i in list1[1]:
            if type(i).__name__=="list":
                i=unloadlist(i)
            if type(i).__name__=="list":
                flag=True
                for j in i:
                    if type(j).__name__=="list":
                        list2.append([list1[0]]+j)
                        flag=False
                if flag==True:
                    list2.append([list1[0]]+i)
            else:
                list2.append([list1[0],i])
        if len(list2)==1:
            list2=list2[0]
    else:
        list2=list1
    return list2

def mergeitems(list1):
    list2=[]
    for i in list1:
        if type(i).__name__=="int":
            list2.append((i,))
        elif type(i).__name__=="list":
            if type(i[0]).__name__!="list":
                list2.append(tuple(sorted(i,reverse=True)))
            else:
                for j in i:
                    list2.append(tuple(sorted(j,reverse=True)))
    set1=set(list2)
    return set1

def find_smallest_number(num):
    #start writing your code here
    list1=getcombinations(num)
    for i in range(0,len(list1)):
        list1[i]=unloadlist(list1[i])
    mainlist=mergeitems(list1)
    possibles=[]
    primes=[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227]
    for i in mainlist:
        num=1
        for j in range(0,len(i)):
            num*=primes[j]**(i[j] - 1)
        possibles.append(num)
    return min(possibles)

num=7
print("The number of divisors :",num)
result=find_smallest_number(num)
print("The smallest number having",num," divisors:",result)

A: The Prime Factorization (PF), in abbreviated form, for the smallest integer having
2**500,500 divisors is shown below:
2**31 * (3...7)**15 * (11...47)**7 * (53...2,713)**3 * (2,719...7,370,029)

The smallest positive integer having 2^n divisors is the product of the sequence of the first n primes and powers of primes.  Powers of primes (pp) are primes raised to the 2^(2^e) power (powers are 2,4,8,16...).  First 3 pp are 4,9 and 16 (2^2,3^2 and 2^4).
Since only prime factors are used in a PF, you will notice that the pp are aggregated with the prime factors.  For n = 500,550 here are some stats or counts:
5 terms in the PF (powers 31,15,7,3,1).
Total Primes (P) = 500,084
Powers of primes(pp) = 416
Total P + pp = n = 500,500  See theorem above.
Single primes (the last term of the PF) total 499,688.

You can calculate this PF (and others for 2^n) using Sage Math and Excel (although with Excel you'll need a prime counting function).
Also, you should check your PF solution. This can be done several ways by assigning weights to the various pp and single primes to check the original n.

A: Fully functional code.
def find_smallest_number(num):
    number2=0

    if(num%8==0):
        number2=min(2**((num/4)-1)*3**1*5**1 , 2**((num//2)-1)*3**1)
    elif(num%9==0):
        number2=2**((num/9)-1)*3**2*5**2
    elif(num%2==0 and num%3==0):
        number2=2**((num/6)-1)*3**2*5**1
    elif((num%4==0)):
        number2=2**((num/4)-1)*3**1*5**1
    elif(num%2==0):
        number2=2**((num/2)-1)*3**1
    else:
        number2=2**(num-1)

    return number2

num=32
print("The number of divisors :",num)
result=find_smallest_number(num)
print("The smallest number having",num," divisors:",result)


text:
Q: How to increment array index I am using arraylist in my java program but the problem is that when i add an item in arraylist its adding on the same index so i want to know that how to increment array index in array list.
ArrayList arr = new ArrayList(500);
StringTokenizer st = new StringTokenizer(line, ":Mode set - Out of Service In Service");
while(st.hasMoreTokens()){
    arr.add(st.nextToken());
}

In above code its keep adding item on the same index i.e. arr[0].

A: There's nothing wrong with your code. I don't believe that it would add to position zero.
Prove it by displaying the contents: System.out.println(arr);

A: You can specify at what index the element must be added:
arr.add(index,st.nextToken());

A: Your code works fine. I cant see any problem.
How do you know whats the value at index 0, I mean are you debugging it?
Is that text really your delimiter ?

A: Do you really need to initalize the ArrayList size? Try your original code changing
ArrayList arr = new ArrayList(500);

for
ArrayList arr = new ArrayList();


text:
Q: Using Thread Object as Key in HashMap I was reading this :
http://tutorials.jenkov.com/java-concurrency/read-write-locks.html
Inside this tutorial ,for writing a re entrant read lock,following code has been used
    public class ReadWriteLock{

      private Map<Thread, Integer> readingThreads =
          new HashMap<Thread, Integer>();

      private int writers        = 0;
      private int writeRequests  = 0;

      public synchronized void lockRead() throws InterruptedException{
        Thread callingThread = Thread.currentThread();
        while(! canGrantReadAccess(callingThread)){
          wait();
        }

        readingThreads.put(callingThread,
           (getAccessCount(callingThread) + 1));
      }

      public synchronized void unlockRead(){
        Thread callingThread = Thread.currentThread();
        int accessCount = getAccessCount(callingThread);
        if(accessCount == 1){ readingThreads.remove(callingThread); }
        else { readingThreads.put(callingThread, (accessCount -1)); }
        notifyAll();
      }

      private boolean canGrantReadAccess(Thread callingThread){
        if(writers > 0)            return false;
        if(isReader(callingThread) return true;
        if(writeRequests > 0)      return false;
        return true;
      }

      private int getReadAccessCount(Thread callingThread){
        Integer accessCount = readingThreads.get(callingThread);
        if(accessCount == null) return 0;
        return accessCount.intValue();
      }

      private boolean isReader(Thread callingThread){
        return readingThreads.get(callingThread) != null;
      }

    }

So I have question,can i use hashmap like this
  private Map<Thread, Integer> readingThreads =
      new HashMap<Thread, Integer>();

I checked Thread class code to check if it overrides equals and hashcode
and find that it doesnt.
So will it be defaut equals and hashcode.
So all will point to same bucket ??
Can anyone please help me understanding how it will be mapped to buckets.
Also,what is needed from programmer side to use thread object as key to hashmap?

A:
So all will point to same bucket ?

No. In java, every class(including Thread) implictly extends from Object class. The equals and hashCode method extend from Object class are enough to make the Thread objects distribute in different buckets.
See the doc of Object.equals:

The equals method for class Object implements the most discriminating
  possible equivalence relation on objects; that is, for any non-null
  reference values x and y, this method returns true if and only if x
  and y refer to the same object (x == y has the value true).

and Object.hashCode:

As much as is reasonably practical, the hashCode method defined by
  class Object does return distinct integers for distinct objects.


text:
Q: Wrong input values in Laravel So, i have 2 forms, one is for sign up, and another is for sign in

Sign Up

    <form action="{{ route('signup') }}" method="post">

            Your E-Mail
            <input class="form-control" type="email" name="su_email" id="email">

            First Name
            <input class="form-control" type="text" name="first_name" id="first_name">

            Password
            <input class="form-control" type="password" name="su_password" id="password">

        {{ csrf_field() }}
        <button class="btn btn-primary">Submit</button>
    </form>

Sign In

    <form action="{{ route('signin') }}" method="post">

            Your E-Mail
            <input class="form-control" type="email" name="si_email" id="email">

            Password
            <input class="form-control" type="password" name="si_password" id="password">

        {{ csrf_field() }}
        <button class="btn btn-primary">Submit</button>
    </form>

Here is my controller
public function postSignUp(Request $request)
{
    $email = $request['su_email'];
    $first_name = $request['first_name'];
    $password = bcrypt($request['su_password']);

    $user = new User();
    $user->email = $email;
    $user->first_name = $first_name;
    $user->password = $password;
    $user->save();
    return redirect()->back();
}
public function postSignIn(Request $request)
{
    if (Auth::attempt(['email' => $request['si_email'], 'password' => $request['si_password']])) {
        return view('dashboard');
    }
    return redirect()->back();
}

So the problem is: when i enter values in "sign in" form, and then go back to page, in my "first_name" field i have "si_email" value, and in "su_password" i have "si_password" value
Why this happens? I didnt set any value in my html.

A: I can't say for sure, but I think it's because the id's are the same on certain inputs. The id attribute should always br unique. It is possible that when the old input is being returned that it is returning it to the wrong id.
Edit
I think you have a syntax error here as well,it might not be whats causing the problem, but it should still be fixed:
if (Auth::attempt(['email' => $request['si_email'], 'password' => $request['si_password']]) {

If you are wondering what the difference is,  i removed a bracket from the end.


text:
Q: show that the function satisfies condition of the lemma Let $(f_n)_{n\geq 0}$ be an eigenfunctions of the compact integral operator
$F$, defined  on $L^2([-1,1])$ by
$$
F(f)(x)=\int_{-1}^1\frac{\sin a(x-y)}{x-y}\,\psi(y)\,\mathrm{d}y, \quad \mbox{here constant}\, a>0.
$$
Functions $(f_n)_{n\geq 0}$ are normalized
by using the following rule,
$$
\int_{-1}^1 |f_{n}(x)|^2\,\mathrm{d}x = 1,\quad \int_{\mathbb R}
|f_{n}(x)|^2\,\mathrm{d}x =\frac{1}{\lambda_n(c)},\quad n\geq 0,
$$
where $(\lambda_n(a))_n$ is the infinite sequence of the eigenvalues of $F$, arranged in the decreasing order $1>
\lambda_0(a)> \lambda_1(a)>\cdots>\lambda_n(a)>\cdots$
and such that $\displaystyle{C_1\left(\frac{a}{ n}\right)^{n-1}\leq \lambda_n(a)\leq C_2 a\left(\frac{a}{n}\right)^{2n}}$ ($C_1, C_2>0$ are absolute constants).
Question: Show that $f_{n}$ satisfies the conditions of the following Lemma:
Lemma:
Let $g\in L^2(R)$. Fix $\epsilon>0$ and define $L$ so that
$$
\int_{-\infty}^{-L}|g(x)|^2\,\mathrm{d}x<\varepsilon^2, \quad \int_{L}^{\infty}|g(x)|^2\,\mathrm{d}x<\varepsilon^2.
$$
Let $S_K$ be the $K$-th partial Hermite expansion
of $g$, that is $S_K=\sum_{k=0}^{K}<g,h_k>h_k$ where $h_k$ is the $k$-th Hermite function. Then,
$$
\left|S_K(x)-\frac{1}{\pi}\int_{-L}^{L}g(y)\frac{\sin N(x-y)}{x-y}\,\mathrm{d}y\right|<\varepsilon(1+\Gamma),
$$
where $\displaystyle{N=\frac{\sqrt{2K+3}+\sqrt{2K+1}}{2}}$ and
$\Gamma=O\left(\frac{1}{K^{1/2}}\right)$.
Thank you.


text:
Q: Repartitioning Lenovo laptop HDD I've recently purchased a Lenovo B570 laptop and decided that I'd like to repartition it.
So I created a Windows disk image using the built in feature and booted the device using an Ubuntu live USB disk.
But after I checked the current partition scheme I noticed there are 2 hidden partitions. One is 200 MB and contains the boot data (e.g. bootmgr, etc.) the other is 15 GB and after mounting it there was again the boot data and some other data such as OneKeyRecovery backup files, a folder named Factory_Process and etc.
Now I'm having second thoughts. What should I do here? I'd very much like to delete everything and start fresh. But would I lose some critical material which is needed for the proper functioning of the device?
Any help and insight is much appreciated.

A: If the 15 gb. partition is a recovery partition, you might want to keep it if you would like to reinstall your OS. You may be able to create recovery disc(s) so that you can keep the option of restoring your OS, but also are able to remove the recovery partition.
You can access the recovery with the 'curved arrow' button on the side of your laptop (the One Key Recovery button).
The Service Partition (the partition without a drive letter) is used by the OneKey recovery system to backup and recover the C partition. This invisible partition requires only 18GB to 20GB of HDD space. The service partition should NOT be deleted otherwise your OneKey recovery will no longer operate.
One advantage of having these partitions is the protection of your personal data. In the event you need to use the OneKey recovery system, the personal data stored on the D drive will not be erased as the files on the C drive are restored (http://forums.lenovo.com/t5/Lenovo-3000-and-Essential/Disk-Partitioning-and-OneKey-Recovery-Feature/td-p/8036)
So if you really do not care about the older OS, and would like to have that extra ~15gb of space, you could repartition and reformat your drive (http://forums.lenovo.com/t5/X-Series-Tablet-ThinkPad-Laptops/Recovery-partition-delete-after-making-recover-dsks/td-p/660751).


text:
Q: Javascript for...of loop over array of objects running one too many times I have an array of objects that I'm iterating through and recording to Google Sheets, and it's working mostly fine, recording all of the objects in the array correctly. However my catch block is running at the end of the loop seemingly because it's trying to iterate over an object that doesn't exist, past the end of the array
UPDATE Even the debugger is seemingly messed up, showing a length of 6 but only 5 items in the array:

const objArr = [
  {sender:'soandso',count:3,lastMessageDate:'2021-09-27', lastMessageSubject: 'Test Subject'},
  {sender:'suchandsuch',count:7,lastMessageDate:'2021-08-27', lastMessageSubject: 'Test Subject 2'},
  {sender:'thisperson',count:2,lastMessageDate:'2021-03-02', lastMessageSubject: 'Test Subject 3'},
  {sender:'thatperson',count:3,lastMessageDate:'2019-09-27', lastMessageSubject: 'Test Subject 4'},
  {sender:'anotherone',count:4,lastMessageDate:'2016-02-14', lastMessageSubject: 'Test Subject 5'},
  ];

const keys = Object.keys(objArr[0]);
/* Updated thanks to comments, this is what I've had in my code, I didn't reproduce it correctly */

/* Note: Counting starts at 1 for rows and columns, rather than 0 */

  try {
    /* each object should be recorded to a new row of the sheet, starting at row 2,
    because row 1 is a header row */
    let row = 2;
    for(let obj of objArr) {
      /* Each property within an object should be recorded starting at
      the leftmost column and moving to the right. Reset after each object */
      let column = 1;
      for (let key of keys) {
        console.log(key);
        activeSheet.getRange(row,column).setValue(obj[key]); //activeSheet is a Google Sheet
        console.log(obj[key]);
        column++;
      }
      row++;
    }
  } catch (err) {
    console.log(`${err.message} Unable to record sender information`);
  }

I end up with the following in the script logger:

...
12:00:38 PM Info    lastMessageDate
12:00:38 PM Info    2016-02-14
12:00:38 PM Info    lastMessageSubject
12:00:38 PM Info    Test Subject 5
12:00:38 PM Info    sender
12:00:38 PM Info    Cannot read property 'sender' of undefined Unable to record sender information
12:00:39 PM Notice  Execution completed

I don't understand how for...of could possibly loop more times than there are items in the array, I'm guessing maybe something to do with the i and j iterators? If someone could point out the (probably simple) mistake I made, I'd appreciate it.

A: Try this:
function testBelow() {
  const objArr = [
    { sender: 'soandso', count: 3, lastMessageDate: '2021-09-27', lastMessageSubject: 'Test Subject' },
    { sender: 'suchandsuch', count: 7, lastMessageDate: '2021-08-27', lastMessageSubject: 'Test Subject 2' },
    { sender: 'thisperson', count: 2, lastMessageDate: '2021-03-02', lastMessageSubject: 'Test Subject 3' },
    { sender: 'thatperson', count: 3, lastMessageDate: '2019-09-27', lastMessageSubject: 'Test Subject 4' },
    { sender: 'anotherone', count: 4, lastMessageDate: '2016-02-14', lastMessageSubject: 'Test Subject 5' },
  ];

  let oA = objArr.map( o => [o.sender,o.count,o.lastMessageDate, o.lastMessageSubject] );
  SpreadsheetApp.getActiveSheet().getRange(1,1,oA.length,oA[0].length).setValues(oA);

}

Active Sheet:

soandso
3
2021-09-27
Test Subject

suchandsuch
7
2021-08-27
Test Subject 2

thisperson
2
2021-03-02
Test Subject 3

thatperson
3
2019-09-27
Test Subject 4

anotherone
4
2016-02-14
Test Subject 5

A: It's always my own fault, I swear.
Earlier in the function, I was trying to assign the length of objArr + 1 to a variable, but accidentally incremented the length value itself (which I didn't even know was possible)
Wrong: let rows = objArr.length++
vs
Right let rows = objArr.length + 1


text:
Q: Protractor: how to search in a table if the column index is unknown? My goal is to determine if there is one row that contains a text in the column corresponding to a determined header.
Here is the view:

  <headers>
    Age
    Gender
    Size
  <headers>

    <row>
      <col>20</col>
      <col hidden="isSmallScreen()">F</col>
      <col>180</col>
    </row>
    <row>
      <col>21</col>
      <col hidden="isSmallScreen()">M</col>
      <col>185</col>
    </row>

It is important to know that the app is responsive, meaning that if the screen is small, the second column is not in the DOM.
The test code tries to know if there is someone with size=180, and it must work whatever ther screen size.
I'm using Typescript.
const headers = element.all(by.tagName('header'));
let headerIndex: number;
headers.filter((header: ElementFinder, columnIndex: number) => {
        return header.getText().then(innerText: => {
            if (innerText === 'Size') {
                headerIndex = columnIndex;
            }
            return innerText === 'Size';
        });
    },
);
const rows = searchRowsByTextInColumn(headerIndex, 180);
expect(rows.count()).toBe(1);

The method searchRowsByTextInColumn(headerIndex, searchText) is implemented, no issue at that level.
The problem is the headerIndex that is still undefined when calling searchRowsByTextInColumn(). It's normal because it lies into async code.
Now how can I do to make the search work ?

A: When searchRowsByTextInColumn(headerIndex, 180); be executed, the headerIndex have not been complete assign value, because element.all().filter() run async.
function findHeaderIndex(header) {
    return element.all(by.css('table > headers > header'))
         .getText().then(function(headers){
             return headers.indexOf(header);
    });
}

function searchRowsByTextInColumn(header, cellText) {
    return findHeaderIndex(header).then(function(index) {
        var xpath = util.format('//table/body/row[ col[%s][text()="%s"] ]',
                                index, cellText);
        return element.all(by.xpath(xpath));
    });
}

searchRowsByTextInColumn('size', 180).then(function(rows){
    expect(rows.count()).toBe(1);
    // if above expect not work, try below

    rows.count().then(function(rowCount){
        console.log('rowCount: ' + rowCount);
        expect(rowCount)).toBe(1);
    });
});