text:
Q: When do you need to `END { close STDOUT}` in Perl? In the tchrists broilerplate i found this explicit closing of STDOUT in the END block.
END { close STDOUT }

I know END and close, but i'm missing why it is needed.
When start searching about it, found in the perlfaq8 the following:

For example, you can use this to make
  sure your filter program managed to
  finish its output without filling up
  the disk:

END {
    close(STDOUT) || die "stdout close failed: $!";
}

and don't understand it anyway. :(
Can someone explain (maybe with some code-examples):

*

*why and when it is needed

*how and in what cases can my perl filter fill up the disk  and so on.

*when things getting wrong without it...

*etc??

A: I believe Mat is mistaken.
Both Perl and the system have buffers. close causes Perl's buffers to be flushed to the system. It does not necessarily cause the system's buffers to be written to disk as Mat claimed. That's what fsync does.
Now, this would happen anyway on exit, but calling close gives you a chance to handle any error it encountered flushing the buffers.
The other thing close does is report earlier errors in attempts by the system to flush its buffers to disk.

A: A lot of systems implement "optimistic" file operations. By this I mean that a call to for instance print which should add some data to a file can return successfully before the data is actually written to the file, or even before enough space is reserved on disk for the write to succeed.
In these cases, if you disk is nearly full, all your prints can appear successful, but when it is time to close the file, and flush it out to disk, the system realizes that there is no room left. You then get an error when closing the file.
This error means that all the output you thought you saved might actually not have been saved at all (or partially saved). If that was important, your program needs to report an error (or try to correct the situation, or ...).
All this can happen on the STDOUT filehandle if it is connected to a file, e.g. if your script is run as:
perl script.pl > output.txt

If the data you're outputting is important, and you need to know if all of it was indeed written correctly, then you can use the statement you quoted to detect a problem. For example, in your second snippet, the script explicitly calls die if close reports an error; tchrist's boilerplate runs under use autodie, which automatically invokes die if close fails.
(This will not guarantee that the data is stored persistently on disk though, other factors come into play there as well, but it's a good error indication. i.e. if that close fails, you know you have a problem.)


text:
Q: Ios how to access google analytics reporting from ios I have an app that is using google analytics to track usage of the app and it works great using GANTracker api. I can see results and analysis when logging on the google analytics web site.
I nowneed to access to these stats with my apps to see what are the top topics or top subject users are interested in, so i would need to be able to do read and request to google analytics.
I've seen that there is a reporting api in java but i have not seen any ios calls or api to read stats from google analytics?
Has anyone done that and can share how you did it ?
Thanks for your help

A: Google has made an Objective C library available which you can use to access JSON APIs, including the Analytics API. You can find the library at http://code.google.com/p/google-api-objectivec-client/.

redpajama_set_name: RedPajamaStackExchange


text:
Q: visual studio c++ external dependencies In my visual studio project I had a file (say called f.h) which I did not require any more and may have incorrectly removed (by just pressing delete in the solution explorer of visual studio.
Now what I observe is that file is showing up in the "external dependencies" list and causing a compile error.
The compile error is caused as follows (f.h has a #include "x.h" which i do not need and hence removed).
So the question is how to figure out how "f.h" got there in the "external dependencies" and if I can remove it the compile error will go away.

A: My educated guess is that you still have a file that includes the "f.h" file
Do a ctrl+shift+f and search for #include "f.h" and see if that exists anywhere in your solution.
Even when a header file is not included in the solution project it will still get compiled into the source if it is referenced somewhere.


text:
Q: Отправка писем с телеграм бота ( Telegraph.js можно и через чистую Node.js( без фреймворков ) ) у меня появилась задача, хочу узнать возможно ли отправить письма пользователям через телеграм бот, к примеру есть массив юзеров и их почта
(сейчас бот написан с помощью telegraph.js)
но если есть способ решения на чистой ноде, смогу переработать
users = ['Eduard', 'Oleg', 'Genry'];
usersEmails= ['123@gmail.com', '1234@gmail.com', '12345@gmail.com']

юзеры пишут свои имена и почту, бот их пушит в массивы,  в целом задача либо отправить после этого письмо на почту, либо написать в личку человеку, возможно есть подсказки по данной теме, буду благодарен. Предполагаю, что перед тем, как рассылать будет сформирован объект с пользователями
users = {

usersInfo:
[
        { name: "Eduard", email: "123@gmail.com"},
        { name: "Oleg", email: "1234@gmail.com"},
        { name: "Genry", email: "12345@gmail.com"}
    ]
}

после чего перебором уже делать отправку, проверять на Имя и узнавать кому отправляем, чтобы указать в письме/смс
возможно как решение пушить в MongoDB, и что то делать дальше с ними, вот тут нуждаюсь в подсказке так же


text:
Q: Access DataContext behind IQueryable Is it possible to access the DataContext object behind an IQueryable?
If so, how?

A: DataContext is specific to LINQ to SQL, so presumably you're talking about LINQ to SQL queries? If so, there's no safe way to do this - you have to resort to a hack such as using reflection to retrieve the private "context" field of the underlying DataQuery object:
static DataContext GetContext (IQueryable q)
{
  if (!q.GetType().FullName.StartsWith ("System.Data.Linq.DataQuery`1")) return null;
  var field = q.GetType().GetField ("context", BindingFlags.NonPublic | BindingFlags.Instance);
  if (field == null) return null;
  return field.GetValue (q) as DataContext;
}


text:
Q: Get running Apps(Internal and External) with icons Currently, I'm working on to get a list of all running applications. I've been able to do this in the following way,
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
ActivityManager.MemoryInfo mInfo = new ActivityManager.MemoryInfo();
activityManager.getMemoryInfo(mInfo);
List<RunningAppProcessInfo> listOfRunningProcess = activityManager
                .getRunningAppProcesses();
Log.d(TAG, "XXSize: " + listOfRunningProcess.size());
l1 = findViewById(R.id.Layout1);
for (RunningAppProcessInfo runningAppProcessInfo : listOfRunningProcess) {
    if (runningAppProcessInfo.uid > 1026) {
        uID = runningAppProcessInfo.uid;
        Log.d(TAG, "ANS " + runningAppProcessInfo.processName + " Id :"
            + runningAppProcessInfo.pid + " UID: " + uID);
    }
}

It gives a list of all running applications. Now I want to differentiate these applications on the basis of whether they are Internal or External apps. Is there any way to separate out internal and external apps.

A: Here is the thread which checks the whether the app is system app or not.
so that if you get the list of apps then you can check the apps whether the apps are system apps or not using the above thread. so that you can separate the apps.


text:
Q: Vertical Scrolling Text In a ListItem? I have implemented a custom ListItem for my ListView. The ListItem looks like this:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rlOfferRoot"
    android:layout_width="fill_parent"
    android:layout_height="60dp"
    android:padding="5dp"
    android:background="@color/white">

      <RelativeLayout
        android:id="@+id/rlOfferDetails"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:background="#000000">

        <LinearLayout
          android:id="@+id/llOfferRoot"
          android:layout_width="fill_parent"
          android:layout_height="200dp"
          android:orientation="vertical"
          android:background="@color/orange">
            <ImageView
              android:id="@+id/imgOfferImage"
              android:layout_width="fill_parent"
              android:layout_height="match_parent"/>
        </LinearLayout>
        <LinearLayout
          android:id="@+id/menuDrawerLayer"
          android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:gravity="bottom"
          android:layout_gravity="bottom">

        <SlidingDrawer
          android:id="@+id/sdOfferDetails"
          android:layout_width="fill_parent"
          android:layout_height="200dp"
          android:layout_alignBottom="@id/imgOfferImage"
          android:content="@+id/drawerButtons"
          android:handle="@+id/slideHandleButton"
          android:topOffset="-50dp">

            <Button
               android:id="@+id/slideHandleButton"
               android:layout_width="wrap_content"
               android:layout_height="wrap_content"
               android:background="@drawable/arrowup"/>

            <RelativeLayout
              android:id="@+id/drawerButtons"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:background="#80000000">
              <ScrollView
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:scrollbars="vertical"
                android:padding="10dp"
                android:focusable="true">
                <TextView
                  android:id="@+id/txtOfferDetails"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent"
                  android:textColor="@color/white"
                  android:text="This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end
                           This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text This is some text end"/>
              </ScrollView>
        </RelativeLayout>
      </SlidingDrawer>
    </LinearLayout>

  </RelativeLayout>
  </RelativeLayout>

This looks great and performs as expected except when I open my SlidingDrawer and try to scroll through the text contained in the TextView.
The TextView looks to get focus as I see the scrollbar for the TextView appear for a moment, but then the ListView seems to grab the focus and the whole list starts to scroll.
Am I going to need to implement a custom ListView to sort this or is their a quick fix? I attempted the same as above but used a HorizontalScrollScrollView which did work, but this is probably because the ListView does nothing with the Horizontal scroll events.
Any help appreciated

A: Set on touch listner on your ScrollView
   OnTouchListener childScroll = new View.OnTouchListener() {

           @Override
           public boolean onTouch(View v, MotionEvent event) {
                 v.getParent().requestDisallowInterceptTouchEvent( true);
                  return false ;
          }
   };


text:
Q: Which one is greater (A or B)? Q. If $$A=(99)^{50} + (100)^{50}$$ and $$ B=(101)^{50}$$   then-
$(a) A>B$
$(b) A<B$
$(c) A=B$
My attempt - I thought of using the binomial approximation to A and B , which gives - $$ A= (100)^{50} + (100)^{50} (\frac{50}{100}) $$ and $$ B= (100)^{50} (1+\frac{50}{100})$$ Therefore, $$ A = (100)^{50} (\frac{3}{2})$$ and $$B = (100)^{50} (\frac{3}{2})$$ Which results in equality between them , but it is not the correct answer!Though it is a simple question but
Where am I doing wrong? Is it the approximation ? If it is , then why? And how to solve it ?
Any help would be appreciated

A: You need the next level in the approximation.  We have $1.01^{50} \gt 1+{50 \choose 1}1^{49}\cdot 0.01+{50 \choose 2}1^{48}\cdot 0.01^2=1+0.5+25\cdot 49 \cdot 0.01^2= 1.6225$
$0.99^{50}\lt 1-{50 \choose 1}1^{49}\cdot 0.01+{50 \choose 2}1^{48}\cdot 0.01^2=1-0.5+25\cdot 49 \cdot 0.01^2= 0.6225$
Then $\frac A{100^{50}} \lt  1.6225 \lt \frac B{100^{50}}$

A: Write
\begin{align}
101^{50} & = (100 + 1)^{50} = 100^{50} + \binom{50}{1} \times 100^{49} + \cdots + \binom{50}{49}\times 100 + 1 \\
99^{50} & = (100 - 1)^{50} = 100^{50} - \binom{50}{1} \times 100^{49} + \cdots - \binom{50}{49}\times 100 + 1 \\
\end{align}
Therefore,
$$101^{50} - 99^{50} = 2 \times \binom{50}{1} \times 100^{49} + \cdots + 2 \times \binom{50}{49}\times 100 > 2 \times \binom{50}{1} \times 100^{49} = 100^{50}.$$
This gives you $B > A$.

A: $99=100-1$
$101=100+1$
Use the Binomial Theorem:
$$\displaystyle 99^{50}=(100-1)^{50}=\sum_{n=0}^{50}(-1)^{50-n}\dbinom{50}{n}100^n $$
$$\displaystyle 101^{50}=(100+1)^{50}=\sum_{n=0}^{50}\dbinom{50}{n}100^n $$


text:
Q: Tidyr: pivot_wider error: Can't convert  to  I have a dataframe which lists species observations across multiple survey plots (the data is here).  I'm trying to use tidyr's pivot_wider to spread that abundance data across several columns, with the new columns being each of the observed species.  Here's the line of code I'm trying to use to do that:
data %>% pivot_wider(names_from = Species, values_from = Total.Abundance, values_fill = 0)

However, this gives me two error messages:
Error: Can't convert <double> to <list>.
Values are not uniquely identified; output will contain list-cols.

I'm not sure what the issue is, because this has worked fine for several other dataframes that are (seemingly) identical to this one.  I've tried googling the first error message and have not been able to find what conditions cause it—I don't know what double R is trying to convert to a list, nor why it's trying to convert to a list. The Total.Abundance column should be integers, but I wonder if somehow it's a double data type?
From what I've been able to find, the second error message appears when there are identical rows in the dataframe.  However, the error persists when I modify my statement to
unique(data) %>% pivot_wider(names_from = Species, values_from = Total.Abundance, values_fill = 0)

Which I would have thought would remove duplicate rows.
Any help would be much appreciated!

A: Expanding on my comment, there are duplicates in your data that cannot be removed by unique() or in dplyr, distinct():
dat %>%
  distinct() %>%
  group_by(Plot.ID, Species) %>%
  count()
#   Plot.ID Species                  n
#     <dbl> <chr>                <int>
# 1       1 Calliopius               1
# 2       1 Idotea                   2
# 3       1 Lacuna vincta            2
# 4       1 Mitrella lunata          2
# 5       1 Podoceropsis nitida      1
# 6       1 Unk. Amphipod            1
# 7       1 Unk. Bivalve             1
# 8       2 Calliopius               1
# 9       2 Caprella penantis        1
#10       2 Corophium insidiosum     1

Need to find out why you have duplicates like this and reconcile it, say by summing them up. The problem might be coming out of data wrangling coding bugs in which case summing is not necessarily suitable. Or perhaps say you sample same plot twice, you want mean instead of sum to normalize vs sampling effort, or perhaps you need extra column indicating sampling effort). Nevertheless, this works perfectly:
dat %>%
  group_by(Plot.ID, Species) %>%
  summarise(abundance = sum(Total.Abundance)) %>%
  tidyr::pivot_wider(names_from = Species, values_from = abundance,
                     values_fill = 0)


text:
Q: Notifications bar lags when onGoing notification is on My application has a notification in the notifications bar that shows the battery level. The notification works but when the checkbox in the preferences is clicked and the notification appears, i try to pull down the notifications bar and it lags. I don't know way but i think that it's because the notification check every second the battery level but i'm not sure.. I post the code:
@SuppressLint("NewApi")
    private void checkPref(Intent intent){
            this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            boolean pref_opt1 = myPref.getBoolean("firstDependent", false);
            int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1);
            if (pref_opt1){
                NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                 Notification notification = new Notification.Builder(getApplicationContext())
                 .setContentTitle("Battery Informations")
                 .setContentText("Battery level"+" "+level+"%")
                 .setSmallIcon(R.drawable.icon_small_not)
                 //.setLargeIcon(aBitmap)
                 .setTicker(level+"%")
                 .build();

                 notification.flags = Notification.FLAG_ONGOING_EVENT;
                 Intent i = new Intent(MainActivity.this, MainActivity.class);
                 PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0);
                 notifi.notify(215,notification);
                } else {
                NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
                notifi.cancel(215);
                }
        }

