text:
Q: Problem with sending encoding polylines with json via ajax to the server Im trying to send encoded polylines of google maps to the server with ajax to save them in the database. Im sending them through JSON and decode them at the server side. The problem is when the polyline gets too long the json_decode() function won't decode the json string anymore. Im making my ajax call with post and i've tried several things already like escaping the polylines etc. but nothing will work!
Working JSON example:
{"title":"a",
 "type":"custom",
 "POIS":["46","43"],
 "polylines":[{
    "points": "oot|H_bgd@rI{HjGkFz@_Ad@w@@eAxD~ClBpAxC`Ax@pAjAbCj@zA|@h@VqAr@wAdBeB|C}Bd@KfY}A",
    "levels": "PEFEFGEFFEEFGEFEFEP"
 }]
}

Not working JSON example:
{"title":"a",
 "type":"custom",
  "POIS":["46","43"],
  "polylines":[{
     "points": "uip|Hc|nd@v@GXoC`TwJV?VPvAhElAxF^bHtHd@zDd@Hj@]jf@KpC@v@F^VOx@HK`De@~EsAdHaEzPyDpMw\zaAqCvJo@tCmDjLyDtNkKvZmD`MmDfNuDnMuA~D_BpDiEhHcF|GxAzEfHhOORvChGjBrEJHnHxOzC~EtDzCpAnBdAzBpc@|hAjJvU`IxPbGdLn@|AJFb@rApAlHF|@fAjGF|AGvGDvCv@rGhA|Fr@fCjA`DfAbCHM`AOzAn@jBzEvBrEbCxCtAnAtAp@|InCf@Dz@Kn@BlDn@`@`@fApCfAqATOh@AxAvAHjA`@E`@L`@b@hGxI|EvF~CmMHInGfF|@bBdCjGvElKrBjGz@bD`@bBjAnGnAdLXjFJpCDtLSlIiBj`@g@tOCjLBdBLnDh@tE`@d@|A|FhA~Fl@pE~CtI`FbMX`@\LZ@`@WbEuFrD_HxBhBrDnBlGfCjFnAX\B`@Gb@sArEE|@g@zDe@`H@x@F\pAdFCv@QZn@lA",
     "levels": "PFFEGEEFFEGEEEFFEFEGEEFFEEEFEEEFEFEGEEFEEEFFFEFEFEEEFEEEFEEFFEFEGEFFEFEFEFEEEFEFEEFFFEEFEFEFFEEGEEEFEEFEFEFEFEGEFEFEEGEEFEGEFEEGEEFEEFEEFEFP"
  }]
}

A: You need to escape certain characters in your points property.
A quick look through your encoded polyline shows you have the character sequence "DpMw\zaA" roughly a fifth of the way into the String.
Backslashes should be escaped with a backslash. So this should look like "DpMw\\zaA"
You should also escape double quotes in your JSON as the property points is constructed with a starting and ending double quote.


text:
Q: Multiple ngb-timepicker in one form with Angular4 I am using Angular 4 to create a form with start time and end time, using two ngb-timepicker. When I set the model to both of them, the first one instantiates the values for the second one. Any idea on how to instantiate them separately?
My HTML looks like this:
<ngb-timepicker [(ngModel)]="time1"></ngb-timepicker>
<ngb-timepicker [(ngModel)]="time2"></ngb-timepicker>

And my component:
import {Component} from '@angular/core';

@Component({
 selector: 'schedule-form',
 templateUrl: './schedule-form.component.html'
})

export class NgbdTimepickerBasic {
  time1 = {hour: startDateH, minute: startDateM};
  time2 = {hour: endDateH, minute: endDateM};
}

The result is that time1 will show time2, so only time2 is correct.

A: You need NgbTimeStruct to format the date which ngb-timepicker knows
import {Component} from '@angular/core';
import {NgbTimeStruct} from '@ng-bootstrap/ng-bootstrap';

@Component({
 selector: 'schedule-form',
 templateUrl: './schedule-form.component.html'
})

export class NgbdTimepickerBasic {
  //declaration
  time1: NgbTimeStruct;
  time2: NgbTimeStruct;

  ngOnInit() {
    //get your start and end time and assign it to below
    this.time1 = {hour: 13, minute: 30, second: 0};
    this.time2 = {hour: 16, minute: 15, second: 0};
  }

}

redpajama_set_name: RedPajamaStackExchange


text:
Q: asp.net mvc hidden field id issue I always have a problem and cannot figure out a way to solve it.
For example in the scenario of asp.net mvc, user "A" has his products:
A1(id=1),A2(id=2).

If we edit for A1, in Edit.cshtml, A1's Id = 1 is just saved in a hiddenfield. We can modify A1's Id to 2 with browser developer tool, so the modified values will be done for A2 when post back to server, although we do a server side validation. But user A has enough rights to modify all his products A1 A2. So in this case, how to prevent users from hacking? I think also to show product id in the url; then user can not modify it when updating.
I am new to MVC — maybe you have some idea or what is the general method to solve this?

A: This most not be a concern, still is a valid question, how I've fix this, well simple instead of using plain Id I'll encrypt the id, the model will look like:
public class ProductSafe
{
  public string Id {get; set;}\\encrypted
  public string Something {get; set;}
}

Using what ever you like to encrypt, when you get the object id is encrypted, when you save the model decrepit it to get real id.


text:
Q: Cocoa: custom NSCell not respond double click action I focus on a cocoa app supported on 10.6, and I use cell-based NSTableView.
I custom the NSCell so that it can display image and text.
The Problem here is : when I set the doubleClickAction to the tableview, it did not respond.
I have already found it due to the custom cell. I guess the cell stops the responding chain, but I don't know how to fix it. I search the document, and I've no idea which method to be overridden.
Please give some guides and Thanks!

A: For anyone coming across this question as I did, the solution in my case was a missed call to:
[self.tableView setTarget:self]; //This was missed
[self.tableView setDoubleClickAction:@selector(doubleClick:)];


text:
Q: Getting the days since last occurence of a value within a group I have the following dataframe:

customer_id
start_date
end_date
incident

1
2022-01-01
2022-01-03
False

1
2022-01-02
2022-01-04
True

1
2022-01-04
2022-01-06
False

1
2022-01-05
2022-01-08
False

1
2022-01-05
2022-01-06
False

I know want to know for each customer and row, how many days ago the last incident occured. To be precise: For each row I want to know the days from start_date until the end_date of the last row with incident == True
This would be the desired output.

customer_id
start_date
end_date
incident
days_since_last_incident

1
2022-01-01
2022-01-03
False
Nan

1
2022-01-02
2022-01-04
True
Nan

1
2022-01-04
2022-01-06
False
0

1
2022-01-05
2022-01-08
False
1

1
2022-01-05
2022-01-06
False
1

Is there an elegant solution to this?
So far, I tried to work with an apply function, and then applied another function to each row, but that threw out of bounds error for those rows for which they weren't any previous incidents. Here is my attempt so far. It only works for rows with previous incidents:
def days_since_last_incident(group):
    group["days_since_last_incidents"] = group.apply(
        lambda row: (
            row["start_date"]
            - (
                group[
                    (group["incident"] == True)
                    & (group["end_date"] <= row["start_date"])
                ]["end_date"].values
            )
        ).days,
        axis=1,
    )

df.groupby("customer_id").apply(days_since_last_incident)

A: Try (explanation below):
# Not mandatory if start_date and end_date are already DatetimeIndex
df['start_date'] = pd.to_datetime(df['start_date'])
df['end_date'] = pd.to_datetime(df['end_date'])

def days_from_last_incident(df):
    return (df['end_date'].where(df['incident']).ffill()
                          .rsub(df['start_date'])
                          .mask(df['incident'])
                          .dt.days.to_frame())

df['days'] = df.groupby(['customer_id'], group_keys=False).apply(days_from_last_incident)

Output:
>>> out

   customer_id start_date   end_date  incident  days
0            1 2022-01-01 2022-01-03     False   NaN
1            1 2022-01-02 2022-01-04      True   NaN
2            1 2022-01-04 2022-01-06     False   0.0
3            1 2022-01-05 2022-01-08     False   1.0
4            1 2022-01-05 2022-01-06     False   1.0

Step by step for the first group (customer_id=1)
# Step 1: keep only end_date where incident is true the front fill the end date
>>> out = df['end_date'].where(df['incident']).ffill()
0          NaT
1   2022-01-04
2   2022-01-04
3   2022-01-04
4   2022-01-04

# Step 2: (right) subtract start_date
>>> out = out.rsub(df['start_date'])
0       NaT
1   -2 days
2    0 days
3    1 days
4    1 days

# Step 3: remove delta for all rows where incident is true
>>> out = out.mask(df['incident'])
0      NaT
1      NaT
2   0 days
3   1 days
4   1 days
dtype: timedelta64[ns]

# Step 4: keep the day part of timedelta
>>> out = out.dt.days.to_frame()
     0
0  NaN
1  NaN
2  0.0
3  1.0
4  1.0


text:
Q: Android INSTALL_REFERRER and Google Play Store I played around with the INSTALL_REFERRER and everything works perfectly fine using adb, but not when my app is in the Google Play-Store.
My scenario is:
1) One library containing my BroadcastReceiver (package com.sm.android)
2) My app using the library (package de.sm.android)
In the AndroidManifest.xml-file of the app, the receiver-part looks like:
<receiver
        android:name="com.sm.android.helper.ReferralReceiver"
        android:exported="true" >
        <intent-filter>
            <action android:name="com.android.vending.INSTALL_REFERRER" />
        </intent-filter>
    </receiver>

As said before, using adb I get the install-event, but when downloading the app from the store, I don't get the event. I build my url using https://developers.google.com/analytics/devguides/collection/android/v2/campaigns, it looks like https://play.google.com/store/apps/details?id=de.sm.riskulator&referrer=utm_source%3Dgoogle%26utm_medium%3Dbanner%26utm_content%3D234124%26utm_campaign%3Dpromo and forwards correctly to my app.
Thanks in advance,
Sascha

A: I could be wrong but I thought this was now disabled as it was a security hole. i.e It allows code to run on a phone before the user initiates it.
Update: Links for reference.
https://nayaneshguptetechstuff.wordpress.com/2014/06/24/receiver-not-working-know-more-about-stopped-state-of-an-application/
http://developer.android.com/about/versions/android-3.1.html
(See Launch controls on stopped applications)
Intercept INSTALL_REFERRER and then forward on to Google AnalyticsReceiver


text:
Q: Jump to line in CSV file I have a CSV file that looks like this:

*

*a'man

*a-bomb

*a-line

just with a around 30.000 entries. So I know the exact number of lines and now I want to jump to a specific line and retrieve its string.
How can I do this? The CSV parsers I have seen only parse all entries of a file.
I need this for an iOS app, so the programming language is Objective-C. If there is a more elegant and faster solution your are welcome to tell me.