Maybe the problem is this one this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));. But i know only this way to update the notification when the battery level changes.. Some helps please?

A: Check whether 'if-case' code to show notification is getting executed repeatedly. If so try limiting show notification to once via a flag value and reset the flag during notifi.cancel().


text:
Q: Extension method on Item in List within another List I'm trying to perform an run an extension method on every item within a List<> that is inside another List<> to return collection of a given type (returned by the extension method).
I initially tried (and failed) to do this using linq, but I have the following:
        var dataset = GetReportDataset(org);

        var reportData = new List<InterventionAndNeetRiskReportLineModel>();

        foreach (var record in dataset)
        {
            foreach (var inter in record.InterventionHistory)
            {
                 reportData.Add(inter.ToInterventionAndNeetRiskReportLineModel());
            }
        }
        return _reportWriter.ReportCsvStream(reportData);

So my question is, how can I project the result of my extension method for each item in the child collection using linq?
UPDATE ToInterventionAndNeetRiskReportLineModel() extension method
    public static InterventionAndNeetRiskReportLineModel ToInterventionAndNeetRiskReportLineModel(this InterventionHistory intervention)
    {
        return new InterventionAndNeetRiskReportLineModel()
        {
            Beneficiary = intervention.Person.Beneficiary,
            CourseTitle = intervention.CourseTitle,
            CaseNotes = intervention.CaseNotes,
            EndDate = intervention.EndDate?.ToString(),
            StartDate = intervention.StartDate.ToString(),
            ParticipantId = intervention.Person.ParticipantId,
            FirstEit = intervention.Person.EitScores.GetFirstEitReading().ToString(),
            LastEit = intervention.Person.EitScores.GetLastEitReading().ToString(),
            FirstLpt = intervention.Person.LptScores.GetFirstLptReading().ToString(),
            LastLpt = intervention.Person.LptScores.GetLastLptReading().ToString(),
            Gender = intervention.Person.Equalitites.Gender,
            HoursAttended = intervention.NoOfHours.ToString(),
            LanguageOfDelivery = intervention.DeliveryLanguage,
            Providername = intervention.ProviderName,
            QanCode = intervention.QanCode,
            SchoolCollegeName = intervention.ProviderName
        };
    }

A: I'm not completely sure which part of the question code you want to separate into an extension method. Also, don't be to focused on the extension method part, its nothing different from other functions, as far as the writing is concerned.
You can use SelectMany in order to get a flat list of InterventionHistory objects and Select in order to convert to InterventionAndNeetRiskReportLineModel and ToList for the final result as list instead of IEnumerable<T> if you really need that.
var reportData = GetReportDataset(org)
    .SelectMany(r => r.InterventionHistory)
    .Select(i => i.ToInterventionAndNeetRiskReportLineModel())
    .ToList();

So, maybe you want an extension method like
public static IEnumerable<InterventionAndNeetRiskReportLineModel> ToInterventionRiskReports(this IEnumerable<ReportDataset> _self)
     return _self
        .SelectMany(r => r.InterventionHistory)
        .Select(i => i.ToInterventionAndNeetRiskReportLineModel());
}

And use it as
var reportData = GetReportDataset(org).ToInterventionRiskReports().ToList();

... as I said, its not completely clear, which part you want to refactor into an extension method.


text:
Q: Playing few audios one after another with JavaScript I have 3 audio files pre-loaded in javascript.
My goal is when a button is pressed, play the first audio.
2 seconds after the previous audio ended, play the next one.
I want to do all this with javascript only (except for calling the function).
Right now, I've only managed to play only the first one or three all at the same time. So I need help on this one.
HTML part:
<button onClick="rotatePrime(0);">Prime Slide Show</button>

JavaScript:
var audioFile = new Array("a1.mp3","a2.mp3","a3.mp3");
var audio = new Array;

    for (i=0; i<audioFile.length; i++) {
      audio[i]= new Audio("Audio/"+audioFile[i]);
      audio[i].load();
    }

    function rotatePrime() {
            audio[0].play();
            audio[0].onended=setTimeout(function(){audio[1].play();}, 2000);
            audio[1].onended=setTimeout(function(){audio[2].play();}, 2000);
    }

A: Have you tried
audio[0].onended=function(){
 setTimeout(function(){
  audio[1].play()
 ;}, 2000);
};

onended syntax:
object.onended=function(){myScript};


text:
Q: Dynamically creating nested navigation menu item using Bootstrap and Angularjs What I want to achieve is dynamically creating a menu in bootstrap based on a json using angularjs.
The json looks like this:
 {
    "Page A":"page_A.html",
    "Page B":{
        "Page B1":"page_B/page_B1.html",
        "Page B2":"page_B/page_B2.html",
        "Page B3":{
            "Page B3-a":"page_B/page_B3/page_a.html",
            "Page B3-b":"page_B/page_B3/page_b.html"
        }
    },
    "Page C":"page_C.html"
}

where The object key is the name of the page and object value is the physical file location.
The angular app.js look like this
app.controller('navCtrl', function($scope, $http) {
    $http.get('data/menu.json').success(function(data) {
        $scope.menus   = data;
    });
});

where menus is stores the json
The HTML bootstarp look like this (Work in progress, doesn't work)

                      {{key}}

My Question:

*

*How can I create nested navbar item based on the json?

*Is there any other Angularjs directive that can do better in terms of recursion and nested beside ng-repeat?

*Should I change my json convention to make it easier? If so, How?

I am new to both Angularjs and Bootstrap. Please be gentle.

A: Object.keys(data) just show like this :
["Page A", "Page B", "Page C"]
loop again :)


text:
Q: why does this code lock my files? Ive narrowed down to this method but i don't understand why its locking the file. I believe you could use something like
using( something)
{

//do stuff here
}

But im not sure that would A) solve the issue or B) be the correct way if it did.
any ideas?
[DllImport("user32.dll", CharSet = CharSet.Auto)]private static extern Int32 SystemParametersInfo(UInt32 action, UInt32 uParam, String vParam, UInt32 winIni);
    private static readonly UInt32 SPI_SETDESKWALLPAPER  = 0x14;
    private static readonly UInt32 SPIF_UPDATEINIFILE    = 0x01;
    private static readonly UInt32 SPIF_SENDWININICHANGE = 0x02;

    private void SetWallpaper(string path)
    {
        try
        {
            Image imgInFile = Image.FromFile(path);
            imgInFile.Save(SaveFile, ImageFormat.Bmp);
            SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
        }
        catch
        {
            MessageBox.Show("error in setting the wallpaper");
        }
    }

#

Updated code
 private void SetWallpaper(string path)
    {
        if (File.Exists(path))
        {
            Image imgInFile = Image.FromFile(path);
            try
            {
                imgInFile.Save(SaveFile, ImageFormat.Bmp);
                SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
            }
            catch
            {
                MessageBox.Show("error in setting the wallpaper");
            }
            finally
            {
                imgInFile.Dispose();
            }
        }
    }

A: From MSDN: "The file remains locked until the Image is disposed." - so yes, this should be fixed by:
using (Image imgInFile ...) { ... }

(As a side note, I would tighten the try catch to just the .Save() and/or SystemParametersInfo() calls)

A: Once you pass out of the using block, all objects initialized within it are disposed.  In your case, the objects will be disposed which will remove the lock on the file.
You must manually dispose (either through a using statement or by calling .Dispose() on the object) any unmanaged calls to either COM or Windows API functions (i.e. when you use interop).