A: Try this
NSArray * array = [string componentsSeparatedByString:@","];
NSString * string = [array objectAtIndex:10];

Or change the separator, but in csv file (Comma Separated Value)


text:
Q: WPF/MVVM Alternate background color of menuitems I've looked and tried to figure this out myself but I've been stuck on this for a while now, and I was wondering if its possible to alternate the background color of a  menuitem in WPF? I've tried alternatecount on the menuitems and tried to change the background color based off of that, but nothing happens. I know I could hardcode the background color of the menuitems but my menu's are dynamic and change as I'm using an MVVM pattern to bind them. If anyone knows how to do this, any help would be appreciated.
Thanks

A:
You can change it with a style. Just this under your Menu.Resources :
    <Style TargetType="MenuItem">
        <Setter Property="Background" Value="SkyBlue" />
    </Style>

EDIT: You can use AlternationCount to achieve this :
<Menu AlternationCount="2">
    <Menu.ItemContainerStyle>
        <Style TargetType="MenuItem">
            <Style.Triggers>
                <Trigger Property="ItemsControl.AlternationIndex" Value="0">
                    <Setter Property="Background"  Value="Red"></Setter>
                </Trigger>
                <Trigger Property="ItemsControl.AlternationIndex" Value="1">
                    <Setter Property="Background" Value="Blue"></Setter>
                </Trigger>
            </Style.Triggers>
        </Style>
    </Menu.ItemContainerStyle>

    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
    <MenuItem Header="qwe" />
</Menu>


text:
Q: Render one div of child component directly in app component or root component in react js I have multiple components and I need to render one modal div at in main app,
tried using, but it's not working for me in react
const element = document.getElementsByClassName()[0].appendChild();

Is there any way rather than putting that component directly to App


text:
Q: Again ERROR java.util.concurrent.TimeoutException: android.view.ThreadedRenderer.finalize() timed out after 10 seconds Please don't mark as duplicate
I get this error very often on crashlytics, and I can't find the problem. I saw it here or here but  I don't have any WebViews in my app.
I have in my app some AsyncTasks that are processing some date: select from DB, compare and call the listener to update UI when is done (I check if activity is still visible when it's needed to update UI). This processing can be long if user has 10k records to compare.
Have to mention that error happens for different devices manufacturers (more on Samsung) and on different Android versions (more on Andorid 6.0 +)
I get this error many times as different one, for example:

File: Daemons.java:217

 java.util.concurrent.TimeoutException: android.view.ThreadedRenderer.finalize() timed out after 10 seconds
1   at android.view.ThreadedRenderer.nDeleteProxy(Native Method)
2   at android.view.ThreadedRenderer.finalize(ThreadedRenderer.java:459)
3   at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:217)
4   at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:200)
5   at java.lang.Thread.run(Thread.java:818)

File: Daemons.java:206

    java.util.concurrent.TimeoutException: android.view.ThreadedRenderer.finalize() timed out after 10 seconds
1   at android.view.ThreadedRenderer.nDeleteProxy(Native Method)
2   at android.view.ThreadedRenderer.finalize(ThreadedRenderer.java:449)
3   at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:206)
4   at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:189)
5   at java.lang.Thread.run(Thread.java:818)

File Daemons.java:210

    java.util.concurrent.TimeoutException: android.view.ThreadedRenderer.finalize() timed out after 15 seconds
1   at android.view.ThreadedRenderer.nDeleteProxy(Native Method)
2   at android.view.ThreadedRenderer.finalize(ThreadedRenderer.java:427)
3   at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:210)
4   at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:193)
5   at java.lang.Thread.run(Thread.java:818)

etc...

A: As one of the posts you link to describes, this is an exception being generated by garbage collection taking too long for an object with a native code implementation.  I ran into this exception and found a solution by looking at the source code producing this exception java.lang.Daemons$FinalizerDaemon.finalizerTimedOut() which you can see here.
In finalizerTimedOut(), if Thread.getDefaultUncaughtExceptionHandler() == null, it create and logs a TimeoutException() and exits with a non-zero code (System.exit(2);)!  To the user, this will look like an FC!  To prevent this, you need to call Thread.setDefaultUncaughtExceptionHandler() to catch and handle this exception.


text:
Q: CSS input:not(input:focus) selector? Is it possible to select an input that does not have focus?

div{
  background: grey;
  margin: 10px;
  padding:10px;
}
intput:not(:focus) {
    background: inherit !important;
    border: none !important;
}
<div>
  <input type="text" />
</div>

A: The right syntax is input:not(:focus). That will select all inputs that aren't in focus.


text:
Q: Setting Range.Value causes #VALUE! in Excel VBA, and also resubmitting a function causes all other functions to be resubmitted I apologise for how trivial this must be for VBA developers, but I have done some digging and cannot fathom why the following code, when assigned to a cell and executed, results in #VALUE!
Function foo()
    Range("A1:B3").Value = 10
End Function

The excel sheet:

I initially tried
ActiveSheet.Range("A1").Value = "abc"

but that didn't work either.  What very simple thing am I doing wrong here?
Also, why, when I try to re-execute the function (using F2 and then Enter), does excel resubmit other functions that are in the same worksheet?  This is truly maddening. I have hit F2 and Enter, so why would Excel think that I want to resubmit all other functions, and how can this be prevented?
Thanks very much.

A: Edit: You tried to use UDF for changing some fields and consistent about the use of some kind of event modification instead of firing your code from a button in your comments with @Mathieu Guindon. Since UDF fire the code only when some cells are recalculated, it is assumed that your requirement is to fire the code when some cells in the sheet get changed either manually or through some formula. The solutions offered below run the code when value of cell F1 change. You may please modify it according to your need.
Old Post: It is not a clean way but may be a called dirty workaround idea. Supposing you want to  any change in cell F1 value to execute the code, may try
Public F1Val As Variant
Private Sub Worksheet_Activate()
F1Val = Range("F1").Value
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If F1Val <> Range("F1").Value Then
Range("A1:B3").Value = 10
F1Val = Range("F1").Value
End If
End Sub

Caution:Certainly it will backfire if cell F1 is linked with formula with the cells getting changed.
Alternately if only manual change of cell F1 is suffice for code to execute then may simply try
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("F1")) Is Nothing Then
Range("A1:B3").Value = 10
End If
End Sub


text:
Q: RHEL 7 service kicks in immediately I am migrating an application from RHEL 6 to 7. In RHEL 6, I used chkconfig and in 7 I am attempting to use systemctl ( config shown below).
However, I noticed that if I stop the service using the actual command (instead of using systemctl stop ), the service gets started up automatically. I dont want this to happen. How do I disable this ?

[Unit]
Description=My service

[Service]
User=my_account
Group=my_account
Type=simple
WorkingDirectory=/some_location
ExecStart=/some_location/start_my_service.sh
ExecStop=/some_location/stop_my_service.sh

[Install]
WantedBy=multi-user.target

A: It's a bad idea but you can force SystemD to not restart it with the line
Restart=no

in the service definition. See man systemd.service for more information about the options.


text:
Q: How do you create a global array of strings? How do you create a global array of strings? I have tried declaring a string outside of main and dynamically initializing it using myString = new string[5];, but I receive the error "No viable overloaded '='" in Xcode. What am I doing wrong?

A: Is this what you want?
char const *myStrings[] = {
    "Some",
    "Strings"
};

A: You need to use curly brace notation to initialize an array:
std::string myString[5] =
{
    "string1",
    "string2",
    "string3",
    "string4",
    "string5"
};

If you're simply trying to declare and allocate it, all you need is:
std::string* myString = new std::string[5];

A: Have you made sure myStrings is a pointer i.e string* myStrings not string myStrings

A: Your code snippet is a little terse, but if your full declaration is
string myString = new string[5];

then the problem is that you are trying to assign an array of strings to a variable that's only designed to hold one particular string. You'll want to do
string *myStrings = new string[5];

where the global variable contains a pointer to the first string in the array -- or
string myStrings[5];

where the global variable is the array.


text:
Q: Can't get user avatar I'm trying to get user's avatars for a welcome message but when someone joins it never shows it. I've tried many different methods. Here is my current code.
bot.on('guildMemberAdd', member => {
    const exampleEmbed = new MessageEmbed()
    .setColor('#0000FF')
    .addField('Welcome!', `Welcome to the server, ${member}! Go to <#channel> for the rules, then grab some roles at <#channel>!`)
    .setThumbnail(member.user.displayAvatarURL)
    member.guild.channels.cache.get('693219932904751177').send(exampleEmbed);

});

A: All you need to do it add a () behind the .displayAvatarURL
So the line would look like this:
.setThumbnail(member.user.displayAvatarURL())


text:
Q: change size of \ref to match text How to change font size of \ref shows how to change the font size of references everywhere.  What if I want to change it to match the surrounding text?
Here's a MWE.
\documentclass[justified]{tufte-handout}

\renewcommand{\thefootnote}{{\footnotesize[\emph{\alph{footnote}}]}}

\begin{document}
\title{Tufte Test}
\maketitle

I want this footnote marker to be \verb|\footnotesize|:\footnote{\label{fn}I.e. {\tt\textbackslash thefootnote} is redefined to emit {\tt \textbackslash footnotesize[\textbackslash emph\{\textbackslash alph\{footnote\}\}]}\ldots}  $\leftarrow$ And it works.

\vspace{2cm}

\noindent{\normalsize \ref{fn}}: $\leftarrow$ But then writing \verb|{\normalsize \ref{fn}}|, just gives me ``{\normalsize \ref{fn}},''  whereas I would wanted to see something like ``[a]'' there.

\end{document}

A: Here, thanks to the hint in David Carlisle's comment, is something that does what I was aiming for.  Once I knew what to look for I found the approach described in Footnote mark in regular or other font styles.
\documentclass[justified]{tufte-handout}

\renewcommand{\thefootnote}{[\emph{\alph{footnote}}]}

\makeatletter%
\long\def\@makefnmark{%
\hbox {\@textsuperscript {\footnotesize \@thefnmark }}}%
\makeatother

\makeatletter%
\long\def\@makefntext#1{%
\@textsuperscript {\@tufte@sidenote@font \@thefnmark }\,\footnotelayout #1}%
\makeatother

\begin{document}
\title{Tufte Test}
\maketitle

%\makeatletter\show\@makefnmark\makeatother <- will depend on class
%\makeatletter\show\@makefntext\makeatother

I want this footnote marker to be \verb|\footnotesize|:\footnote{\label{fn}This
solution redefines both {\tt \textbackslash @thefnmark} and
{\tt \textbackslash @makefntext}.}  $\leftarrow$ And it works.

\vspace{2cm}

\noindent Now \ref{fn} (produced by ``\verb|\ref{fn}|'') matches the
 text.\footnote{\label{fn2}: Even in here; see \ref{fn}.}
\end{document}


text:
Q: how to pass a string  from a UIButton using prepareForSegue I sending a String from a UIButton to my next UITtableviewcontroller, the string is the UIButton Title  (Monday ... Sunday) the string is used by the NSPredicate to filter my table information by day.
@property (nonatomic, weak) NSString *dayOTW;

- (IBAction)selectDay:(UIButton *)sender {
UIButton *dayW = sender;
dayOTW = dayW.titleLabel.text;
NSLog(@"button press = %@", dayOTW);
}

2012-05-01 06:23:21.731 passingdata[99957:fb03] button press = Monday

And segue to my next screen
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
// Make sure your segue name in storyboard is the same as this line
if ([[segue identifier] isEqualToString:@"SendWeekDay"])
{
    // Get reference to the destination view controller
    ViewController *vc = [segue destinationViewController];

    // Pass any objects to the view controller here, like...
    vc.dayOTW = dayOTW;
   }
}

the first time I select the button no information is show in my table , if I go back and select the button again my table show with the correct information for that day .
what i am doing wrong ?
one more question related to the above .
I have 7 UIButtons one for each day on the week, how can segue from all the UIButtons with one segue ?
Thanks

A: The segue is being called before your IBAction method, so the variable is not set the first time you click it.
If the segue is connected to your button, then it will be the sender in prepareForSegue, so you don't really need the action method. Just get the title in prepareForSegue:
UIButton *dayButton = (UIButton*)sender
vc.dayOTW = sender.titleLabel.text;

To connect the same segue to all buttons, you have to ctrl-drag from each button, but give all segues the same identifier. This looks messy on the storyboard, so an alternative is to create a single segue directly from the source view controller, and in the action method (which you would need in this case, and would be connected to all of your buttons) call performSegueWithIdentifier:sender::
-(IBAction)dayButtonPressed:(UIButton*)sender
{
    [self performSegueWithIdentifier:@"SendWeekDay" sender:sender];
}

This would then pass the button to the performSegue method as the sender, so you can use the code outlined above.


text:
Q: Pluralized Rest Resources I want to create a new rest resources that searches an entity in database. I have to make the request as POST since there is a complex criteria passed in a request body.
I created my resource endpoint as /search, however, I learned that resources should be always pluralized. In this case, should I be naming as /searches? I want to know if /searches is a standard naming convention?

A: No, I have never heard that resources should always be pluralized. I would say /search is appropriate here. For example, if you do a search on google or msn, you'll see that they use /search for their searches.
Hopefully this helps.


text:
Q: Is event.preventDefault cancelling change events? I have a certain situation I want to clarify for myself, and I would be glad if anyone has any experience with this issue and is willing to explain it to me.
I have a textarea that has a change event handler:
textarea.bind('change', function(event){
    // do something
});

Hypothetically, what if I have some sort of a click event handler that catches all user clicks:
$(document).bind('click', function(event){
    event.preventDefault();
});

Will this handler also cancel blur and change events for a textarea if a user clicks out of it with his mouse? And if it will, how can I prevent this from happening?
Update: Thank you for your answers, I can not say that I tried it, but I have a similar situation and I am trying to rule out possibilities why change is not firing on my textarea. In my case there is a change handler that doesn't work if I click on an area in which all click events are prevented by default and replaced with custom behaviour.

A: No, it will only prevent the default browser behavior for the 'click' event.

A: No, it won't.

A: Hypothetically, what if you just tried it? (answer: it won't, as stated just before me)
If you don't want users to be able to leave a inputfield (which sounds like strange user interaction to me), you might be able to just set focus after a blur/change event - perhaps you would need a small timeout to let the event finish first. I would not recommend it, but it's always worth a try.


text:
Q: Community Guest User vs Force.com Guest Site User What is the difference between community guest user and Force.com site guest user?
Primarily based on the number of views.  Is there any limitation on concurrency or guest page loads or view.
Thanks!

A: In both contexts there are limitations (albeit high). In both contexts the limitations are a function of the Salesforce editions. Also, as a heads up, there are limitations beyond the # of page views.
In a site context, there are limitations in terms of

*

*Bandwidth Allocation(PER ROLLING 24-HOUR PERIOD PER SITE)

*Service Request Time (PER ROLLING 24-HOUR PERIOD PER SITE)

*Max Page Views

This sites documentation will tell you about the Limitations, Billing and Monthly Page Views Enforcement, What Counts as a Page View, and how to Monitor Usage. To your question, Enterprise Edition Orgs get 500,000 views, and Unlimited Edition get One million.
Likewise, there are limitations around Community Guest Licences. Again, the page view limitation is a function of the SF edition you have, where overages are calculated on a yearly basis. Enterprise Edition Orgs get 500,000/month, and Unlimited Edition get One million/month.  Here is the similar communities documentation
In any case, to track your view usage, check out this free app on the app exchange. This package gives you reports and a dashboard to monitor usage of your Force.com sites. Analyze monthly page views, daily bandwidth, and daily request time to avoid reaching monthly and daily limits for individual sites and your organization. - https://appexchange.salesforce.com/listingDetail?listingId=a0N30000001SUEwEAO


text:
Q: select option text input type hidden display block in javascript When I select the "Number" option, it does not show <input id="number">.
I want all numbers to be selected without input, but when the "Number" option is clicked, it shows <input id="number">. Users can enter a number into <input id="number">.

var select = document.getElementById("select");
$("#select").change(function() {
  var res = select.options[select.selectedIndex].getAttribute("name");
  document.getElementById('number').value = select.options[select.selectedIndex].getAttribute("name");
  $('#number').hide();
  $('#help').hide();
  $('#' + $(this).val()).show();
  return false;
});

<form action="index.php" method="post">
  <select name="select" id="select">
    <option value="1" name="1">1</option>
    <option value="2" name="2">2</option>
    <option value="3" name="3">3</option>
    <option value="number" name="">Number</option>
    <option value="help" name="">Help</option>
  </select>
  <input id="number" type="hidden" name="number" value="Choose" style="display:none" />
  Help!
  <input type="submit" value="submit" />
</form>

A: Don't use type="hidden" .Because its not visible on html if the display:block also .And already you are using jquery so better use selector with jquery $(this).find('option:selected').attr('name')

var select = document.getElementById("select");
$("#select").change(function() {
  var res = $(this).find('option:selected').attr('name')
  $('#number').val(res)
  $('#number').hide();
  $('#help').hide();
  $('#' + $(this).val()).show();
  return false;
});

<form action="index.php" method="post">
  <select name="select" id="select">
    <option value="1" name="1">1</option>
    <option value="2" name="2">2</option>
    <option value="3" name="3">3</option>
    <option value="number" name="">Number</option>
    <option value="help" name="">Help</option>
  </select>
  <input id="number" name="number" value="Choose" style="display:none" />
  Help!
  <input type="submit" value="submit" />
</form>

A: If you put type="number" instead of type="hidden", it will force user to input digits only.

var select= document.getElementById("select");
    $("#select").change(function(){
      var res=select.options[select.selectedIndex].getAttribute("name");
      document.getElementById('number').value=select.options[select.selectedIndex].getAttribute("name");
        $('#number').hide();
        $('#help').hide();
        $('#' + $(this).val()).show();
      return false;
    });

<form action="index.php" method="post">
<select name="select" id="select">
    <option value="1" name="1">1</option>
    <option value="2" name="2">2</option>
    <option value="3" name="3">3</option>
    <option value="number" name="">Number</option>
    <option value="help" name="">Help</option>
</select>
<input id="number" type="number" name="number" value="Choose" style="display:none"/>
Help!
<input type="submit" value="submit"/>
</form>


text:
Q: Create a public connection to SQL Server in Excel with Microsoft Query I want to import data from SQL Server to Excel. Because I want to use parameters in the query's, I use a Microsoft Query instead of the standard SQL Server connection.
When making a custom connection the following screen comes up:

My problem is that the connection string this creates contains my name. Is it possible to create a public connection string that everyone can use? Or can that be done with this connection string aswell?
Below the connection string:
DRIVER=SQL Server Native Client 11.0;SERVER=[SERVERNAME];UID=[MY LOGIN];Trusted_Connection=Yes;APP=Microsoft Office 2010;WSID=[PC NAME];DATABASE=[DATABASE NAME];


text:
Q: ListAdapter showing already shown item when scrolled I'm pretty new to Android, and I'm currently having some problem in using custom list adapter.
Basically, I want to make a list of question, with different type for each question (radio, checkbox, text, numeric).
When the listview is generated, it displayed fine. But when I scroll down, the item from the top gets regenerated in the bottom.
My code is like this :
public View getView(int position, View convertView, ViewGroup parent) {

  View someView = convertView;

  //get question type
  String type = questions.get(position)[2];

  //declare viewholder
  final ViewHolder holder;
  Log.i("Position", Integer.toString(position));

  if (someView == null) {
    Log.i("convertView", "null");
    holder = new ViewHolder();

    LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    someView = inflater.inflate(R.layout.list_survey, parent, false);

    TextView textView = (TextView) someView.findViewById(R.id.surveyQuestion);
    textView.setText(questions.get(position)[1]);

    LinearLayout optionContainer = (LinearLayout) someView.findViewById(R.id.surveyOption);

    int size = options.get(position).size();

    //radio button
    if (type.equals("radio")) {

        RadioGroup group = new RadioGroup(this.context);
        RelativeLayout.LayoutParams groupParam = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        optionContainer.addView(group, groupParam);
        RadioButton radio = null;

        ArrayList<RadioButton> radios = new ArrayList<RadioButton>();

        for (int i=0; i<size; i++){
            radio = new RadioButton(this.context);
            radio.setId(i+1);
            radio.setText(options.get(position).get(i)[1]);
            group.addView(radio);
            radios.add(radio);
        }
        group.setOnCheckedChangeListener(new OnCheckedChangeListener()
        {
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                //Model element = (Model)group;
            }
        });

        holder.radiogroup = group;
        holder.radiobuttons = radios;

    //checkbox
    } else if (type.equals("check")) {
        CheckBox checkbox = null;

        ArrayList<CheckBox> checks = new ArrayList<CheckBox>();

        for (int i=0; i<size; i++){
            checkbox = new CheckBox(this.context);
            checkbox.setId(i+1);
            checkbox.setText(options.get(position).get(i)[1]);
            optionContainer.addView(checkbox);
            checks.add(checkbox);
        }

        holder.checkboxes = checks;

    //textfield
    } else if (type.equals("txt")) {
        EditText field = null;

        ArrayList<EditText> fields = new ArrayList<EditText>();

        for (int i=0; i<size; i++){
            field = new EditText(this.context);
            field.setId(i+1);
            field.setHint(options.get(position).get(i)[1]);
            optionContainer.addView(field);
            fields.add(field);
        }

        holder.edittext = fields;
    //numeric
    } else if (type.equals("num")) {
        EditText field = null;

        ArrayList<EditText> fields = new ArrayList<EditText>();

        for (int i=0; i<size; i++){
            field = new EditText(this.context);
            field.setId(i+1);
            field.setHint(options.get(position).get(i)[1]);
            field.setInputType(InputType.TYPE_CLASS_NUMBER);
            optionContainer.addView(field);
            fields.add(field);
        }

        holder.edittext = fields;
    }

    someView.setTag(holder);

  } else {
    Log.i("convertView", "not null");
    holder = (ViewHolder) someView.getTag();
  }

    return someView;
}