A: Here is what i have please let me know if you see anything that i could pretty up. But its working like a champ so i'm pretty happy.
                private void SetWallpaper(string path)
                {
                    if (File.Exists(path))
                    {
                        Image imgInFile = Image.FromFile(path);
                        try
                        {
                            imgInFile.Save(SaveFile, ImageFormat.Bmp);
                            SystemParametersInfo(SPI_SETDESKWALLPAPER, 3, SaveFile, SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE);
                        }
                        catch
                        {
                            MessageBox.Show("error in setting the wallpaper");
                        }
                        finally
                        {
                            imgInFile.Dispose();
                        }
                    }

                    Else
                    {
                          messagebox.show("Error with path: "+path+" Not found or in use");
                    }
                }


text:
Q: Finite projective planes How big a set of points in general position (i.e., no three collinear) can be found in a finite projective plane of order $n$?
I hope the answers won't be too technical, as I know almost nothing about projective planes besides the definition.
Motivation: I want to use this for an example in graph theory.
My work: If $S$ is a set of points in general position, then $|S|\le n+2$, since $S$ has at most a point $p$ and another point on each of the $n+1$ lines through $p$. So $n+2$ is an upper bound. For a lower bound, let $S$ be any maximal set of points in general position and note that $\binom{|S|-1}2\ge n$, whence $|S|\ge\frac{3+\sqrt{1+8n}}2$.

A: An arc is a set of points, no three collinear. An arc is complete if it is maximal with respect to set inclusion. So you are asking for the maximum size of a complete arc.
According to this paper, this appears to be a hard problem in general, although if $n$ is even, then your upper bound is attained, and if $n$ is odd, then it can be improved to $n+1$.
I was hoping to track down a proof for the $n$ even case (due to Segre) but it appears to be a bit too obscure. Hopefully you have better luck. Actually it's not clear to me if he "only" proved it for $n=2^k$.

A: The size of an arc is always less than $n+2$, as you noted.  However $n+2$ can only occur if $n$ is even. To see this, take a collection of $n+2$ points no three collinear; it can then have no tangent lines. So every line either meets $0$ or $2$ points of the arc.  Take a point not in the arc, and consider all of the secants to the arc through that point.  There needs to be $(n+2)/2$ secants so $n$ must be even!
When the plane is $PG(2,q)$, q a prime power, than we always have $q+1$-arcs (ovals) defined by a conic. These are the only $q+1$-arcs when $q$ is odd.  When $q$ is even, these can be extended to $q+2$-arcs (hyperovals). More interestingly, we have $q+2$-arcs that are not conics, and these are not classified.  The hard problem referred to by Casteels is actually to find small arcs that are complete, that is they cannot be extended.  Usually if arcs are large enough they can always be extended.
There are also interesting problems related to arcs in non-Desarguesian projective planes.  Can we always find ovals? Some planes (Hall planes) can inherit them from the Desarguesian planes, but this problem is open in general (indeed we do not even know all of the planes).


text:
Q: Rails password can't be blank error I am trying to create a user signup form in Rails 4.1.6.  I keep getting a 'password can't be blank' error.  I can see that both the password and password_confirmation are in the params hash but not in the params[:user] sub-hash.  I cannot figure out why for the life of me.  Any help will be greatly appreciated.
User Model:
class User < ActiveRecord::Base

    belongs_to :company

    has_secure_password

end

Users Controller:
class UsersController < ApplicationController

    respond_to :json

    def index
        @users = User.all
        respond_with(@users)
    end

    def create
        @user = User.new(user_params)
        @user.save
        respond_with(@user)
    end

    private

        def user_params
            params.require(:user).permit(:given_name, :family_name, :email, :password, :password_confirmation)
        end

end

A: It sounds like your parameters are not being sent to the server correctly.
password should be sent as user[password] and password_confirmation should be sent as user[password_confirmation].
See documentation for hash and array parameters.
Alternatively, adding wrap_parameters to the controller will wrap parameters into a nested hash.
wrap_parameters :user, include: [:given_name, :family_name, :email, :password, :password_confirmation]
See documentation for ActionController::ParamsWrapper.


text:
Q: Magento2: How to configure CodeSniffer in phpstorm? I want to configure code sniffer in phpstorm so i can refactor my code according to Magento coding standards

A: Code Sniffer Configurations:

Open PHPStorm, Alt + Ctrl + S Select PHP > Quality Tools >
PHP_Codesniffer > ... > Give the path of
"Suizlabs/PHP_Codesniffer/bin/phpcs" Then validate it and apply/Ok
Select Editor > Inspections > PHP > Quality Tools > Check the
PHP_CodeSniffer validation Then in OPTIONS on the right side check all
the options Give path of
"vendor/magento/magento-coding-standard/Magento2" to Installed
standards path
After that select "magento2" from the coding standard dropdown and
apply/Ok.

Steps to properly configure spacing or lint feature in PHPStorm:

ctrl + alt + s Editor --> Code Style --> PHP --> Set from -->
PSR1/PSR2 Apply and OK Press CTRL + ALT + L or CTRL + ALT + SHIFT + L


text:
Q: JavaFx program Runs but nothing is blank, Why? So I was super excited thinking I finally figured this program out and then BAM launching it = blank screen. Am I calling a blank Pane here, and the other info isnt populating? Is it populating but off screen? For some Reason JavaFX is really getting to me. If anyone also has any good places to go and read up on it. (I know google works, A lot of the sites/places I find just aren't doing it for me.
package application;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Node;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ComboBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class Main extends Application {

Button button1, button2;
Label label1, label2;
Scene scene1, scene2;
BorderPane border1, border2;
Stage stage;

ComboBox<String> choseImage;
ImageView mga1 = new ImageView(new
Image(getClass().getResourceAsStream("/res/mga1.jpg")));
ImageView mga2 = new ImageView(new
Image(getClass().getResourceAsStream("/res/mga2.jpg")));
ImageView mga3 = new ImageView(new
Image(getClass().getResourceAsStream("/res/mga3.jpg")));

@Override
public void start(Stage primaryStage) throws Exception {

    primaryStage.setTitle("multi-factor key");
    primaryStage.setScene(scene1);

    //passPhrase
    TextField passPhrase = new TextField();
    button1 = new Button("submit");
    button1.setOnAction(e -> handleButtonAction(e));
    label1 =new Label ("Type in your PassPhrase");

    border1=new BorderPane();
    border1.getChildren().addAll(passPhrase, button1, label1);
    border1.setPadding(new Insets(20));
    BorderPane.setAlignment(passPhrase, Pos.CENTER);
    BorderPane.setAlignment(button1, Pos.BOTTOM_CENTER);
    BorderPane.setAlignment(label1, Pos.TOP_CENTER);
    scene1 = new Scene(border1, 350, 500);

    //combobox
    choseImage = new ComboBox<>();
    choseImage.setPromptText("Select a image.");
    choseImage.getItems().addAll("mga1.png"
    + "mga2.jpg"
        +   "mga3.png");

    choseImage.setValue("mga1.png");
    label2=new Label("Select a image");
    System.out.println(choseImage.getValue());
    String Selection = choseImage.getValue();
    if (Selection == "mga1.png")
            BorderPane.setAlignment(mga1, Pos.CENTER_RIGHT);
    if (Selection == "mga2.jpg")
            BorderPane.setAlignment(mga2, Pos.CENTER_RIGHT);
    if (Selection == "mga3.jpg");
            BorderPane.setAlignment(mga3, Pos.CENTER_RIGHT);

    border2= new BorderPane();
    border2.setPadding(new Insets(20));
    border2.getChildren().addAll(choseImage,label2);
    BorderPane.setAlignment(choseImage, Pos.CENTER);
    BorderPane.setAlignment(label2, Pos.TOP_CENTER);

    scene2 = new Scene(border2, 350, 500);
    primaryStage.show();

}

private void handleButtonAction(ActionEvent event) {
    if (event.getTarget()==button1)
        stage.setScene(scene1);
}

}

A: There are many problems why the screen is blank when you start the app

*

*When you call primaryStage.setScene(scene1); the scene is null, so it is expected to be blank, you should set the scene after you instantiate it. In your case after the line :  scene1 = new Scene(border1, 350, 500);

*Even if you do the previous step the screen still remain blank because you call border1.getChildren().addAll(...) which is wrong. A BorderPane has 5 regions top bottom left right and center, so you should set a Node to this regions instead of adding them to the borderPane's children. It depends where you want to "see" them you should put in the right place. You should do something like:    border1.setTop(...) border1.setBottom(...) and so on.


text:
Q: Basic doubts related to rendering of texture region in libgdx? I have just recently started using libgdx.I have some doubts regarding rendering of texture region.Here is my code
@Override
public void create() {
    float w = Gdx.graphics.getWidth();
    float h = Gdx.graphics.getHeight();

    camera = new OrthographicCamera(1, h/w);
    batch = new SpriteBatch();

    texture = new Texture(Gdx.files.internal("data/libgdx.png"));
    texture.setFilter(TextureFilter.Linear, TextureFilter.Linear);

    TextureRegion region = new TextureRegion(texture, 0, 0, 512, 275);

    sprite = new Sprite(region);
    sprite.setSize(1f, 1f * sprite.getHeight() / sprite.getWidth());
    sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);
    sprite.setPosition(-sprite.getWidth()/2, -sprite.getHeight()/2);
    sprite.setRotation(30);
}

In this case sprite renders perfectly.
But if i change line
sprite.setOrigin(sprite.getWidth()/2, sprite.getHeight()/2);

to
sprite.setOrigin(any constant values like 50, sprite.getHeight()/2);

i only get blue screen.
same thing happens when i set position this way.
Also if i use something like
sprite.setOrigin(0.53*sprite.getWidth()/2, sprite.getHeight()/2);

it renders as expected, why does it renders as expected when i use any multiple of sprite.getWidth() and not when i use constant of same value.
EDIT:
Here are my resize and render methods
@Override
public void render() {
    Gdx.gl.glClearColor(0, 0, 1, 1);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    batch.setProjectionMatrix(camera.combined);
    batch.begin();
    sprite.draw(batch);
    batch.end();
}

@Override
public void resize(int width, int height) {
}

I have not changed anything here.

A: This might depend on your rendering camera setting. It cuold be caused by setting the origin out of bounds. In other words, try setting it to (for example) much lower or much higher values.


text:
Q: How to get the big picture of the legacy SQL database? I am expected to make (small) changes to the legacy SQL application on Microsoft SQL Server 2008. It uses several databases, many stored procedures, functions, and some CLR assemblies.
There is no big-picture documentation, only some common knowledge in the heads of the people around.
What tools do you use when you search for say all places where the stored procedure is called? I am not the experienced SQL developer. My experience fits better with programming languages where source code is stored in text files rather than in the databases.
What tools would you recommend to learn the content of the legacy SQL application?
Thanks, Petr

A: For the specific question:

all places where the stored procedure is called?

You can use brute force, though this will lead to some false positives where the procedure name is simple and may appear in code naturally (even as part of another object name), or in comments:
SELECT OBJECT_SCHEMA_NAME([object_id]), OBJECT_NAME([object_id])
  FROM sys.sql_modules
  WHERE definition LIKE '%your_procedure_name%';

This also doesn't capture calls to the procedure that are built with dynamic SQL, but I don't think there is a perfect all-encompassing solution for this problem anyway. You can also discover cases where the stored procedure is being called by a job:
SELECT j.name FROM msdb.dbo.sysjobs AS j
  INNER JOIN msdb.dbo.sysjobsteps AS s
  ON j.job_id = s.job_id
  WHERE s.command LIKE '%your_procedure_name%';

(Same caveats exist for false positives and dynamic SQL there, as well as nested procedure calls which won't be caught even if they are relevant.)
Some other ideas:

*

*Red-Gate has a free tool called SQL Search or, probably more appropriately, SQL Dependency Tracker.

*There is a free version of SQL Digger but the pro version is required for stored procedures.

*You can try the dependency viewer in Management Studio, but I don't really trust the underlying data.


text:
Q: javascript object in constructor is filled with values much earlier than the filling functions are executed I create the object eqC from function ColsProt.
In constructor of this function i instantiate this.colsO = {}; as empty.
If i log the value - it is empty.
If i try to run function, which fills the this.colsO with values (actually it is deep nesting 5 functions) in my logs this.colsO gets filled with values before these functions are executed. It logs values already in constructor, before any function execution, but only if this function in code will be executed in feature ( if it is not executed in future, this.colsO log is empty).
The order of logs is normal, but in logs i find this.colsO values, although normally this.colsO object shall be empty till step 7.
1 constructor this.colsO=  undefined
2 constructor this.colsO= { object full of style variables, though should be empty }
2 end of constructor this.idArr= //empty
3 ColsProt.prototype.init this.colsO= { object full of style variables, though should be empty }
3  ColsProt.prototype.init   this.idArr = //empty
4 ColsProt.prototype.getVars this.colsO = { object full of style variables, though should be empty }
4f ColsProt.prototype.getVars fullOname = { object full of style variables, though should be empty }
4 ColsProt.prototype.getVars   this.idArr= //empty

// repeates several tims
5 ColsProt.prototype.findColumns   this.idArr=loccontPck,introPck,servicesPck
5 ColsProt.prototype.findEls this.colsO = { object full of style variables, though should be empty }
5f ColsProt.prototype.findEls fullOname= //undefined
6 ColsProt.prototype.getProps ans= { object with style parameters }
6 ColsProt.prototype.getProps this.colsO= { object full of style variables, though should be empty, the ans is already part of the object, although it is not yet assigned to be }
7 ColsProt.prototype.findEls this.colsO = { object full of style variables, the ones which should be assigned, and the ones which will be assigned in future }

Actually, I need an empty this.colsO in some deeper places, but it is full of variables and I can not delete them, because deletion seems occur earlier than this.colsO gets filled with variables. Additionally to that nothing is deleted, if i try to delete the object, in it occurs a new item, named "rem".
var ColsProt = function( gO ) {
        //this.win = $(window); //the window object
        //UNC  //console.log(' From ColsProt constructor '); // ['ecols']

        this.colCss = null;
        if( (gO['colCss']!==undefined) && (gO['colCss']!==null) ) { this.colCss = gO['colCss']; }

        this.mode = 'dev'; // 'prod'|'dev'; //the main difference is on resize events. In once case the different stylesheet is included. In another case - the stylesheet is generated and window is reset
        if( (gO['mode']!==undefined) && (gO['mode']!==null) ) { this.mode = gO['mode']; }

        this.oNameArr = []; ////oName of [ 'imgO', 'divO', 'oelO']
        this.oSelArr = [];
        var mi;
        //the names of Object which contains images, divs, other elements
        //[ { cssSel : ['img'], oName : 'imgO' },
        //{  oName : 'oelO', cssSel : [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div //h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ] }    // '#'+colid +' h1',
        //{ cssSel : ['div:not(:has(img))'], oName : 'divO' } ];
        var onm, me, sels;
        if ( ( gO['oMap']!==undefined ) && ( gO['oMap']!==null) ) {
            this.oNameArr = Object.keys( gO['oMap'] );
            for ( onm of this.oNameArr ) {
                me = gO['oMap'][onm];
                sels = JSON.parse( JSON.stringify ( me['cssSelArr'] ) );
                this.oSelArr.push( sels );
            } // for ( mi of gO['oMap'] ) {
            this.oMap = JSON.parse( JSON.stringify ( gO['oMap'] ) );
        }  // if ( ( gO['oMap']!==undefined ) && ( gO['oMap']!==null) ) {
        else {
            this.oNameArr = [ 'imgO', 'divO', 'oelO' ];
            this.oSelArr = [ ['img'], ['div:not(:has(img))'], [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ] ];
            this.oMap = {
                //'imgO' : { cssSelArr:['img'], rules:{ adj:150, mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0} },
                'imgO' : { cssSelArr:['img'], rules:{} }, //adj is top and bottom padding
                //'divO' : { cssSelArr:['div:not(:has(img))'], rules:{  mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0 },
                'divO' : { cssSelArr:['div:not(:has(img))'], rules:{adj:20} },
                //'oelO' : { cssSelArr : [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ], rules:{ adj:150, mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0} }
                'oelO' : { cssSelArr : [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ], rules:{ adj:12 } }
            };
        }

        /*this.oNameSelMap = {};
        for ( mi of this.oMap ) {
            var oName = this.oMap['oName'];
            var cssSelArr = this.oMap['cssSel'];
            this.oNameSelMap['oName'] = cssSelArr;
        } */

        //class of images, which are very reduced in size, but enlarge in case of column resizing
        this.imgClass = null;
        if( (gO['imgClass']!==undefined) && (gO['imgClass']!==null) ) { this.imgClass = gO['imgClass']; }

        //ids of topdiv elements, mostly images, where you should not apply any styling, nto to make spaces
        this.topDivsIds=null;
        if( (gO['topDivsIds']!==undefined) && (gO['topDivsIds']!==null) ) { this.topDivsIds = gO['topDivsIds']; }

        this.stSettStr='';
        if( (gO['stSettStr']!==undefined) && (gO['stSettStr']!==null) ) { this.stSettStr = gO['stSettStr']; }  ////console.log('this.stSettStr='); //console.log(this.stSettStr);

        this.cusIdMap = null; this.cusIdArr=[];
        if( (gO['cusIdMap']!==undefined) && (gO['cusIdMap']!==null) ) {
            this.cusIdMap = gO['cusIdMap'];
            this.custIdArr = Object.keys(this.cusIdMap);
        }

        this.styleDataFname = 'coffStyleSett170926.json';
        if( (gO['styleDataFname']!==undefined) && (gO['styleDataFname']!==null) ) { this.styleDataFname = gO['styleDataFname'] +'.json'; }

        this.tallestColId = ""; //id of tallest column
        this.shorterCalIdArr = [];

        this.colsOdif = {};  //this.colsOdif[id] = diff;

        this.stSettStr = '';
        if ( ( this.stSettStr!==undefined ) && ( this.stSettStr!==null ) && ( this.stSettStr.length > 0 ) ) { this.colsSettO = JSON.parse( this.stSettStr ); }

        //this.colsSettO = { ecols:{}, objectName:'colsSettO' }; //contains settings data

        //this.colsO = { ecols:{}, objectName:'colsO' }; //is filled with current data in function init() -- //contains id : { hBefore, hAfter, bhighest, imgFallArr
        console.log('1 constructor this.colsO='); console.log(this.colsO); //empty
        this.colsO = {};
        console.log('2 constructor this.colsO='); console.log(this.colsO); // filled with variables
        //this.colsO['ecols'] = {};//contains this.colsO['ecols'][id] [ parameters for equal columns, like diff, L ]..
        var on;
        for ( on of this.oNameArr ) { this.colsO[on] = {}; }

        //console.log(' before the init, in constructor this.idArr=' + this.idArr.toString() ); undefined
        this.idArr = []; //ids of columns
        console.log('2 end of constructor this.idArr=' + this.idArr.toString() );

        //this.oiDivAdj = 20; //maximum size to increase the div ( currently is applied to margin// REFACTOR to be able to apply to border or to padding
        //this.oiAdj = 12; //maximum size to increase the element. Make different size for p, ul li, a etc....
        //this.imgAdj = 200; //amoun to strech, add borders, etc to images

        //UNC  //console.log( 'this.colsSettO=' ); //console.log(this.colsSettO);
        //UNC  //console.log( 'this.colsO=' ); //console.log(this.colsO);

} // var ColsProt = function( gO ) {

    ColsProt.prototype.init = function() {
        console.log( ' 3 ColsProt.prototype.init this.colsO=' ); console.log( this.colsO );
        console.log( ' 3  ColsProt.prototype.init   this.idArr=' + this.idArr.toString() );
        this.getVars( this.colsO );
    }

    ColsProt.prototype.getVars = function (fullOname) {
        console.log( ' 4 ColsProt.prototype.getVars this.colsO=' ); console.log( this.colsO );
        console.log( ' 4f ColsProt.prototype.getVars fullOname=' ); console.log( fullOname );
        console.log( ' 4 ColsProt.prototype.getVars   this.idArr=' + this.idArr.toString() );
        //this.findColumns();
        //this.findColumns2(this.colCss);
        this.findColumns(this.colCss);

        var colid, oName, css, cssStr;
        for( colid of this.idArr ) {
            for ( oName of this.oNameArr ) {
                if ( ( this.colsO[oName]===undefined ) || ( this.colsO[oName]===null ) ) {  this.colsO[oName] = {};  }
                if ( ( this.colsO[oName]['cssSelArr']===undefined ) || ( this.colsO[oName]['cssSelArr']===null ) ) {
                    var cssSelArr = this.oMap[oName]['cssSelArr'];
                    ////console.log( '154 From   ColsProt.prototype.getVars, before this.findEls.   cssSelArr = ' ); //console.log( cssSelArr );
                    this.findEls( { colid:colid, cssSelArr:cssSelArr, oName:oName, fullOname:fullOname } );
                } // if ( ( this.colsO[oName]['cssSelArr']===undefined )

            } // for ( oName of [ 'imgO', 'divO', 'oelO'] ) {
        } // for( let colid of this.idArr ) {
    }

    ColsProt.prototype.findColumns = function() {
        var css;
        for( css of this.colCss ) {
            var that = this;
            $(css).each( function () {
                var id = $(this).attr('id');
                that.idArr.push(id);
            }); // $(css).each( function () {
        } // for( css of this.colCss ) {
        console.log( ' 5 ColsProt.prototype.findColumns   this.idArr=' + this.idArr.toString() );
    } //ColsProt.prototype.findColumns = function() {

////get data for oName and colid.
//(i) this can be used for downlaoding to StyleSettingsFile ( fullOname = ,
//(ii) or For adjusting style settings
//cold - id of the column div.pck
//Gell all images
//var css =  [ '#'+colid +' img'];
//var css = ['#'+colid +' div:not(:has(img))'];
//var css = this.oiEls  //for ( sel of this.oiEls ) {
//oName = imgO | divO | oiO
//fullOname - object, which will containt the selected information
ColsProt.prototype.findEls = function( gO ) {

    console.log( ' 5 ColsProt.prototype.findEls this.colsO=' ); console.log( this.colsO ); //filled, but hsould be empty
    console.log( ' 5f ColsProt.prototype.findEls fullOname=' ); console.log( fullOname ); //filled, but hsould be empty

    var colid, css, oName, fullOname; var berr = false;

    if( (gO!==undefined) && (gO!==null) ) {

        if ( ( gO['colid']!==undefined) && (gO['colid']!==null) ) {
            colid = gO['colid']; } else { berr = true; }
        if ( ( gO['cssSelArr']!==undefined) && (gO['cssSelArr']!==null) ) {
            css = gO['cssSelArr']; } else { berr = true; }
        if ( ( gO['oName']!==undefined) && (gO['oName']!==null) ) {
            oName = gO['oName']; } else { berr = true; }
        if ( ( gO['fullOname']!==undefined) && (gO['fullOname']!==null) ) {
            fullOname = gO['fullOname']; } else { berr = true; }

    } // if( (gO!==undefined) && (gO!==null) ) {
    else {
        berr = true;
        //UNC //console.log(' ERROR, ERROR ');
    }

    if(!berr) {

        //UNC //console.log( '349 From   ColsProt.prototype.findEls    colid='+colid+',    css='+css+',  oName='+oName );

        // find elements for given oName and columnid //oName is the name of css rule, like 'img', 'ul', etc...
        var citem;
        var tmpO = {}; var tmpOcss = {};

        //remove the same elements
        var uOcss = {}; var uO = {};
        var int, inu;

        //push to this.fullOname[oName][colid]
        var iu, citem;
        var selO = {}; var selOcss = {};
        var cnt = 0;

        for ( citem of css ) {

            var that = this;

            $( '#' + colid).find(citem).each( function() {

                cnt++;
                if( $(this).length > 0 ) {

                    if( $(this).length == 1 ) {
                        tmpO[cnt] = $(this);
                        tmpOcss[cnt] = citem;
                    } // if( $(this) == 1 ) {

                    //separate between different items, and items having the same selector like ul li
                    else if ( $(this).length > 1 ) {

                        var elemcopy = $(this);
                        $(this).each ( function() {
                            var that = $(this);
                            $(elemcopy ).each ( function() {
                                var buniq = true;
                                ////console.log( '140 that=' ) ; //console.log( that );
                                ////console.log( '140 this=' ) ; //console.log( $(this) );
                                //UNC //console.log( '349 citem='+citem+'  !that.is( $(this) ) =' ); //console.log( !that.is( $(this) ) );
                                if( !that.is( $(this) ) ) {
                                    tmpO[cnt] = $(this);
                                    tmpOcss[cnt] = citem;
                                    buniq = false;
                                } // if( !that.is( $(this) ) )  {
                                if(buniq) {
                                    tmpO[cnt] = $(this);
                                    tmpOcss[cnt] = citem;
                                } // if(buniq) {

                            } ); // $(elem).each ( function() {
                        } ); // $(elem).each ( function(elem) {

                    } // else if ( elem.length > 1 ) {
                } // if( $(this) > 0 ) {
            } ); // $( css ).each( function() {
        } // for (citem of css ) {

        ////console.log('tmpArr');  //console.log(tmpArr);
        //UNC //console.log('tmpO');  //console.log(tmpO);
        ////console.log('tmpOcss');  //console.log(tmpOcss); //

        //remove the same elements
        for ( int of Object.keys(tmpO) ) {
            var elt = tmpO[int];
            var cc = tmpOcss[int];  //css condition
            var L = Object.keys(uO).length;
            if( L > 0 ) {
                var bnew = true;
                //for ( let elu of uArr ) {
                for ( let inu of Object.keys(uO) ) {
                    var elu = uO[inu];
                    if ( elt.is(elu) ) { bnew = false; }
                    // removes the same parent chldrens // if ( $(e1).parent().children().is($(e2)); )
                    //because you need to apply margin only once to div div a, not as many times as there are <a> elements
                    if ( elt.parent().children().is(elu) ) { bnew = false; }

                } // for ( let elu of uArr ) {
                if ( bnew ) {
                    //uArr.push(elt);
                    uOcss[int] = cc; uO[int] = elt;
                }
            } // if ( uArr.length > 0 ) {
            else {
                //uArr.push(elt)
                uOcss[int] = cc; uO[int] = elt;
            }
        } // for ( let elt of tmpArr ) {
        //UNC //console.log('uO');  //console.log(uO);
        //UNC //console.log('uOcss');  //console.log(uOcss);

        ////console.log('uArr'); //console.log(uArr);
        ////console.log('uOcss'); //console.log(uOcss); //console.log('uO'); //console.log(uO);
        //gett properties and push to fullArr

        if( (fullOname[oName]===undefined) || (fullOname[oName]===null) ) {
            fullOname[oName] = {};
        }

        if( (fullOname[oName][colid]===undefined) || (fullOname[oName][colid]===null) ) {
            fullOname[oName][colid] = {};
        }

        if( (fullOname['map']===undefined) || (fullOname['map']===null) ) {
            fullOname['map'] = {};
        }

        if( (fullOname['map'][oName]===undefined) || (fullOname['map'][oName]===null) ) {
            fullOname['map'][oName] = {};
        }

        if( (fullOname['map'][oName][colid]===undefined) || (fullOname['map'][oName][colid]===null) ) {
            fullOname['map'][oName][colid] = {};
        }

        var idMap = {};
        var cssMap = {};
        var classMap = {};
        var id, css, cls;

        for ( iu of Object.keys( uO ) ) {

            var el = uO[iu]; //elements
            var css = uOcss[iu];
            ////console.log('289 css=' + css );
            var propO = this.getProps( {el:el,css:css} );

            //UNC //console.log('propO='); //console.log(propO);
            //fullOname[oName][colid].push( propO );
            if(iu=="rem") { console.log("ERROR iu = rem propO="); console.log(propO); }
            fullOname[oName][colid][iu] = propO;

            if( (propO['id']!==undefined) && (propO['id']!==null) ) {
                id = propO['id'];
                if( (fullOname['map'][oName][colid]['id']==undefined) || (fullOname['map'][oName][colid]['id']==null) ) { fullOname['map'][oName][colid]['id'] = {}; }
                if( (fullOname['map'][oName][colid]['id'][id]==undefined) || (fullOname['map'][oName][colid]['id'][id]==null) ) { fullOname['map'][oName][colid]['id'][id] = []; }
                fullOname['map'][oName][colid]['id'][id].push(iu);
            }

            if( (propO['css']!==undefined) && (propO['css']!==null) ) {
                css = propO['css'];
                if( (fullOname['map'][oName][colid]['css']==undefined) || (fullOname['map'][oName][colid]['css']==null) ) { fullOname['map'][oName][colid]['css'] = {}; }
                if( (fullOname['map'][oName][colid]['css'][css]==undefined) || (fullOname['map'][oName][colid]['css'][css]==null) ) { fullOname['map'][oName][colid]['css'][css] = []; }
                fullOname['map'][oName][colid]['css'][css].push(iu);
            }

            if( (propO['cls']!==undefined) && (propO['cls']!==null) ) {
                cls = propO['cls'];
                if( ( fullOname['map'][oName][colid]['setCl']==undefined) || (fullOname['map'][oName][colid]['setCl']==null) ) { fullOname['map'][oName][colid]['setCl'] = {}; }
                if( ( fullOname['map'][oName][colid]['setCl'][cls]==undefined ) || ( fullOname['map'][oName][colid]['setCl'][cls]==null ) ) { fullOname['map'][oName][colid]['setCl'][cls] = []; }
                fullOname['map'][oName][colid]['setCl'][cls].push(iu);
            } // if( (propO['cls']!==undefined) && (propO['cls']!==null) ) {

        } // for ( int of Object.keys(tmpO) ) {

        if( (fullOname['ecols']===undefined) || (fullOname['ecols']===null) ) { fullOname['ecols']={}; }
        if( (fullOname['ecols'][oName]===undefined) || (fullOname['ecols'][oName]===null) ) { fullOname['ecols'][oName]={}; }
        if( (fullOname['ecols'][oName][colid]===undefined) || (fullOname['ecols'][oName][colid]===null) ) { fullOname['ecols'][oName][colid]={}; }
        fullOname['ecols'][oName][colid]['elArrL'] = Object.keys( uO ).length;

    }// if berr

    //console.log('ColsProt.prototype.findEls = fullOname=');  console.log(fullOname);
    console.log( ' 7 ColsProt.prototype.findEls this.colsO=' ); console.log( this.colsO ); //here should be filled
    console.log( ' 7f ColsProt.prototype.findEls this.colsO=' ); console.log( this.colsO ); //here should be filled

}; // ColsProt.prototype.findEls = function(colid, css, oName ) {

ColsProt.prototype.getProps = function( gO ) {

    var el, css; var berr = false;

    if ( (gO!==undefined) && (gO!==null) ) {

        if ( ( gO['el']!==undefined) && (gO['el']!==null) ) {
            el = gO['el']; } else { berr = true; }
        if ( ( gO['css']!==undefined) && (gO['css']!==null) ) {
            css = gO['css']; } else { berr = true; }

    } // if( (gO!==undefined) && (gO!==null) ) {
    else { berr = true;
        console.log(' ERROR , ERROR ');
    }

    if(!berr) {

        var mT = parseInt ( el.css('margin-top') );
        var mR = parseInt ( el.css('margin-right') );

        var mB = parseInt ( el.css('margin-bottom') );
        var mL = parseInt ( el.css('margin-left') );
        var bT = parseInt ( el.css('border-top') );
        var bR = parseInt ( el.css('border-right') );
        var bB = parseInt ( el.css('border-bottom') );
        var bL = parseInt ( el.css('border-left') );

        var pT = parseInt ( el.css('padding-top') );
        var pR = parseInt ( el.css('padding-right') );
        var pB = parseInt ( el.css('padding-bottom') );
        var pL = parseInt ( el.css('padding-left') );

        var id = el.attr( 'id' );
        var cls = el.attr( 'class' );
        var width = el.width();
        var height = el.height();
        var boxSizing = el.attr( 'box-sizing' );

        var css = css;

        var ans = { mT:mT, mR:mR, mB:mB, mL:mL, bT:bT, bR:bR, bB:bB, bL:bL, pT:pT, pL:pL, pB:pB, pR:pR, id:id, cls:cls, width:width, height:height, boxSizing:boxSizing, css:css };

        console.log( ' 6 ColsProt.prototype.getProps ans=' ); console.log( ans );
        console.log( ' 6 ColsProt.prototype.getProps this.colsO=' ); console.log( this.colsO ); //filled, but hsould be empty

        return  ans;

    }

}; // ColsProt.prototype.getProps = function( el) {

//THe part of main script, which initialize the object
    var oMap = {
                //'imgO' : { cssSelArr:['img'], rules:{ adj:150, mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0} },
        imgO : { cssSelArr:['img'], rules:{} }, //adj is top and bottom padding
                //'divO' : { cssSelArr:['div:not(:has(img))'], rules:{  mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0 },
        divO : { cssSelArr:['div:not(:has(img))'], rules:{adj:20} },
                //'oelO' : { cssSelArr : [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ], rules:{ adj:150, mT:0,mR:0,mB:0,mL:0,bT:0,bR:0,bB:0,bL:0,pT:0,pL:0,pB:0,pR:0} }
        oelO : { cssSelArr : [ 'h1', 'h2', 'h3', 'h4', 'h5', 'h6',  ' p', ' a',  ' ul',  ' ul li', ' div h1',  ' div h2', ' div h3', ' div h4', ' div h5', ' div h6', ' div p', ' div a', ' div div a',  ' div ul', ' div ul li' ], rules:{ adj:12 } }
    };

   var cusIdMap = {};

    var topDivsIds = [ 'loccontPck', 'locontPckItem', 'introPck', 'imgPckiEyePckItem', 'servicesPck',  'carePgPckItem' ]; //do not apply to values for these items

    var botDivsIds = [];

    //var stSettStr = from C:\Bitnami\wampstack-7.0.22-1\apache2\htdocs\type70823\src\HotColImgBundle\Resources\actions\person\certifOfficer2\settings\StyleData_certifO.json
    //var stSettStr = "";
    var stSettStr =$( "#stSettStr" ).text();
    //console.log('stSettStr='); console.log(stSettStr);

 var eqC = new ColsProt( { colCss:['.pck' ], cusIdMap:cusIdMap, oMap:oMap, topDivsIds:topDivsIds, botDivsIds:botDivsIds, stSettStr:null, styleDataFname:'coffStyleSett170926', mode:'dev' } );

eqC.init();


text:
Q: For what $a,b$ is this integral finite: $\int_0^1 \frac{(1-x)^a}{x^b} dx$ The case where $b<1$ is trivial (converge). And for $b \ge 1$, if $a\le 0$, the integral must diverge. I'm not sure what to do with $b \ge 1, a>0$.

A: If $b \geq 1$ and $a > 0$, note that
$$
\int_0^{1/2} \frac{(1-x)^a}{x^b}\ dx \geq \int_0^{1/2} \frac{2^{-a}}{x^b}\ dx
$$
hence the integral diverges.

A: Near $0$ the integrand is equivalent to
$$x^b$$ since
$$(1-x)^a\text{ goes to  } 1.$$
it converges if $-b<1$.
Near $1$, the integrand is equivalent to $$(1-x)^a$$
since $x^b$ goes to $1$.
it converges if $-a<1$.
The inyegral is convergent if $a>-1$ and $b>-1$.

A: Your conclusion is too quick. Write the integral as
$$
\int_0^{1/2}\frac{(1-x)^a}{x^b}\,dx+
\int_{1/2}^1\frac{(1-x)^a}{x^b}\,dx=
\underbrace{\int_0^{1/2}\frac{(1-x)^a}{x^b}\,dx}_I+
\underbrace{\int_0^{1/2}\frac{(1-x)^{-b}}{x^{-a}}\,dx}_J
$$
Note that in both $I$ and $J$ you can disregard the numerators as far as convergence is considered.
The integral
$$
\int_0^{1/2}\frac{1}{x^b}\,dx
$$
converges for $b<1$ and diverges for $b\ge1$.
Thus you have convergence for $b<1$ and $-a<1$, that is, $a>-1$; divergence for $b\ge1$ or $a\le-1$.


text:
Q: c# Windows service with Timer not executing code I Have following code, which does not executed when windows service starts
I found solutions here but they didn't work for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.ServiceProcess;
using System.Configuration;
using System.Threading.Tasks;

namespace TFS_JIRA_sync
{
    public partial class SyncProcess : ServiceBase
    {

        public SyncProcess()
        {
            InitializeComponent();
        }

        private System.Timers.Timer timer = new System.Timers.Timer();

        protected override void OnStart(string[] args)
        {

            this.timer.Interval = ScanPeriod.period * 60000; //turn minutes to miliseconds
            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);//OnTimer;
            this.timer.Enabled = true;
            this.timer.AutoReset = true;
            this.timer.Start();
        }

        private void OnTimer(object sender, System.Timers.ElapsedEventArgs e)
        {
            Processing proc = new Processing();
            proc.doProcess();
        }

        protected override void OnStop()
        {
        }
    }
}