The viewHolder class is here :
//viewHolder
static class ViewHolder {
    ArrayList<CheckBox> checkboxes;
    ArrayList<EditText> edittext;
    RadioGroup radiogroup;
    ArrayList<RadioButton> radiobuttons;
}

What am I doing wrong?
I really appreciate your help. I've searched some other solutions but I can't get it work on my code.
Thanks

A: This happened because you are using the convertView and ViewHolder incorrectly. When you scroll down, the views will be recycled and the converView will not be null. The ViewHolder pattern is usually used this way:
public View getView(int position, View convertView, ViewGroup parent) {
    if(convertView == null) {
        inflate the view
        create a ViewHolder and store the necessary views in it
        use setTag to store the ViewHolder in the convertView
    }
    else {
        use getTag to get the ViewHolder
    }
    update the views // <- you are not doing this when convertView != null
}

The reason that convertView/ViewHolder pattern is used is that views in a list usually have the same layout but different data shown in them. In essence, the convertView (when not null) is a view that was previously used in the list and must be converted to show correct data for this position. By reusing it you avoid the expensive layout inflation. The ViewHolder is a further optimization with which you avoid the also expensive findViewById calls.


text:
Q: Custom validation messages pop up even when input is valid I am trying to define my own invalidate error message for input type='email'.
I use the below HTML. The problem is that when submitting the input, I get the custom error message EVEN if the input value is a valid.
<input name="resp_mail" required="required" onchange="try{setCustomValidity(' ')}catch(e){}" onkeypress="try{setCustomValidity(' ')}catch(e){}" oninvalid="setCustomValidity('Custom error message')" type="email" placeholder="Enter mail" />

Also see this fiddle

A: If you change the order to have the oninvalid first and remove the space for onchange and onkeypress it seem to me that it works.
<input
  name="resp_mail"
  required="required"
  oninvalid="setCustomValidity('Custom error message')"
  onchange="try{setCustomValidity('')}catch(e){}"
  onkeypress="try{setCustomValidity('')}catch(e){}"
  type="email"
  placeholder="Enter mail"
/>

A: this is how you should do it

document.addEventListener("DOMContentLoaded", function (e) {

  /** @this {HTMLInputElement}*/
  function validateInput () {
      const label = document.getElementById("label-"+this.id);
    if (this.validity.patternMismatch) {
        this.setCustomValidity("If pattern does not match set this message");

        return;
    }
    if (this.validity.badInput) {
        this.setCustomValidity("if badInput is invalid show this message");

        return;
    }

    if (this.validity.patternMismatch) {
        this.setCustomValidity("if patternMismatch is invalid show this message");

        return;
    }
    if (this.validity.rangeOverflow) {
        this.setCustomValidity("if rangeOverflow is invalid show this message");

        return;
    }
    if (this.validity.rangeUnderflow) {
        this.setCustomValidity("if rangeUnderflow is invalid show this message");

        return;
    }
    if (this.validity.stepMismatch) {
        this.setCustomValidity("if stepMismatch is invalid show this message");

        return;
    }
    if (this.validity.tooLong) {
        this.setCustomValidity("if tooLong is invalid show this message");

        return;
    }
    if (this.validity.tooShort) {
        this.setCustomValidity("if tooShort is invalid show this message");

        return;
    }
    if (this.validity.typeMismatch) {
        this.setCustomValidity("if typeMismatch is invalid show this message");

        return;
    }

    if (this.validity.valueMissing) {
        this.setCustomValidity("if valueMissing is invalid show this message");

        return;
    }
    // IF YOW INPUT IS VALID CLEANUP CUSTOMMESSAGE
    if (this.validity.valid) {
        this.setCustomValidity("");

        return;
    }
  }

  const phone = document.getElementById("phone");

  phone?.addEventListener("blur", function (evt){
      validateInput.call(this);
  });

  validateInput.call(phone);

});
label,button {
display: block}

input {
margin-bottom: .5rem;
}
<form>
<label id="phone-label" for="phone">Phone</label>
<input maxlength="14" minlength="14" enterkeyhint="send" inputmode="tel" required="true" name="phone" id="phone" type="tel" pattern="[\(]\d{3}[\)]\s\d{3}-\d{4}" />
<button type="submit">submit</button>


text:
Q: Get a single item from JSON in PHP I've seaching stack overflow and did not find what I`m trying to do ...
So here is the question:
HOW TO RETURN STEAMID ONLY?
CODE:
<?php
// define variables and set to empty values
$steamID = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
  $steamID = test_input($_POST["steamID"]);
}
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
$keyApp = '5DE00EE4D07BA728EDAB0B3C2961AA6B';
$api = "";
$json_data = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=$keyApp&steamids=$steamID");
$array = json_decode($json_data, true);
var_dump($array);
?>

var_dump:
array(1) {
  ["response"]=>
  array(1) {
    ["players"]=>
    array(1) {
      [0]=>
      array(19) {
        ["steamid"]=>
        string(17) "76561198058543756"
        ["communityvisibilitystate"]=>
        int(3)
        ["profilestate"]=>
        int(1)
        ["personaname"]=>
        string(12) ""Cientistas""
        ["commentpermission"]=>
        int(1)
        ["profileurl"]=>
        string(37) "https://steamcommunity.com/id/rhatto/"
        ["avatar"]=>
        string(116) "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c9/c9442f1ea597a7685f8e50f2f7c922321beb4eba.jpg"
        ["avatarmedium"]=>
        string(123) "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c9/c9442f1ea597a7685f8e50f2f7c922321beb4eba_medium.jpg"
        ["avatarfull"]=>
        string(121) "https://steamcdn-a.akamaihd.net/steamcommunity/public/images/avatars/c9/c9442f1ea597a7685f8e50f2f7c922321beb4eba_full.jpg"
        ["avatarhash"]=>
        string(40) "c9442f1ea597a7685f8e50f2f7c922321beb4eba"
        ["lastlogoff"]=>
        int(1593317334)
        ["personastate"]=>
        int(0)
        ["realname"]=>
        string(44) "por erro em estudo sobre a hidroxicloroquina"
        ["primaryclanid"]=>
        string(18) "103582791454640235"
        ["timecreated"]=>
        int(1328817888)
        ["personastateflags"]=>
        int(0)
        ["loccountrycode"]=>
        string(2) "CN"
        ["locstatecode"]=>
        string(2) "32"
        ["loccityid"]=>
        int(9982)
      }
    }
  }
}

How can i extract steamid from $array?
Already tryed this links
https://www.codewall.co.uk/how-to-read-json-file-using-php-examples/
https://www.php.net/manual/pt_BR/function.json-decode.php

A: By accessing the correct path to the steamid the only thing is, apparently you might have multiple items in the players array. So you'll probably need a loop of some sorts.
Something like this maybe:
$players = $array['response']['players'];

foreach($players as $player) {
  echo $player['steamid'] . '<br>';
}

Or if you always have 1 player in your players array you could also do this (quick and dirty):
echo $array['response']['players'][0]['steamid'];

A: $steamID = $array['response']['players'][0]['steamid'];


text:
Q: Foreground service START_STICKY is not restarted after being killed in low memory conditions I know there are tones of threads with similar title, but no one of them gives a definitive answer.
We're currently stress testing the foreground service of our application by filling up the RAM with junk with another app and investigating what happens to our application and its foreground service.
So, our foreground service is started and notification is shown to the user, and its mode is START_STICKY. However, when we simulate extreme memory usage the application is killed (which is OK and we can do nothing about it), but the bad thing is that our foreground service never gets restarted. Perhaps I'm confusing something from the START_STICKY doc, but what I can understand from below doc is that system should guarantee the restart, isn't it?

Constant to return from onStartCommand(Intent, int, int): if this
  service's process is killed while it is started (after returning from
  onStartCommand(Intent, int, int)), then leave it in the started state
  but don't retain this delivered intent. Later the system will try to
  re-create the service. Because it is in the started state, it will
  guarantee to call onStartCommand(Intent, int, int) after creating the
  new service instance; if there are not any pending start commands to
  be delivered to the service, it will be called with a null intent
  object, so you must take care to check for this.

The above doc is too vague.
First question is

*

*will it ALWAYS RESTART the service? If not, what are the
conditions for the service being restarted and what are the
conditions when it won't be restarted?

And the second question is

*

*What does it mean Later? Later when? Later next year or what? :D

To summarize, we do need to guarantee that our foreground service will restart whatever it takes. Any ideas?

EDIT 1:
I did investigate the logcat logs a little bit more. Here's is what happens.
Process com.MY_PACKAGE_ID (pid 1192) has died: prcp FGS
Scheduling restart of crashed service com.MY_PACKAGE_ID/MyForegroundService in 1284608ms

Obviously, the system kills the application and schedules a restart. In this case it's approximately in 21 minutes. In other cases I would see that the reschedule time was 10.000ms aka 10 seconds. And, in 10 seconds the device would still be in memory stressful situation and the app will not be launched. Which implies, that in case the service fails to start at rescheduled time there won't be any 2nd rescheduling and the service will never restart. But, if at rescheduled time the device was in normal non-memory stressful conditions, the restart will happen successfully.


text:
Q: Use arrays and if or for loops and output separate files My office gets text 7 text files with about 10,000 lines of text each 163 characters long. The string of text ends in zip codes either in 5 digit or 10 character strings (ex. xxxxx or xxxxx-xxxx). I am trying to write a script that will read the text files and output filtered text files into their mail distribution counties
I have taken one file and have been successful and getting an output of certain zips with this:
$content | Select-String -Pattern ".{153}006[0-9]{2,}"

I have set up arrays for each county with an empty array where non-ca zip codes will be sorted to reno. I haven't gotten as far as to put values into reno.
Code
$LA = 900,901,902,903,904,905, 907, 908
$Industry = 906, 917, 918
$SantaClarita = 910,916
$SanDiego = 919,921
$SanBernardino= 922,925
$SantaAna = 926,927
$Anaheim = 928
$SantaBarbara = 930, 931, 934
$Bakersfield = 932, 933, 935
$Fresno = 936, 937, 938
$SanJose = 939, 950, 951
$SanFrancisco = 940, 941, 943, 944, 949, 954
$Sacramento = 942, 952, 953, 956, 957,958,959
$Oakland = 945..948
$Eureka = 955
$Redding = 960
[String]$Reno = @()

<#put values into $Reno
if (values are not in $zipcodes){$reno = $_}

Please excuse the formatting#>

I would like the script to flow like
$content = get-content -path .\*txt