In Programm:
using System;
using System.Collections.Generic;
using System.ServiceProcess;
using System.Threading.Tasks;

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

namespace TFS_JIRA_sync
{
    static class Program
    {
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        static void Main()
        {
            ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {
                new SyncProcess()
            };
            ServiceBase.Run(ServicesToRun);

            //Processing proc = new Processing();
            //proc.doProcess();

        }
    }
}

When I comment part starting "ServiceBase[]..." and uncomment "Processing ..." in Programm class it works fine.
But when my code run as Windows service - Nothing happens

A: Put Console.ReadLine() in your code:
  static void Main()
    {
        ServiceBase[] ServicesToRun;
        ServicesToRun = new ServiceBase[]
        {
            new SyncProcess()
        };
        ServiceBase.Run(ServicesToRun);
        Console.ReadLine();
    }

A: As I see your service is not going to run all the time
this.timer.Interval = ScanPeriod.period * 60000;. For your scenario
rather than having a windows service with a timer (and spending time on resolving the issue), I'd recommended to use a scheduled task (as suggested by this answer).
It references a Jon Gallow's article, that gives a lot of reasons why it is better to use a scheduled task.

If you're writing a Windows Service that runs a timer, you should re-evaluate your solution.


text:
Q: dart: how to get correct (typed) reference to document object in iframe I have a use case where a complex UI hierarchy needs to be rendered in an iframe, but the logic handling it (creation, enter document, event handling, exit document) need to be in the main frame / app.
I face issues with getting a typed reference to the Document instance of the iframe. Is this possible at all? The code errors even with type casts.
Any advise would be helpful, except the one to use js interop - something as simple as extracting a UI branch and fitting it inside an iframe should not require this IMHO.
Also if this is not possible where should I go filling a bug?

A: Cross window access is very limited due to security concerns. There are open issues to allow it again because it can be circumvented by dart-js-interop anyway.
So the suggested solution is to use dart:js as workaround until the issues are fixed.
  var ifrm = new js.JsObject.fromBrowserObject(dom.querySelector('#ifrm'));
  print(ifrm['contentWindow']);
  print(ifrm['contentDocument']);

A: Try to use window.postMessage() to transfer DOM updates between the frames. That might be a possiblity I guess?


text:
Q: aurelia application startup errors in both ie and chrome I'm trying to copy the code of the contact app from the aurelia repo in a asp.net 5 application using typescript 1.5 beta.
I copied all the files, the tsconfig configuration seems ok, but when I run the application, after the initial screen, I obtain errors in oth ie11 and chrome 42.
In Ie 11 I receive the error message:

JavaScript runtime error: Cannot define property 'Symbol(id)_i.jtkqmdozsa6': object is not extensible

calling configureAurelia  in the handleApp function
In Chrome I obtain

Uncaught TypeError: Cannot read property '__decorate' of undefined

in the same place.
How can I find the problem?

A: I believe you need to set the TS 1.5 compiler's --emitDecoratorMetadata flag to true.


text:
Q: Save / Analyze output after applying a filter I'm trying to analyze the amplitude data of an audio file, but I can't seem to find a way to get this data after applying a filter.  Is it possible to get the floatChannelData or write the output to a new file for analysis?
    player = AKPlayer(audioFile: file)
    player.buffering = .always
    player.preroll()
    let filter = AKBandPassButterworthFilter(player, centerFrequency: 1000, bandwidth: 100)
    AudioKit.output = filter

    do {
        try AudioKit.start()
    } catch {
        print("Failed to start AudioKit")
        return nil
    }

    // This is the peak as though no filter was applied
    print(player.buffer?.peak())

A: Yes, you can choose to render the output to file. You can also tap the filter node to get its data for use in plots, or to save the contents to a buffer and save the data external to AudioKit's rendering.


text:
Q: FTP - Filename not allowed I'm trying to upload a file to an FTP server using code based on this Microsoft Article
My code looks like this for testing purposes:
string ftpUrl = "ftp://" + ftpSite + ftpPath + "test.txt";
//string ftpUrl = ftpSite;

FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl);
request.Credentials = new NetworkCredential(ftpUsername, ftpPassword);
request.Method = WebRequestMethods.Ftp.UploadFile;

StreamReader srcStream = new StreamReader(filePath);
byte[] fileContents = Encoding.UTF8.GetBytes(srcStream.ReadToEnd());
request.ContentLength = fileContents.Length;

Stream requestStream = request.GetRequestStream();
requestStream.Write(fileContents, 0, fileContents.Length);
requestStream.Close();

FtpWebResponse response = (FtpWebResponse)request.GetResponse();

Every time I try to upload the file, I get a "Filename not allowed" error back from the FTP server. If I use an FTP client application like WS_FTP, I'm able to FTP the same file just fine.
Any thoughts on how to correct this? I've already tried setting active/passive FTP mode, keepalive, and binary modes without any luck.
EDIT
This is a winforms application - the filename comes in from an OpenFileDialog prompt and the FTP address is based on settings in App.Config.

A: Without seeing your full code, I will say there is a very good chance the constructed FTP URL / path is incorrect, in comparison to what you expect it to be when you manually connect to the FTP site through a FTP client.
If you post your app.config code and how you assign values to ftpSite and ftpPath, it would be helpful in answering this question.

A: You can get that particular error for many cases.
Most common issue is that the path you are accessing is not valid by the permissions allowed, and using a relative path or changing thew path might get it fixed.


text:
Q: Premature end of file when I try to Extract SAMLResponse by Jmeter xpath extractor? The value I need to extract is something in the following format :
<input type='hidden' name='SAMLResponse' value='PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiPz4K.... ">

I used the following xpath extractor.

//input[@type='hidden'][@name='SAMLResponse']/@value

But I get the following exception.
Please let me know why I get something like this?
[Fatal Error] :-1:-1: Premature end of file.
.
.
.
.

    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:315)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1110)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)
Caused by: org.xml.sax.SAXParseException; Premature end of file.
    at org.apache.xerces.parsers.DOMParser.parse(Unknown Source)
    at org.apache.xerces.jaxp.DocumentBuilderImpl.parse(Unknown Source)
    at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:121)
    at ...

A: "Premature end of file" indicates that XML document is not well formed and doesn't have closing tag.
You need to check "Use Tidy" under your XPath extractor post processor. By the way, starting from JMeter 2.11 it's possible to evaluate XPath right in View Results Tree Listener
However as per Using the XPath Extractor in JMeter guide XPath Extractor

Builds DOM tree to parse HTML code, it consumes CPU and memory

So you may wish to consider using Regular Expression Extractor instead. If text to parse isn't complex, isn't multiline, etc. RegExp is the best option to do the correlation.

A: "Premature end of file" indicates it is not well formed.
Hence Use Tidy option under  XPath extractor post processor.

A: I found the answer.
You have to tick Use Tidy (tolerant parser) and Quiet when you define the Xpath Query. Then the problem will be solved.


text:
Q: Why is my Mongoose query not updating a value in a nested array in the MongoDB databse? I have tried to implement this in several ways and none seem to work.
All I need to do is change the Status value of a specific Notifications object (found by its _id) from 0 to 1.
Example JSON:
{
    "_id": "577fbf0c7c6e88600ede5e73",
    "updatedAt": "2016-07-14T11:27:18.670Z",
    "createdAt": "2016-07-08T14:56:12.013Z",
    "Name": "Name",
    "Email": "test@test.com",
    "Notifications": [
      {
        "_id": "5787644108edec801e9cd0ab",
        "Title": "They commented on This",
        "Type": 1,
        "Status": 0,
        "TeamID": "578357109bb105602b1cba27",
        "DraftID": "578357b89bb105602b1cba2a"
      },
      {
        "_id": "578777167d1f3424251c361f",
        "Title": "He commented on That",
        "Type": 1,
        "Status": 0,
        "TeamID": "578357109bb105602b1cba27",
        "DraftID": "578357b89bb105602b1cba2a"
      }
    ]
    .....
  }