if ($content | Select-String -Pattern ".{153}$LA[0-9]{2,}")
      {
      out-file -path .$LA.txt
      }

so on and so forth and values not found in move to reno.txt
Output Text:
<153 Characters>xxxxx
<153 Characters>xxxxx-xxxx

Input Lines
123456          92345555                                                                2570 S Fake St    AVE                       280SNO                      CA  93725-1724
123456          92345555                                                                2560 S Fake St    AVE                       280SNO                      CA  93725-1124

A: I feel like this could be better served by creating a hashtable to track what city each code goes to, then using that as a lookup. Then you could use a capture group, and reference that to the hashtable, and be done with it.
$CityHT = @{}
900,901,902,903,904,905, 907, 908 | %{$CityHT.Add($_.ToString(),"LA.txt")}
906, 917, 918 | %{$CityHT.Add($_.ToString(),"Industry.txt")}
910,916 | %{$CityHT.Add($_.ToString(),"SantaClarita.txt")}
919,921 | %{$CityHT.Add($_.ToString(),"SanDiego.txt")}
922,925 | %{$CityHT.Add($_.ToString(),"SanBernardino.txt")}
926,927 | %{$CityHT.Add($_.ToString(),"SantaAna.txt")}
928 | %{$CityHT.Add($_.ToString(),"Anaheim.txt")}
930, 931, 934 | %{$CityHT.Add($_.ToString(),"SantaBarbara.txt")}
932, 933, 935 | %{$CityHT.Add($_.ToString(),"Bakersfield.txt")}
936, 937, 938 | %{$CityHT.Add($_.ToString(),"Fresno.txt")}
939, 950, 951 | %{$CityHT.Add($_.ToString(),"SanJose.txt")}
940, 941, 943, 944, 949, 954 | %{$CityHT.Add($_.ToString(),"SanFrancisco.txt")}
942, 952, 953, 956, 957,958,959 | %{$CityHT.Add($_.ToString(),"Sacramento.txt")}
945..948 | %{$CityHT.Add($_.ToString(),"Oakland.txt")}
955 | %{$CityHT.Add($_.ToString(),"Eureka.txt")}
960 | %{$CityHT.Add($_.ToString(),"Redding.txt")}

That leaves you with a hashtable that will match those numbers (in string form) to an output file. Then you just need to add anything that goes to Reno. You can use the matches that are automatically generated by Select-String to do that.
#Get content and perform matching
$Content = Select-String -Path "*.txt" -Pattern ".{153}(\d{3})[0-9]{2,}"
#Add extra codes to Reno
$Content.Matches.Groups.Captures|?{$_.Name -eq '1' -and $_.Value -notin $CityHT.Keys}|Select -ExpandProperty Value -Unique|ForEach-Object{$CityHT.Add($_,"Reno.txt")}
#Add content to files by matches
$Content|ForEach{Add-Content -Value $_.Line -path $CityHT[$_.Matches.Groups[1].Value]}

Edit: Ok, I just tested this against multiple files and made a revision to make it work with multiple files. Now, as requested, let's break the second codeblock down. The first thing we do is look for matching patterns in your files. The Select-String cmdlet allows you to specify a path, wildcards accepted, in which it will attempt to perform the string matching. So rather then reading in the whole files, then piping that against Select-String I just do it in one step. What Select-String outputs is more than just the lines that match, it also outputs matching information for each line. I slightly modified your RegEx pattern to include a capture group, so it now captures the three digits we care about as part of the output. If you just output it to screen it only shows you the source file, line number, and line text, but there's more there than that. Let's look at a single entry piped to Format-List:
IgnoreCase : True
LineNumber : 1
Line       : 123456          92345555                                                                2570 S Fake St    AVE                       280SNO                      CA  93725-1724
Filename   : datain.txt
Path       : C:\temp\datain.txt
Pattern    : .{153}(\d{3})[0-9]{2,}
Context    :
Matches    : {0}

Now, each line that matched the pattern has an entry like this. Due to how matches are handled the Matches property will contains a Groups property with at least 1 entry, and 1 additional entry for each capturing group that the regular expression had (in our case only 1 capturing group). So when I reference .Matches.Groups[1].Value I can get that line's 3 digit code that was in the capturing group.
I use that in the next line, where I loop through all of the entries in $Content, checking if that 3 digit code already has a record in the hashtable that we created earlier, and if it is already in there I filter it out passing only codes that aren't accounted for down the pipeline with this bit of code:
$Content.Matches.Groups.Captures|?{$_.Name -eq '1' -and $_.Value -notin $CityHT.Keys}

That could pass a lot of 3 digit codes down the pipeline, many of which I suspect would be duplicates, so I pass it to |Select -Unique to only get unique 3 digit codes. Those I add to the hashtable and assign to Reno.txt, so anything not defined in the first section automatically goes to Reno.
Now, for the last line... I pass $Content into a loop and use Add-Content to write each line to a path based on the captured value. We have a hashtable that will convert a 3 digit code into a filename for the associated city, so I just reference that to determine which file to write each line to.


text:
Q: Pie Chart Not Popping Up HighCharts I am trying to make a pie chart that shows that rating of a python course. However every time I try to run it, the pie chart doesn't pop up, only the title. I am using HighCharts to create the pie chart and it is also supposed to be interactive. This is what I am using to create the pie chart. I also don't get any error message. Please help me.
https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/pie-basic
This is my code down below:
import justpy as jp
import justpy as jp
import pandas as pa
from datetime import datetime
from pytz import utc

data = pa.read_csv("reviews.csv", parse_dates=['Timestamp'])
share = data.groupby(['Course Name'])['Rating'].count()

chart_def = """
 {
    chart: {
        plotBackgroundColor: null,
        plotBorderWidth: null,
        plotShadow: false,
        type: 'pie'
    },
    title: {
        text: 'Browser market shares in January, 2018'
    },
    tooltip: {
        pointFormat: '{series.name}: {point.percentage:.1f}%'
    },
    accessibility: {
        point: {
            valueSuffix: '%'
        }
    },
    plotOptions: {
        pie: {
            allowPointSelect: true,
            cursor: 'pointer',
            dataLabels: {
                enabled: true,
                format: '{point.name}: {point.percentage:.1f} %'
            }
        }
    },
    series: [{
        name: 'Brands',
        colorByPoint: true,
        data: [{
            name: 'Chrome',
            y: 61.41,
            sliced: true,
            selected: true
        }, {
            name: 'Internet Explorer',
            y: 11.84
        }, {
            name: 'Firefox',
            y: 10.85
        }, {
            name: 'Edge',
            y: 4.67
        }, {
            name: 'Safari',
            y: 4.18
        }, {
            name: 'Sogou Explorer',
            y: 1.64
        }, {
            name: 'Opera',
            y: 1.6
        }, {
            name: 'QQ',
            y: 1.2
        }, {
            name: 'Other',
            y: 2.61
        }]
    }]
}
"""
def app():
    wp = jp.QuasarPage()
    h1 = jp.QDiv(a = wp, text = "Analaysis of Course Reviews", classes='text-h3 text-center q-pa-md')
    p1 = jp.QDiv(a = wp, text = "These graphs represent course review analaysis")

    hc = jp.HighCharts(a= wp, options = chart_def)
    hc_data = [{"name":v1, "y":v2} for v1, v2 in zip(share.index, share)]
    hc.options.series[0].data = hc_data

    return wp

jp.justpy(app)