My route:
router.post('/notification', function (req, res) {
    UserProfile.update({
        'Notifications._id' : req.body.NotificationID
    }, {
        '$set' : {
            'Notifications.$.Status' : 1
        }
    }, function (err) {
        if (err)
            res.send(err);
    })
});

I don't get any errors and the update doesn't seem to happen.
What could the problem be?

A: Is the type of Notifications._id ObjectId? If so, try cast req.body.NotificationId to ObjectId. Change the query to
{'Notifications._id' : mongoose.Types.ObjectId(req.body.NotificationID)}

A: Try '$set' instead of $set.
Ensure that you are getting id coming in correctly.
Update callback comes with updated document - print that to know what happens.

A: The $ is referring only the first item in the array. If you want to update all you have to use find and save:
UserProfile.findOne({
        'Notifications._id' : req.body.NotificationID
    }, function(err, doc) {
         _.find(doc.Notifications, {_id: req.body.NotificationID}).Status = 1;

         doc.save(function (err) {
        if (err)
            res.send(err);
    })
})


text:
Q: python 3 IRC bot syntax error Okay, first off. I'm very new to python, and I've just started to teach myself python 3
 As a fun project to help me learn I decieded to do an IRC Bot, I figured I'll follow a basic tutorial on creating a basic bot, and as I learn I could add more to it, and make it my own but the problem is I believe
the tutorial was written for python 2.x. I've gotten a few errors that I was able to fix on my own, but now I'm getting this syntax error that I cant seem to figure out.
the error is on line 39, here are lines 38 and 39, (38 because I had a syntax error there but managed to fix it)
if msgpart[0]=='`' and sender[0]==OWNER  # Treat all messages start with ` as a command
   cmd=msgpart[1:].split('')

and the error I get is.
File "pybot.py", line 39
cmd=msgpart[1:].split('')
  ^
Syntax error: invalid syntax

the error on line 38 was kind of the same thing, but with that I removed the : after owner and it fixed
itself, which seemed weird to me because from what I understand theres supposed to be : after IF statements.

A: You are missing : after if statement. Should be:
if msgpart[0]=='`' and sender[0]==OWNER:
   cmd=msgpart[1:].split('')

A: You are missing a colon : at the end of the if statement:
if msgpart[0]=='`' and sender[0]==OWNER  # Treat all messages start with ` as a command
                                       ^

should be:
if msgpart[0]=='`' and sender[0]==OWNER:  # Treat all messages start with ` as a command
                                       ^

A: Check that your tabs and spaces are consistent in the source file. There seem to be 3 spaces in front of line 39 (normally it's 4, or at least some even number).
Plus the colon : at line 38 like others said.
The empty string in split('') is no syntax error, but it also looks weird. What are you trying to achieve there?


text:
Q: Definition of Prism Operator and homotopy of chain complexes I am reading Algebraic Topology by Allen Hatcher.
For reference:
https://pi.math.cornell.edu/~hatcher/AT/AT.pdf
On page 112, in the first sentence of the last paragraph, we find the following:

The terms with $i=j$ in the two sums cancel out, except for $F\circ (\sigma \times \mathbf{1})|[\hat{v_0},w_0,\dots, w_n]$...

It is not clear to why the pairs of terms in the series with $i=j$ should cancel out. In the picture of the decomposition of $\Delta^2\times I$ decomposed into $3$-simplices above, for instance, it is clear that the $2$ simplex $[v_0,v_1, w_2]$ is equal to both $[v_0,v_1, \hat{w}_1,w_2]$ and $[v_0,v_1,\hat{v}_2,w_2]$ but it is not clear that one is able to find any kind of nontrivial relationship between $[v_0,\hat{v}_1,w_1,v_2]$ and $[v_0,v_1,\hat{w}_1,v_2]$. This suggests that the correct cancellation is to pair up terms $i,j$ with $i=j+1$.
Is this simply a minor typo? Or am I missing something? I looked it up in the errata but didn't find anything.

A: I understand now what the wording is trying to convey; it escaped me at first. The message is that pairs $(i,j)$ in the first sum with $i=j$ match up and cancel with pairs $(i-1,j-1)$ in the second sum; that is, the pair $(i=2,j=2)$ in the first sum over $j\leq i$ matches up with the pair $(i=1,j=1)$ in the second sum over $i\leq j$. I will leave this up in case anyone else runs into similar confusion.


text:
Q: turn on 3g mobile data programatically in ios device I searched i could not find a proper answer. I want to turn on device's 3g data ON from my ios application. My scenario is initially, I will check whether internet is reachable via wifi/ 3g. If both are not available, I should turn ON device 3g data. I should be able to do it without the help of third party library. Please help me out.

A: It is not possible. you can not do it via your application. You can let the user know to go to settings page and turn on the data. But with out user's interaction, it is not possible.

A: No the closest you can get is by setting the UIRequiresPersistentWifi boolean in your info plist, which will make iOS present an alert with a button to the settings app, but it also means your app will always show this when opened if you're not connected to wifi (even if you're still on 3G)


text:
Q: Confusion regarding the p- value of a test I have a confusion regarding the p-value of a statistical test.
Suppose $\tau$ is a normally distributed rv.
We have  for a one tailed test:
p value=$P(\tau > \tau_{0})$ (for right tailed test),
p value=$P(\tau < \tau_{0})$ (for left tailed test)
$\tau_{0}$ is the observed value of the test statistic.
Now, I am having doubts how to interpret the p value of a both tailed test which is given by $2 P(\tau > |\tau_{0}|)$
Also, had the distribution been a positively skewed one with $\chi$ being positive (as in chi-squared distribution) how can we interpret the p-value for a both tailed test?

A: Here is a discussion in terms of two-sided confidence intervals, rather than two-sided tests, that illustrates inference for exponential data.
First, if the exponential mean is $\mu,$ rate $\lambda = 1/\mu,$ then
the distribution of the sample mean $\bar X$ is $\mathsf{Gamma}(n, n/\mu),$
a gamma distribution with shape parameter $n$ and rate parameter $n/\mu$.
Thus $E(\bar X) = \mu$ and $SD(\bar X) = \mu/\sqrt{n}.$ Also, $\bar X/\mu \sim
\mathsf{Gamma}(n.n).$
This can be proved by using moment generating functions, and is illustrated
for the case $\mu = 1, n = 16$ by the brief simulation in R statistical
software below. [In R, rexp samples from an exponential distribution,
dgamma is a gamma density function (second parameter, rate),
qgamma is the inverse of a gamma CDF, and a is a vector
of a million sample means.]
set.seed(318)
a = replicate(10^6, mean(rexp(16)))
mean(a);  sd(a)
[1] 0.9999153  # approx 1
[1] 0.2499526  # approx 1/4 = 1/sqrt(16)
hist(a, prob=T, col="skyblue2", main="GAMMA(16,16)")
  curve(dgamma(x,16,16), add=T, col="blue", lwd=2)
  abline(v=qgamma(c(.025,.975),16,16), col="red", lwd=3, lty="dashed")

Now, consider a particular random sample of size $n = 16$ from
$\mathsf{Exp}(rate=1/10).$
set.seed(325);  x = rexp(16, .1)
mean(x);  sd(x)
[1] 9.888107
[1] 8.290735
stripchart(x, pch="|")

Of course, because we simulated the data we know that $\mu = 10.$
But let's use the data to make a 95% confidence interval (CI) for $\mu$
and see what happens. We have
$$P\left(L < \frac{\bar X}{\mu} < U\right) = P\left(\frac 1 U < \frac{\mu}{\bar X} < \frac 1 L\right) = P\left(\frac{\bar X}{U} < \mu < \frac{\bar X}{L}\right) = 0.95,$$
where $L$ and $U$ cut 2.5% of the probability from the lower and upper tails,
respectively, of $\mathsf{Gamma}(16,16)$ [see the vertical dashed lines
in the first figure above.] Thus a 95% CI is $(\bar X/U, \bar X/L)
= (6.395, 17.299),$ which has length 10.905 and covers the true value
$\mu = 10.$ This CI is sometimes called 'probability-symmetric' because
it was formed by taking equal probabilities from the two tails of the
appropriate distribution.
CI = mean(x)/qgamma(c(.975, .025), 16, 16);  CI;  diff(CI)
[1]  6.394839 17.299409
[1] 10.90457

However, it is possible to get a shorter 95% CI by cutting different
probabilities from the two tails: $(5.916, 16.259)$ of length 10.343.
With some fussing (or a simple computer search) one could find the
interval that is, for practical purposes, shortest.
CI.2 = mean(x)/qgamma(c(.99,.04), 16, 16);  CI.2;  diff(CI.2)
[1]  5.915955 16.259290
[1] 10.34334

In a similar way, one usually has to use computational methods to find
the best test of $H_0: \mu = \mu_0$ against $H_1: \mu \ne \mu_0.$ Or to
find its true P-value for a particular set of data.
Note: If one (incorrectly) assumes data are normal and uses a 95% CI
from Student's t distribution, the result is $(5.470, 14.306).$
Such intervals (using both the sample mean and SD along with the incorrect
assumption) are often shorter than the ones made from a gamma distribution,
but they do not truly have the 'advertised' 95% coverage probability.
[A Shapiro-Wilk test of normality for these 16 observations convincingly rejects the null hypothesis with
P-value  0.0157.]


text:
Q: Add array value dynamically with a specific index? createObjectDataadd: function(component, event) {
    var index = event.getParam("indexVar");
    console.log(index);

    var RowItemList1 = component.get("v.QuotelinitemList");
     RowItemList1.push({
        'sobjectType': 'Quote_Line_Item__c',
        'Name':'',
        'Client_P_N__c': ''
         });
     RowItemList1.splice(index+1,0,RowItemList1);

    //  for (var i = index; i <RowItemList1.length; i++) {
    //  RowItemList1.splice(index+1,0,rowli);
    //    }
    component.set("v.QuotelinitemList", RowItemList1);
    //RowItemList1.splice(index-1,0,RowItemList1);
},

Quote_Line_Item__c is an object. suppose it has three records. Every record has index value. Every record has button new quote_line_item button which it is pushing a new quote line item record at end of the array.
My problem is it adding at the last index.I  want to add it on next index where the record new quote line item button is pressed.
I tried many ways but it is not coming.

A: For adding item at specified index in Array, you can use "Array.splice" like below. It takes 3 arguments: index, number of items to remove from that index, new value(s) to add. So, trick is you can pass 0 as second argument which means you do not want to delete any item

let arr = [1,2,3,4]

function addItem(item, index) {
  arr.splice(index, 0, item)
}

addItem(10, 1)
console.log(arr)