A: I had the same problem.
I fixed it by removing (or commenting out) the 2 code lines below, which set the "plotBackgroundColor" and "plotBorderWidth" properties to null:
chart_def = """
 {
    chart: {
        //plotBackgroundColor: null,  --> remove or comment out this line
        //plotBorderWidth: null, --> remove or comment out this line
        plotShadow: false,
        type: 'pie'
    },

(...)


text:
Q: Proving an identity regarding Levi-civita connections of a metric
Here $\nabla$ is the levi-civita connection of the given metric $g$. I am stuck at the last equality (g). What on earth does $\nabla^a \nabla_a$ mean? Isn't it just $g^{ab}\nabla_a \nabla_b$? But, then the equality does not hold because the left side of (g) is just $g^{ab}\partial_a\partial_bf$ and the right side of (g) contains more than that. Could anyone please help me what $\nabla^a \nabla_a$ mean?

A: You are right for the first statement, i.e.,
$$
\nabla^a\nabla_af=g^{ab}\nabla_a\nabla_bf.
$$
However, your second statement remains to be improved. Provided that
$$
\nabla_bf=\partial_bf
$$
is a vector,
$$
\nabla_a\nabla_bf=\nabla_a\left(\partial_bf\right)=\partial_a\left(\partial_bf\right)-\Gamma_{ab}^c\left(\partial_cf\right).
$$
Therefore,
$$
\nabla^a\nabla_af=g^{ab}\nabla_a\nabla_bf=g^{ab}\left(\partial_a\partial_bf-\Gamma_{ab}^c\partial_cf\right).
$$
This is still faraway from the ultimate goal. To make it short, we could turn to part (e) for help.
Provided that, using $\nabla_ag^{bc}=0$,
$$
\nabla^a\nabla_af=g^{ab}\nabla_a\nabla_bf=\nabla_a\left(g^{ab}\nabla_bf\right)=\nabla_a\left(g^{ab}\partial_bf\right)
$$
and that, from part (e),
$$
\nabla_aV^a=\left|g\right|^{-1/2}\partial_a\left(\left|g\right|^{1/2}V^a\right),
$$
let $V^a=g^{ab}\partial_bf$, and the last formula immediately gives
$$
\nabla^a\nabla_af=\nabla_a\left(g^{ab}\partial_bf\right)=\left|g\right|^{-1/2}\partial_a\left(\left|g\right|^{1/2}g^{ab}\partial_bf\right),
$$
as is expected.


text:
Q: jQuery IE6 dilemma: animate scrollLeft or left? I have a few panels that I slide horizontally using the animate function that jQuery so generously provides.
The problem is that 100% of the clients that will be using this small app I am making use IE6. I am worried that because the panels contain a few elements on them, not too many but not few it will be very slow on IE6 and the rather poor-ish PCs that will be seeing this.
Now the question, should I animate scrollLeft to scroll the parent div or should I reposition the child div animating css left attribute?
Is there any performance gain by chosing one over the other? (I cannot test on the target PCs at the time being to be able to make an empirical decision.)
Thank you.

A: From my experience, animating scrollLeft gives better performance because most browsers do not redraw the entire window when scrolling (otherwise scrolling down a page would be ridiculously laggy for the slower computers...), while animating the left css property would cause the browser to redraw.


text:
Q: Promisify an upload with multer I have some troubles using multer and promises (bluebird).
I try to upload a pdf file in a folder then extract the text inside this pdf with the plugin (textract)
Both of the functions I created works, but I have some trouble in the execution and the promisification of the upload function. here's my code :
pdf-rest.js :
var bodyParser = require('body-parser');
var request = require('request');
var jsonParser = bodyParser.json();
var fs = require('fs');
var Promise = require('bluebird');
var multer  = require('multer');
var textract = require('textract');

module.exports = function(app) {

var destination = "uploads";
var filename = "" + Date.now() + ".pdf";
var filePath = "C:\\wamp64\\www\\ebook-stage\\backend\\rest\\uploads\\" + filename;
var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, destination);
    },
    filename: function (req, file, cb) {
        cb(null, filename);
    }
});
        app.post('/rest/create_pdf', function (req, res) {

            var upload = multer({storage: storage}).single('file');

            function uploadFile() {
                var uploadFilePromise = new Promise(function (resolve, reject) {
                    upload(req, res, function (err) {
                        if (err) {
                            reject(err);
                            res.end('error uploading file')
                        }
                        else {
                            res.end('file uploaded');
                            console.log('fileupload')
                        }
                    });
                    resolve(upload);
                });
                console.log(uploadFilePromise);
                return uploadFilePromise;
            }

            function textractPdf(path) {
                textract.fromFileWithPath(path, function (error, text) {
                    console.log('textract');
                    if (text) {
                        console.log(text);
                        return text;
                    }

                    else {
                        console.log(error);
                        return error;
                    }
                });
            }

            uploadFile().then(textractPdf(filePath));

            });

server.js :
var express = require('express');

var app = express();

require('./pdf-rest.js')(app);

app.listen(8080);

I use a button to execute this script in a HTML page, the upload of the pdf in the folder work the first time I click on the button but the textract doesn't.
I know I do something wrong, the execution of the function textractPdf(Path) is done first. I think I didn't promisify correctly my upload function.


text:
Q: Yesod - Persistent - getting migrations sql instructions I am using persistent-odbc, and would like to know how to get the SQL instructions to run manually the create table instructions, instead of automatically doing the migrations.

A: You can use printMigration to see what migrations you have to manually run. Just replace the runMigration function with printMigration and it should do the job.


text:
Q: How to use Alamofire inside a framework? I would like to use Alamofire in my framework's viewcontroller to make some network request.
// Call
let myURLString = "https://jsonplaceholder.typicode.com/todos/1"
Alamofire.request(myURLString)
    .responseJSON { response in
        // do stuff with the JSON or error
}

However, it's returning
No such module 'Alamofire'

A: Firstly you should create target of your CocoaTouch Framework.
And then you should add your CocoaTouch Framework to your Main Project's PodFile:
# Uncomment the next line to define a global platform for your project
platform :ios, '9.0'

target 'MainApp' do
  use_frameworks!
end

target 'CocoaTouchFramework' do
  use_frameworks!
end

pod 'Alamofire'

Or you can set specific pods for frameworks:
platform :ios, '9.0'
use_frameworks!

#Your custom framework's pods
def customframework_pods
    pod 'Alamofire'
end

target 'MainApp' do
    pod 'MyAwesomePod', '~>1.0'
    customframework_pods
end

target 'CocoaTouchFramework' do
    customframework_pods
end

I found one more answer about this:
Source: Youval Vaknin's Medium Article
# Uncomment this line to define a global platform for your project
platform :ios, '8.0'
# Uncomment this line if you're using Swift
# use_frameworks!
workspace 'YourWorkSpaceName'
xcodeproj 'Project/ProjectName.xcodeproj'
xcodeproj 'CustomFramework/Framework.xcodeproj'

def project_pods
    pod 'Alamofire'
end

def framework_pods
    pod 'Alamofire'
end

target 'ProjectName' do
    xcodeproj 'Project/ProjectName.xcodeproj'
    project_pods
end

target 'ProjectName' do
    xcodeproj 'Project/ProjectName.xcodeproj'
    project_pods
end

target 'Framework' do
    xcodeproj 'CustomFramework/Framework.xcodeproj'
    framework_pods
end

target 'Framework' do
    xcodeproj 'CustomFramework/Framework.xcodeproj'
    framework_pods
end

I hope it works
Enjoy


text:
Q: how to read from pandas dataframe with networkx versions before 2.0 I need to generate a networkx graph with arc attributes from a pandas dataframe. In networkx version 2.0, I am aware of the from_pandas_dataframe function and I did what I wanted as follows:
graph=nx.from_pandas_dataframe(df_t, 'node2', 'node1', ['Transit Time','arctype','node1type','node2type','cpt'],nx.DiGraph())

However  at the moment I have to use networkx 1.9., which does not have from_pandas_dataframe function. I was wondering how I can do that. Any help will be appreciated.
P.S. I am deploying my application in a framework which has only networkx v1.9. I don't have time to upgrade the networkx version in the framework so I am trying to change my own code.

A: Using IPython, you can find the file which defines nx.from_pandas_dataframe:
In [125]: import networkx as nx
In [126]: nx.from_pandas_dataframe?
...
File:      ~/.virtualenvs/muffy/lib/python3.4/site-packages/networkx/convert_matrix.py

Inspecting this file (or the source on github) shows from_pandas_dataframe is fairly simple and depends only on one helper function, _prep_create_using.
So you could create a file utils_networkx.py and insert there the definitions of
_prep_create_using and from_pandas_dataframe. Just be sure to place utils_networkx.py in a directory listed in your PYTHONPATH environment variable so that Python can import it as a module.
Then you could use it like this:
import numpy as np
import pandas as pd
import networkx as nx
import utils_networkx as UNX

r = np.random.RandomState(seed=5)
ints = r.randint(1, 10, size=(3,2))
a = ['A', 'B', 'C']
b = ['D', 'A', 'E']
df = pd.DataFrame(ints, columns=['weight', 'cost'])
df[0] = a
df['b'] = b
print(df)
#    weight  cost  0  b
# 0       4     7  A  D
# 1       7     1  B  A
# 2      10     9  C  E
G = UNX.from_pandas_dataframe(df, 0, 'b', ['weight', 'cost'])
print(G['E']['C']['weight'])
# 10
print(G['E']['C']['cost'])
# 9

The code above comes from the from_pandas_dataframe docstring.


text:
Q: Socket communication in C language. Sending file contents So the other day I got a relatively simple assignment, which was to build some client and some server code that in which the server received a message and returned its current system time. It wasn't hard to do, i delivered and got an easy mark.
I started thinking a bit more on it and I decided to set out and try to send the contents of specific file server --> client (server sends contents to client). While i was building the code I tested every so often locally and it worked as intended, the real problem arose when I uploaded the server code to my server (hah) running Ubuntu. Started the server, everything OK, started the client, asked for "index.html" and BAM! half the file wasn't received.
The server prints it (I made it so it printed the contents of file as it sent so I could troubleshoot with more ease).
I have been searching for a bit now and every time I find something that looks useful it ends being in a different programming language and cant find any equivalents in C.
Using sleeps in both client and server code seems to solve this, but I figure it's not good practice.
The code is a mess so I'll include what I figure is relevant, I'll also include a link tot he full code. I really meant to improve it but so got demotivated while trying to fix this that I just made it worse.
Client side
printf("Please specify the filename: ");
fgets(msg,1000,stdin); // get message from std input

if(strcmp(msg,"\n")==0) {
    printf("Wrong file name or format\n");
    printf("Please specify the filename: ");
    fgets(msg,1000,stdin); // get message from std input
}

while(strcmp(msg,"!stop\n")) {

    msg[strlen(msg)-1]='\0';
    write(sockfd,msg,strlen(msg));
    FILE *fp = NULL;

    char filecontent[1000];
    bzero(filecontent,sizeof(filecontent));

    while(  (n = read(sockfd,filecontent,1000)) && strcmp(filecontent,"Over and out!")!=0  ) {

        if(strcmp(filecontent,"No such file")!=0 && fp == NULL) {
            fp = fopen(msg,"w");
        }

        printf("%s",filecontent);

        if(fp !=NULL)
            fprintf(fp, "%s",filecontent);

        bzero(filecontent,sizeof(filecontent));
    }

    if(fp != NULL)
        fclose(fp);

    printf("\nPlease specify the filename: ");
    fgets(msg,1000,stdin); // get message from std input

    if(strcmp(msg,"\n")==0) {
        printf("Wrong file name or format\n");
        printf("Please specify the filename: ");
        fgets(msg,1000,stdin); // get message from std input
    }

}

Server side
   char date[50];
time_t ticks;
struct tm *tinfo;
time(&ticks);
tinfo=localtime(&ticks);
strcpy(date,asctime(tinfo));
printf("DATA: %s\n",date);
write(newsocketfd,date,sizeof(date));

while( (n = read(newsocketfd,msg,1000)) && strcmp(msg,"!stop\n")!=0) {
    //printf("MSG: %s\n",msg);

    if(n<0)
        error("ERROR READING");
    /////////READING FILE/////////////

    char *filename = malloc(sizeof(msg)+1);
    strcpy(filename,msg);
    printf("'server filename:%s'\n",filename);
    FILE *fp = fopen( filename,"r");

    if(fp == NULL) {
        printf("No such file found\n");
        write(newsocketfd,"No such file",sizeof("No such file"));
    }

    while( fp!=NULL && fgets(msg,1000,fp)!=NULL){
        write(newsocketfd,msg,sizeof(msg));
        msg[strlen(msg)-1]='\0';
        printf("server: '%s'\n",msg);
        bzero(msg,sizeof(msg));

    }

bzero(msg,sizeof(msg));
bzero(filename,strlen(filename));
n = write(newsocketfd,"Over and out!",sizeof("Over and out!"));
printf("Over\n");

}

sorry for any headaches. Full code here.
Examples:
I think this pretty much shows the problem
My thinking was, the server reads the file, line by line, and sends its, line by line, to the client, when it's done the server sends "over" and the client stops reading from there, it seems however that the client never receives all the information or the "over" signal. Worth adding that this works perfectly fine if I run both codes on my local machine.

A: Welcome to the world of network programming! Network protocols are layered for a reason.  When you send something on a TCP socket, and immediately close the socket, the delivery is unreliable: it may be correctly delivered to the peer, or may vanish because of race conditions.
The only reliable way is to only close the socket when the peer sends an acknowledgement that it could receive everything that was sent. Standard protocol use control messages for that, and you really should contemplate that, but if you do not need your server to be warned for client failures, you could simply have the client to close the connection when it has received "Over and out!". BTW, you should be aware that as TCP is a stream protocol, nothing can guarantee that the message will not be splitted in more than one read, or concatenated to other bytes. So you should keep the end of the previous read (size of the signal string minus one byte), concatenate next read to that and search the string anywhere in the buffer.
Another common way is to use a graceful shutdown: the sender uses shutdown(socket.SHUT_WR) to signal that the communication is over without closing the socket and waits (with a read) for the peer to close the socket when everything has been correctly delivered.


text:
Q: Slow performance of AddString in MFC I've got a dialog with several largeish combo boxes in it (maybe several hundred items apiece). There's a noticeable delay at construction while these are populated (confirmed that it's them by profiling).
My initial thought was that sorting was killing it's performance, but disabling sort and using InsertString instead doesn't seem to make things much better. I hadn't thought that it seemed like an excessive number of items - is there something else I should be doing or considering here?
The MFC calls are trivial wrappers to Win32 message calls so I don't think there's any significant overhead there.
DUPLICATE How to load a large array of strings in to an MFC combobox control fast as possible?

A: You should be using CWnd::SetRedraw around your adds, to prevent the control updating all its internal state after each add.
If you're not already doing it, then do this:
combo.SetRedraw(FALSE);

...  All the adds

combo.SetRedraw(TRUE);
combo.Invalidate();

You should also consider using the CComboBox::InitStorage function, which preallocates memory for the combo-box.


text:
Q: Using Fly Dynamic Image Resizer for ACF gallery Trying to use a great plugin "Fly Dynamic Image Resizer" to return images from ACF but not having much luck. Can anyone provide any clue as to what I may be doing wrong? Thanks.
ACF variables:
<?php
$photo = get_field('photo', $post);
$fly_image = fly_get_attachment_image_src($photo, 'big_featured_works', true);
?>

HTML:
<img src="<?php echo $fly_image['src']; ?>"/>

A: $fly_image = fly_get_attachment_image_src(get_field('photo', $post), 'big_featured_works', true);

<img src="<?php echo $fly_image['src']; ?>"/>

then switch the return value of the custom field to image ID (from default "Image Array")

A: If your field is a repeater field you'll have to use get_sub_field, like this:
$image = get_sub_field('image');

fly_get_attachment_image_src($image, 'image-custom-size')['src'];

A: $image = fly_get_attachment_image_src( get_post_thumbnail_id(), 'home_page_square', array( 500, 500 ), true );
echo '';

(Reference)


text:
Q: Scale Factor on Error I was gathering some data from the particle data group website and for many results it gives a value, an uncertainty and then a scale factor for the uncertainty. For instance, at here, where it gives the mass for the singlet ground state of charmonium, it says the error contains a scale factor of 1.3. Could anyone help me understand what is meant by this?

A: The answer can be found in this paper. Quoting from it (page 10):

Our reasoning is as follows. The large value of the χ2 is likely to be due to
underestimation of errors in at least one of the experiments. Not knowing which of the
errors are underestimated, we assume they are all underestimated by the same factor S.
If we scale up all the input errors by this factor, the χ2 becomes N − 1, and of course the
output error δx scales up by the same factor.


text:
Q: View list of only current user objects, Django REST I have 2 views: /notes/ and /notes//
In note model in models.py I have owner variable, that stores owner's login.
Because I want to have many users, I don't want them to see other's notes, so I created the permission:
class IsOwner(permissions.BasePermission):
    def has_object_permission(self, request, view, obj):
        return obj.owner == request.user

I set this permission to NotesList(generics.ListCreateAPIView) and NotesDetail(generics.RetrieveUpdateDestroyAPIView). Now user can't view other's notes if he will go to /notes/<pk>/, but in /notes/ he can view the full list anyway.
So, how can I change it? I want to see in notes list only my notes.
I think the right way is to filter queryset = Snippet.objects.all().filter(owner=...) but can't think right away.

A: You are correct, you need to override the queryset in the list view. But you can't do that in the queryset attribute itself, because that is executed at process startup whereas you need access to data that is only available at request time. So you need to define the get_queryset method in that view:
def get_queryset(self, *args, **kwargs):
     return Snippet.objects.all().filter(owner=self.request.user)


text:
Q: why do i only see one tweet in the search from API Query? I'm using the following query:
https://twitter.com/search.json?callback=?&q=from:_adeel&count=5&include_entities=true&include_rts=true
and I would like to see the last 5 tweets from this user. You can see that the user has many more than 2 tweets yet the query only returns 2 tweets. I'm following the twitter search API and I fail to see what I'm doing wrong. I prefer to use the twitter search API because I want to perform the search on the client side without authentication and rate limits.
Do you see what I am doing wrong?

A: As indicated here in the documentation, the search API is an index of recent tweets, between 6-9 days old. It looks like the other tweets from the user you linked to are just outside this window.
So to summarize - you are not doing anything wrong. This is simply a limitation of the Twitter API.


text:
Q: How to access first element in array of nested objects? I have the following JSON data like so:
[{
  "target": {
    "source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0",
    "selector": {
      "conformsTo": "http://www.w3.org/TR/media-frags/",
      "value": "xywh=pixel:582.6087036132812,114.49275207519531,98.55072021484375,189.85508728027344",
      "type": "FragmentSelector"
    }
  },
  "id": "#423647a0-bd23-11ea-8727-73bc60edcd34",
  "body": [{
    "created": "2020-07-03T11:49:32.058Z",
    "purpose": "commenting",
    "type": "TextualBody",
    "creator": {
      "name": "testme",
      "id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
    },
    "value": "don't move me"
  }, {
    "creator": {
      "name": "testme",
      "id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
    },
    "value": "move",
    "type": "TextualBody",
    "purpose": "tagging",
    "created": "2020-07-03T11:49:30.850Z"
  }],
  "@context": "http://www.w3.org/ns/anno.jsonld",
  "type": "Annotation",
  "photoDocId": "92wNwz2aaqy7CWf3mGo1"
}, {
  "@context": "http://www.w3.org/ns/anno.jsonld",
  "body": [{
    "type": "TextualBody",
    "purpose": "commenting",
    "created": "2020-07-03T10:57:40.590Z",
    "value": "anyone ever climb this mountain top?",
    "creator": {
      "id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92",
      "name": "doss"
    }
  }, {
    "created": "2020-07-03T10:57:39.351Z",
    "value": "ridge",
    "type": "TextualBody",
    "creator": {
      "name": "doss",
      "id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
    },
    "purpose": "tagging"
  }, {
    "value": "i did in 2005",
    "purpose": "commenting",
    "type": "TextualBody",
    "creator": {
      "id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2",
      "name": "testme"
    },
    "created": "2020-07-03T10:59:45.318Z"
  }, {
    "type": "TextualBody",
    "purpose": "tagging",
    "creator": {
      "name": "testme",
      "id": "0qbvzjI3llhyIrKVO6PZxcZUSiI2"
    },
    "value": "testme",
    "created": "2020-07-03T10:59:43.966Z"
  }, {
    "value": "test",
    "type": "TextualBody",
    "purpose": "replying",
    "creator": {
      "name": "doss",
      "id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
    },
    "created": "2020-07-03T11:39:18.860Z"
  }],
  "type": "Annotation",
  "photoDocId": "92wNwz2aaqy7CWf3mGo1",
  "id": "#03a1f0e0-bd1c-11ea-a688-e1387cc6bed2",
  "target": {
    "selector": {
      "value": "xywh=pixel:247.82608032226562,73.91304016113281,233.33334350585938,240.57972717285156",
      "type": "FragmentSelector",
      "conformsTo": "http://www.w3.org/TR/media-frags/"
    },
    "source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0"
  }
}, {
  "body": [{
    "value": "test",
    "created": "2020-07-05T11:29:14.742Z",
    "purpose": "commenting",
    "creator": {
      "name": "doss",
      "id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
    },
    "type": "TextualBody"
  }, {
    "creator": {
      "name": "doss",
      "id": "K2Lb1R7owqR9BYmpJAJzrg6w1s92"
    },
    "created": "2020-07-05T11:29:13.584Z",
    "value": "test",
    "purpose": "tagging",
    "type": "TextualBody"
  }],
  "type": "Annotation",
  "target": {
    "selector": {
      "conformsTo": "http://www.w3.org/TR/media-frags/",
      "value": "xywh=pixel:395.65216064453125,413.0434875488281,142.02899169921875,131.88406372070312",
      "type": "FragmentSelector"
    },
    "source": "https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0"
  },
  "photoDocId": "92wNwz2aaqy7CWf3mGo1",
  "id": "#c1761960-beb2-11ea-888f-c3ab54e1f3a9",
  "@context": "http://www.w3.org/ns/anno.jsonld"
}]

This data is annotation data for an image.
What I am trying to do is loop through each object's body and only check the first element's (ie, body[0].creator.id) creator field. I want to check the id value in that creator field. If the id is the original author's id (lets use the id 0qbvzjI3llhyIrKVO6PZxcZUSiI2 for this example), then return console.log('original author').
I need help with accessing the above element. Any tips?
Side note: The reason for the above workflow is because I need to prevent another user from editing the author's original annotation. The original author will always be the first element in each body.

A: You could try this

const data = [
  {
    target: {
      source:
        'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0',
      selector: {
        conformsTo: 'http://www.w3.org/TR/media-frags/',
        value:
          'xywh=pixel:582.6087036132812,114.49275207519531,98.55072021484375,189.85508728027344',
        type: 'FragmentSelector'
      }
    },
    id: '#423647a0-bd23-11ea-8727-73bc60edcd34',
    body: [
      {
        created: '2020-07-03T11:49:32.058Z',
        purpose: 'commenting',
        type: 'TextualBody',
        creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
        value: "don't move me"
      },
      {
        creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
        value: 'move',
        type: 'TextualBody',
        purpose: 'tagging',
        created: '2020-07-03T11:49:30.850Z'
      }
    ],
    '@context': 'http://www.w3.org/ns/anno.jsonld',
    type: 'Annotation',
    photoDocId: '92wNwz2aaqy7CWf3mGo1'
  },
  {
    '@context': 'http://www.w3.org/ns/anno.jsonld',
    body: [
      {
        type: 'TextualBody',
        purpose: 'commenting',
        created: '2020-07-03T10:57:40.590Z',
        value: 'anyone ever climb this mountain top?',
        creator: { id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92', name: 'doss' }
      },
      {
        created: '2020-07-03T10:57:39.351Z',
        value: 'ridge',
        type: 'TextualBody',
        creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
        purpose: 'tagging'
      },
      {
        value: 'i did in 2005',
        purpose: 'commenting',
        type: 'TextualBody',
        creator: { id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2', name: 'testme' },
        created: '2020-07-03T10:59:45.318Z'
      },
      {
        type: 'TextualBody',
        purpose: 'tagging',
        creator: { name: 'testme', id: '0qbvzjI3llhyIrKVO6PZxcZUSiI2' },
        value: 'testme',
        created: '2020-07-03T10:59:43.966Z'
      },
      {
        value: 'test',
        type: 'TextualBody',
        purpose: 'replying',
        creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
        created: '2020-07-03T11:39:18.860Z'
      }
    ],
    type: 'Annotation',
    photoDocId: '92wNwz2aaqy7CWf3mGo1',
    id: '#03a1f0e0-bd1c-11ea-a688-e1387cc6bed2',
    target: {
      selector: {
        value:
          'xywh=pixel:247.82608032226562,73.91304016113281,233.33334350585938,240.57972717285156',
        type: 'FragmentSelector',
        conformsTo: 'http://www.w3.org/TR/media-frags/'
      },
      source:
        'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0'
    }
  },
  {
    body: [
      {
        value: 'test',
        created: '2020-07-05T11:29:14.742Z',
        purpose: 'commenting',
        creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
        type: 'TextualBody'
      },
      {
        creator: { name: 'doss', id: 'K2Lb1R7owqR9BYmpJAJzrg6w1s92' },
        created: '2020-07-05T11:29:13.584Z',
        value: 'test',
        purpose: 'tagging',
        type: 'TextualBody'
      }
    ],
    type: 'Annotation',
    target: {
      selector: {
        conformsTo: 'http://www.w3.org/TR/media-frags/',
        value:
          'xywh=pixel:395.65216064453125,413.0434875488281,142.02899169921875,131.88406372070312',
        type: 'FragmentSelector'
      },
      source:
        'https://firebasestorage.googleapis.com/v0/b/vue-photoapp-api.appspot.com/o/photos%2Fmountains-hero.jpg?alt=media&token=fbe93188-d13d-4a7f-a472-4a529aa565a0'
    },
    photoDocId: '92wNwz2aaqy7CWf3mGo1',
    id: '#c1761960-beb2-11ea-888f-c3ab54e1f3a9',
    '@context': 'http://www.w3.org/ns/anno.jsonld'
  }
]

data.forEach(d => {
  if (d.body[0].creator.id === '0qbvzjI3llhyIrKVO6PZxcZUSiI2') {
    console.log('original author')
  }
})


text:
Q: 401 Unauthorized Access Error with SharePoint NTLM Authentication flutter var client = NTLMClient(
workstation: "",
domain: 'domain',
username: "username",
password: 'password',
);
client.get(Uri.parse('https://xxxxxxxx.signin.no/xxxxx/Delte%20dokumenter/filename.pdf'),)
.then((res) {
401 Unauthorized});


text:
Q: How to return everything in an output except something specific Is there any way that i can get an output to only display the IP addresses that are not the one the user input at the start of the script? The start of my code is below.
def get_asset_group_criteria(group_number):
    asset_group_number = str(group_number)
    asset_group_path = "/api/3/asset_groups/" + asset_group_number + "/search_criteria"
    url5 = server + asset_group_path
    response = requests.request("GET", url5, headers=headers, verify=False)
    data = response.json()
    print(data)

x = input("What is the asset group id?: ")
get_asset_group_criteria(x)

The output of the print command returns the following:
{'match': 'any', 'filters': [{'field': 'ip-address', 'operator': 'is', 'value': '192.168.1.0'}, {'field': 'ip-address', 'operator': 'is', 'value': '192.168.1.1'}]}

To further elaborate on what i am trying to do based on this output:
I would like for the script to ask the user what IP address will not be included in the output. Then the script will go through and respond with everything that isn't that IP. Once this is done i would like to use PUT to update the search criteria in the program im using this for.

A:
Is there any way that i can get an output to only display the IP addresses that are not the one the user input at the start of the script?

Yes, all you need is to filter the array of data['filters'] from the response, excluding a desired IP. Check the snippet below:
def get_asset_group_criteria(group_number):
    asset_group_number = str(group_number)
    asset_group_path = "/api/3/asset_groups/" + asset_group_number + "/search_criteria"
    url5 = server + asset_group_path
    response = requests.request("GET", url5, headers=headers, verify=False)
    data = response.json()
    return data

def put_asset_group_criteria(group_number, data):
    asset_group_number = str(group_number)
    asset_group_path = "/api/3/asset_groups/" + asset_group_number + "/search_criteria"
    url5 = server + asset_group_path
    response = requests.request("PUT", url5, json=data, headers=headers, verify=False)
    return response

x = input("What is the asset group id?: ")
ip = input("What IP should not be included?: ")
data = get_asset_group_criteria(x)
data['filters'] = [filter for filter in data['filters'] if filter['value'] != exclude_ip]
print(data)
resp = put_asset_group_criteria(x, data)
print(resp)

What I've done is to update the array of data['filters'] by generating a new one, copying every element except the ones with value equal to exclude_ip argument.
The output should be: {'match': 'any', 'filters': [{'field': 'ip-address', 'operator': 'is', 'value': '192.168.1.0'}]} if 192.168.1.1 is informed.
The PUT request is very similar to the GET using your current interface, all you need to change is the name of the method, from "GET" to "PUT", and pass a json argument to the request, containing your data. Check the docs.


text:
Q: Как правильно примонтировать диск данными в /home У меня вот возникла такая проблема... Установил себе на ноут Ubuntu 12.04.1. Винт разделен на 3 раздела (swap-sda1, /-sda2 и sda3). Так вот, хочу щас раздел sda3 смонтировать в /home, чтоб не терять пользовательские настройки после переустановки системы. Возник вопрос, не сломаю ли я систему прописав монтирование этого раздела в /etc/fstab. И не потеряю ли пользовательские данные после первой же перегрузки системы? Если так, то как правильно мне все сделать?
A: Если я правильно понял, то /home сейчас в /dev/sda2 и планируется разместить его в /dev/sda3. Тогда сперва нужно данные переместить в /dev/sda3:mkdir /mnt/homemount /dev/sda3 /mnt/home\# далее переместить любым доступным методом все файлы (не забыть про скрытые) из /home в /mnt/homeumount /dev/sda3правка /etc/fstab\# никаких ребутовmount -a\# всё, теперь df -h и видим что надо
A: Я этим мануалом пользовался. Все получилось.Move /home to it's own partition.
A: Не стоит монтировать разделы в fstab по конкретному имени девайса (/dev/sda3), монтируйте разделы по UUID, его можно выяснить командой sudo blkid.Пример вывода blkid:/dev/sda1: UUID="4b9fb3d5-f1cd-47b8-af0c-3b14fd6ef4ad" TYPE="ext4"/dev/sda2: UUID="A4E0DDE0E0DDB8AE" TYPE="ntfs"/dev/sda4: UUID="d83a7677-8679-49e5-a4cb-4ff63801505d" TYPE="ext4"Далее строка из /etc/fstab:UUID=d83a7677-8679-49e5-a4cb-4ff63801505d /home ext4 defaults 0 0


text:
Q: Error running multiple commands using here document in bash script I'm trying to execute the following set of commands in 3 remote servers using arrays, using Here Document, but getting an error
code -
ssh -oPasswordAuthentication=no $remoteUser@${SERVER[i]} <<-END_TEXT
VALUE=`cat /home/cognos/cognos/c8/configuration/cogstartup.xml | grep -i xsd:long | head -1 | cut -d">" -f2 | sed 's/[:/<|crn:value]*//g'`
VALUE_BACKUP=$VALUE
........................ (many more lines of code)
RESULT1=`perl -e '@stats = stat("/home/cognos/cognos/c8/configuration/signkeypair"); print ((time - $stats[9]) < '$VALUE');'`

END_TEXT

And the error:
**error -**
syntax error at -e line 1, near "< )"
Execution of -e aborted due to compilation errors.
syntax error at -e line 1, near "< )"
Execution of -e aborted due to compilation errors.
syntax error at -e line 1, near "< )"
Execution of -e aborted due to compilation errors.

ps- using scp to copy commands to remote server and then running them using ssh is not a solution I'm looking for.

A: Look into the whole here document and search for -e.
Edit:
Enclose END_TEXT in single quotes, like this:
ssh ... <<-'END_TEXT'
...
END_TEXT

This will prevent substitution of $VALUE with an empty string, before it is available on the remote server.


text:
Q: How to add additional handlings to Vpn disconnection in Android? I have a custom implementation of VpnService, which needs to perform some additional cleanup on disconnection. Everything works fine when I am stoping VpnService from my application using service bindings, but I need to perform that cleanup when client is disconnecting from the Vpn using system dialog.
So, how can I catch the disconnection and add some handlings to that?
Get VPN Connection status on Android - this could be the solution, but it's not working on android 4+.
From logs point of view there are only two entries:
03-20 03:27:09.478: INFO/Vpn(504): Switched from org.my.package to [Legacy VPN]
03-20 03:27:09.478: DEBUG/Vpn(504): setting state=IDLE, reason=prepare

A: This happens if we use a custom IBinder defined via AIDL, which I return from onBind().
VpnService implements onBind() too and returns an instance of VpnService.Callback private-class.
Solution:
@Override
public IBinder onBind(Intent intent) {
    String action = intent != null ? intent.getAction() : null;
    if (action != null && action.equals(VpnService.SERVICE_INTERFACE)) {
        return super.onBind(intent);
    }

    return yourBinder;
}

Note that above works as long as you never set VpnService.SERVICE_INTERFACE as action manually.
That action should only be set by Android's internal-logic (automatically, never by our code manually).

A: I just ran into the same issue. VpnService.onRevoke() is not called.
It turns out this happens because I use a custom IBinder defined via AIDL wich I return from onBind(). VpnService implements onBind() too and returns an instance of VpnService.Callback.
Which is implemented this way:
private class Callback extends Binder {
    @Override
    protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) {
        if (code == IBinder.LAST_CALL_TRANSACTION) {
            onRevoke();
            return true;
        }
        return false;
    }
}

VpnService.Callback does not use AIDL and just checks if the function code IBinder.LAST_CALL_TRANSACTION was sent. If so it executes onRevoke().
I integrated this code fragment in my custom IBinder implementation and now I receive the onRevoke() message. See the following example:
private final IBinder mBinder = new ServiceBinder();
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}
public final class ServiceBinder extends ICustomVpnService.Stub
{
    ... implement methods defined in ICustomVpnService.Stub ....

    /**
     * Intercept remote method calls and check for "onRevoke" code which
     * is represented by IBinder.LAST_CALL_TRANSACTION. If onRevoke message
     * was received, call onRevoke() otherwise delegate to super implementation.
     */
    @Override
    public boolean onTransact(int code, Parcel data, Parcel reply, int flags)
    throws RemoteException
    {
        // see Implementation of android.net.VpnService.Callback.onTransact()
        if ( code == IBinder.LAST_CALL_TRANSACTION )
        {
            onRevoke();
            return true;
        }
        return super.onTransact( code, data, reply, flags );
    }

    private void onRevoke()
    {
        // shutdown VpnService, e.g. call VpnService.stopSelf()
    }
}

How did I figure it out? I searched the android source code for where onRevoke() is actually invoked. For that I find grepcode (android) pretty helpful. I often read the android source to understand how things work.


text:
Q: Authenticate wp site on LAN to access on cloud site I have a WordPress built intranet on my company LAN, we use AD to authenticate staff users on this site using Active Directory Integration plugin.
Now we are migrating this wp intranet site unto AWS where it is far from the reach of our domain controller to keep authenticating with AD.
Getting this configured with AWS will require so much process and approval which will kill our project timelines.
How can we authenticate locally and redirect login into the new site located on AWS?