text:
Q: What is a deleted segment in linux pmap output? Here are the first few lines of output from pmap on a process, running on CentOS 5.2:
Address   Kbytes     RSS    Anon  Locked Mode   Mapping
00101000    1268       -       -       - r-x--  libc-2.5.so
0023e000       8       -       -       - r----  libc-2.5.so
00240000       4       -       -       - rw---  libc-2.5.so
00241000      12       -       -       - rw---    [ anon ]
00244000      36       -       -       - r-x--  threads.so (deleted)
0024d000       4       -       -       - rw---  threads.so (deleted)
0024e000      20       -       -       - r-x--  Socket.so (deleted)
00253000       4       -       -       - rw---  Socket.so (deleted)
[...]

What does "(deleted)" mean on the shared library mappings?

A: That means that the file in question has been deleted. Its link count in the filesystem has gone to 0. The file will stay around until the last in-kernel reference to it has been closed, then it will be removed from the disk.
You will often see this when a program has continued running while the packaging system has installed new updates. The old libraries have been removed and new libraries installed.


text:
Q: Sum amount of overlapping datetime ranges in MySQL I have a table of events, each with a StartTime and EndTime (as type DateTime) in a MySQL Table.
I'm trying to output the sum of overlapping times and the number of events that overlapped.
What is the most efficient / simple way to perform this query in MySQL?
CREATE TABLE IF NOT EXISTS `events` (
  `EventID` int(10) unsigned NOT NULL auto_increment,
  `StartTime` datetime NOT NULL,
  `EndTime` datetime default NULL,
  PRIMARY KEY  (`EventID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=37 ;

INSERT INTO `events` (`EventID`, `StartTime`, `EndTime`) VALUES
(10001, '2009-02-09 03:00:00', '2009-02-09 10:00:00'),
(10002, '2009-02-09 05:00:00', '2009-02-09 09:00:00'),
(10003, '2009-02-09 07:00:00', '2009-02-09 09:00:00');

# if the query was run using the data above,
# the table below would be the desired output

# Number of Overlapped Events | Total Amount of Time those events overlapped.
1, 03:00:00
2, 02:00:00
3, 02:00:00

The purpose of these results is to generate a bill for hours used. (if you have one event running, you might pay 10 dollars per hour. But if two events are running, you only have to pay 8 dollars per hour, but only for the period of time you had two events running.)

A: Try this:
SELECT `COUNT`, SEC_TO_TIME(SUM(Duration))
FROM (
    SELECT
        COUNT(*) AS `Count`,
        UNIX_TIMESTAMP(Times2.Time) - UNIX_TIMESTAMP(Times1.Time) AS Duration
    FROM (
        SELECT @rownum1 := @rownum1 + 1 AS rownum, `Time`
        FROM (
            SELECT DISTINCT(StartTime) AS `Time` FROM events
            UNION
            SELECT DISTINCT(EndTime) AS `Time` FROM events
        ) AS AllTimes, (SELECT @rownum1 := 0) AS Rownum
        ORDER BY `Time` DESC
    ) As Times1
    JOIN (
        SELECT @rownum2 := @rownum2 + 1 AS rownum, `Time`
        FROM (
            SELECT DISTINCT(StartTime) AS `Time` FROM events
            UNION
            SELECT DISTINCT(EndTime) AS `Time` FROM events
        ) AS AllTimes, (SELECT @rownum2 := 0) AS Rownum
        ORDER BY `Time` DESC
    ) As Times2
    ON Times1.rownum = Times2.rownum + 1
    JOIN events ON Times1.Time >= events.StartTime AND Times2.Time <= events.EndTime
    GROUP BY Times1.rownum
) Totals
GROUP BY `Count`

Result:
1, 03:00:00
2, 02:00:00
3, 02:00:00

If this doesn't do what you want, or you want some explanation, please let me know. It could be made faster by storing the repeated subquery AllTimes in a temporary table, but hopefully it runs fast enough as it is.

A: Start with a table that contains a single datetime field as its primary key, and populate that table with every time value you're interested in. A leap years has 527040 minutes (31622400 seconds), so this table might get big if your events span several years.
Now join against this table doing something like
SELECT i.dt as instant, count(*) as events
FROM instant i JOIN event e ON i.dt BETWEEN e.start AND e.end
GROUP BY i.dt
WHERE i.dt BETWEEN ? AND ?

Having an index on instant.dt may let you forgo an ORDER BY.
If events are added infrequently, this may be something you want to precalculate by running the query offline, populating a separate table.

A: I would suggest an in-memory structure that has start-time,end-time,#events... (This is simplified as time(hours), but using unix time gives up to the second accuracy)
For every event, you would insert the new event as-is if there's no overlap, otherwise, find the overlap, and split the event to (up to 3) parts that may be overlapping, With your example data, starting from the first event:
Event 1 starts at 3am and ends at 10am: Just add the event since no overlaps:
    3,10,1

Event 2 starts at 5am and ends at 9am: Overlaps,so split the original, and add the new one with extra "#events"
    3,5,1
    5,9,2
    9,10,1

Event 3 starts at 7am and ends at 9am: also overlaps, do the same with all periods:
    3,5,1
    5,7,2
    7,9,3
    9,10,1

So calculating the overlap hours per #events:
1 event= (5-3)+(10-9)=3 hours
2 events = 7-5 = 2 hours
3 events = 9-7 = 2 hours

It would make sense to run this as a background process if there are many events to compare.


text:
Q: Spring roo one to many not sorted The default one to many relationship in Spring Roo has a Set variable for maintaining relations data.
public Set<MyChildObject> Parent.getChildren() {
    return this.children;
}

when I try to use this in my JSPX file, the data is not sorted.
<c:forEach items="${parent.children}" var="item">
    <c:out value="${item.id}  " />
</c:forEach>

What would be a better and easier way to sort the data either in JSPX or Domain? please provide a working example.

A: you only have it like a method. You should have a variable:
@OneToMany(cascade = CascadeType.ALL, mappedBy = "the relationship in the other class Ithink it could be for you parent", fetch = FetchType.LAZY, orphanRemoval=true)
public Set<MyChildObject> child= new HashSet<MyChildObject>();

and the you must put this in the show.jspx:
    <field:display field="child" id="your child id" object="${the class}" z="your chid z"/>

A: use this
@OrderBy("orderingField asc")

and don't forget to
import javax.persistence.OrderBy;


text:
Q: allowsBackgroundLocationUpdates only working for a few seconds I have a bluetooth device that triggers location services in my app when a button is pressed. And location services do run, but only for about 8 seconds. I have an NSLog outputting Location Found in the didUpdateToLocation delegate method. It outputs that NSLog for only that 8 seconds.
When I put the app in the foreground, location services continue again. Here is how I initialize the location manager:
self.locationManager = [[CLLocationManager alloc] init];
self.locationManager.delegate = self;
[self.locationManager requestAlwaysAuthorization];
[self.locationManager requestWhenInUseAuthorization];
self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
[self.locationManager setAllowsBackgroundLocationUpdates:YES];
[self.locationManager allowsBackgroundLocationUpdates];

When button is pressed, I run this:
[self.locationManager startUpdatingLocation];

A: You need enabling the background mode (location), as long as your location-manager is capable to receive location-updates, your app will receive all bluetooth data.
As @Paulw11 mentioned in comments, using significant-location-updates will drastically reduce battery usage.
Here is the link to Apple guide.
Here is the link to a question related to getting location updates in background.


text:
Q: Create automatically generated timestamp column in table? How to create a automatically generated timestamp column in table in Microsoft SQL Server 2019? Timestamp column should be automatically generated when I insert or update table.
In IBM Db2 database the syntax is the following:
    create table myschema.mytable (col1 int, col2 timestamp not null generated always for each row on update as row change timestamp
    insert into myschema.mytable (col1) values (1)
    update myschema.mytable set col1 = 2

After insert/update of column col1, column col2 is automatically generated as current timestamp.

A: In Microsoft SQL Server you can try this code:
CREATE TABLE myschema.mytable
(
    col1 int,
    col2 datetime not null default(current_timestamp)
)

INSERT INTO myschema.mytable(col1) VALUES (1)

UPDATE myschema.mytable SET col1 = 2

SELECT * FROM myschema.mytable

Update:
Let's create temporary table for test
DECLARE @mytable TABLE
(
    col1 int,
    col2 datetime not null default(current_timestamp)
)

INSERT INTO @mytable(col1) VALUES (1)
SELECT * FROM @mytable

UPDATE @mytable SET col1 = 2
SELECT * FROM @mytable


text:
Q: Storing an array of ranges of timestamps into postgresql using PlaySlick and slick-pg I'm trying to store a List of Ranges of Timestamps into the "available" column of a PostgreSQL table. I'm using slick-pg to help out. For the table data I have:
create table users (
    id text NOT NULL PRIMARY KEY,
    action text NOT NULL,
    scheduled timestamptz,
    available tstzrange[]
);

In my DAO I have:
private class UsersTable(tag: Tag) extends Table[User](tag, "users") {

    def id = column[String]("id", O.PrimaryKey)
    def action = column[String]("action")
    def timestamp = column[Option[Timestamp]]("scheduled")
    def available = column[Option[List[com.github.tminglei.slickpg.Range[Timestamp]]]]("available")

    def * = (id, action, timestamp, available) <> (User.tupled, User.unapply _)
}

And an associated case class for the table:
case class User(id: String, action: String, timestamp: Option[Timestamp] = None, available:Option[List[com.github.tminglei.slickpg.Range[Timestamp]]] = None)

I know I'm missing an implicit, something similar to the implicits in this example file. However I'm still new to Scala and stuck on exactly how to define it.

A: In the class you are doing some DAO accesses, inject DatabaseConfigProvider like this:
class Class @Inject() (protected val dbConfigProvider: DatabaseConfigProvider)

and make it extends HasDatabaseConfigProvider[MyPostgresDriver].
You have to import: (database is the name of the package where is the MyPostgresDriver file)
import database.MyPostgresDriver.api._
import database.MyPostgresDriver
import play.api.db.slick.{DatabaseConfigProvider, HasDatabaseConfigProvider}

Here is the MyPostgresDriver file:
package database

import com.github.tminglei.slickpg._

trait MyPostgresDriver extends ExPostgresDriver
    with PgArraySupport
    with PgDate2Support
    with PgPlayJsonSupport
    with PgNetSupport
    with PgLTreeSupport
    with PgRangeSupport
    with PgHStoreSupport
    with PgSearchSupport
    with PgPostGISSupport {

  override val pgjson = "jsonb"
  override lazy val Implicit = new ImplicitsPlus {}
  override val simple = new SimpleQLPlus {}

  trait ImplicitsPlus extends Implicits
  with ArrayImplicits
  with DateTimeImplicits
  with RangeImplicits
  with HStoreImplicits
  with JsonImplicits
  with SearchImplicits
  with PostGISImplicits

  trait SimpleQLPlus extends SimpleQL
  with ImplicitsPlus
  with SearchAssistants
  with PostGISAssistants

  override val api = new API with ArrayImplicits
    with DateTimeImplicits
    with PlayJsonImplicits
    with NetImplicits
    with LTreeImplicits
    with RangeImplicits
    with HStoreImplicits
    with SearchImplicits
    with PostGISImplicits
    with SearchAssistants {}
}

object MyPostgresDriver extends MyPostgresDriver

(Choose only the needed implicits).