text:
Q: WPF bottun rounded corner So i have this "window" (not a Window but Grid):

Code:
<Grid Name="gridDeleteAllWindows">
    <Grid.RowDefinitions>
        <RowDefinition Height="110"/>
        <RowDefinition Height="40"/>
    </Grid.RowDefinitions>
    <Grid Grid.Row="0">
        <StackPanel Orientation="Vertical" VerticalAlignment="Center" Margin="0,0,0,0">
            <Label Content="Delete All Files"
                       FontSize="20"
                       HorizontalAlignment="Center"
                       FontWeight="Bold"
                       Margin="0,0,0,0"/>
            <Label Content="Are you sure you want to remove"
                       HorizontalAlignment="Center"
                       Margin="0,0,0,0"/>
            <Label Content="all the files ?"
                       HorizontalAlignment="Center"
                       Margin="0,0,0,0"/>
        </StackPanel>
    </Grid>
    <Grid Grid.Row="1">
        <Border BorderThickness="0,1,0,0" BorderBrush="#55B3B3B6">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="125"/>
                    <ColumnDefinition Width="125"/>
                </Grid.ColumnDefinitions>
                <Border BorderBrush="#55B3B3B6" BorderThickness="0,0,1,0" Grid.Column="0">
                    <Grid>
                        <Button Name="btnDeleteAllFilesYes"
                                Content="Yes"
                                FontSize="16"
                                Style="{StaticResource ButtonDefaultStyle}"
                                VerticalAlignment="Stretch"
                                HorizontalAlignment="Stretch"
                                Click="btnDeleteAllFilesYes_Click"
                                Margin="0,0,0,0"/>
                    </Grid>
                </Border>
                <Border BorderBrush="#55B3B3B6" BorderThickness="0,0,1,0" Grid.Column="1">
                    <Grid>
                        <Button Name="btnDeleteAllFilesNo"
                                Content="No"
                                FontSize="16"
                                Background="Transparent"
                                Style="{StaticResource ButtonDefaultStyle}"
                                VerticalAlignment="Stretch"
                                HorizontalAlignment="Stretch"
                                Click="btnDeleteAllFilesNo_Click"
                                Margin="0,0,0,0"/>
                    </Grid>
                </Border>
            </Grid>
        </Border>
    </Grid>
</Grid>

Style:
<Style x:Key="ButtonDefaultStyle" TargetType="{x:Type Button}" BasedOn="{StaticResource MetroFlatButton}" >
    <Style.Triggers>
        <Trigger Property="IsMouseOver" Value="False">
            <Setter Property="Background" Value="#FF103766"/>
            <Setter Property="Foreground" Value="Gainsboro"/>
        </Trigger>

        <Trigger Property="IsMouseOver" Value="True">
            <Setter Property="Background" Value="Gray"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>

        <Trigger Property="IsEnabled" Value="False">
            <Setter Property="Background" Value="#FF6899D3"/>
            <Setter Property="Foreground" Value="White"/>
        </Trigger>
    </Style.Triggers>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border TextBlock.Foreground="{TemplateBinding Foreground}"
                        x:Name="Border"
                        CornerRadius="0"
                        BorderBrush="Transparent"
                        Background="{TemplateBinding Background}"
                        BorderThickness="1">
                    <VisualStateManager.VisualStateGroups>
                        <VisualStateGroup x:Name="CommonStates">
                            <VisualStateGroup.Transitions>
                                <VisualTransition GeneratedDuration="0:0:0.5" />
                                <VisualTransition GeneratedDuration="0" To="Pressed" />
                            </VisualStateGroup.Transitions>
                            <VisualState x:Name="Normal" />
                            <VisualState x:Name="MouseOver">
                            </VisualState>
                            <VisualState x:Name="Pressed">
                            </VisualState>
                            <VisualState x:Name="Disabled">
                            </VisualState>
                        </VisualStateGroup>
                    </VisualStateManager.VisualStateGroups>
                    <ContentPresenter Margin="2"
                                      HorizontalAlignment="Center"
                                      VerticalAlignment="Center"
                                      RecognizesAccessKey="True" />
                </Border>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

And i want just to add another color into my Button while MouseEnter so i add this Trigger:
<Trigger Property="IsMouseOver" Value="True">
    <Setter Property="Background" Value="Gray"/>
    <Setter Property="Foreground" Value="White"/>
</Trigger>

Result:

And as you can see that my rounded corner is now missing so i just need your help to fix it.


text:
Q: Suggestion:Need a carousel slider in wordpress[images from api] Consider a table containing image URLs and some count for each image
so my API is returning top 5(limit can be changed) image links according to count in descending order
Here is sample images table:

this is API response(the image will become suffix www.hostname.com/IMAGE_ID)

Now I want to show these images as a carousel in WordPress.
SO ANY SUGGESTION FOR PLUGINS AVAILABLE IN WORDPRESS?

redpajama_set_name: RedPajamaStackExchange


text:
Q: ExtJS image viewer I have list of images in json format, and want to make an image gallery, but not with full features. Basically all I want is to display 4 pictures next to each other with 2 rows. And when the user clicks the thumbnail sees the large picture. How would I go about doing this.

A: If you're wanting to create an image gallery then everything you need is here:
http://dev.sencha.com/deploy/ext-4.0.0/examples/view/data-view.html


text:
Q: Can a compiler inline a virtual function if I use a pointer in a clear situation? I've already read Are inline virtual functions really a non-sense?. But I still have some doubts and found no answer there.
They say that if situation isn't ambiguous, compiler should inline the virtual function.
However:

This can happen only when the compiler has an actual object rather than a pointer or reference to an object.

So what if I have a B class derived from an A one (which contains a virtual void doSth() function) and I use the B* pointer, not the A*:
B* b = new B;

b->doSth();

*

*Suppose that the B hasn't any child classes. It's rather obvious (on the compile time) what function should be called. So it's possible to be inlined. Is it in fact?

*Suppose that the B has some child classes but these classes haven't its own doSth() function. So compiler should "know" that the only function to call is B::doSth(). I guess it doesn't inline though?

A: It doesn't matter whether B has any derived classes. In that situation b points to a B object so the compiler can inline the call.
And surely any decent modern compiler can and will do that in your situation. If you don't use pointers it becomes a whole lot easier. It's not really an "optimization" then. The fact that you can omit a virtual call then becomes obvious by only looking at the AST node at the left side of the .-operator. But if you use pointers, you need to track the dynamic type of the pointee. But modern compilers are capable of that.
EDIT: Some experiment is in order.
// main1.cpp
struct A {
  virtual void f();
};

struct B : A {
  virtual void f();
};

void g() {
  A *a = new A;
  a->f();

  a = new B;
  a->f();
}

// clang -O2 -S -emit-llvm -o - main1.cpp | c++filt
// ...
define void @g()() {
  %1 = tail call noalias i8* @operator new(unsigned int)(i32 4)
  %2 = bitcast i8* %1 to %struct.A*
  %3 = bitcast i8* %1 to i32 (...)***
  store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @vtable for A, i32 0, i32 2) to i32 (...)**), i32 (...)*** %3, align 4
  tail call void @A::f()(%struct.A* %2)
  %4 = tail call noalias i8* @operator new(unsigned int)(i32 4)
  %5 = bitcast i8* %4 to i32 (...)***
  store i32 (...)** bitcast (i8** getelementptr inbounds ([3 x i8*]* @vtable for B, i32 0, i32 2) to i32 (...)**), i32 (...)*** %5, align 4
  %tmp = bitcast i8* %4 to %struct.B*
  tail call void @B::f()(%struct.B* %tmp)
  ret void
}
// ...

As can be seen, clang does direct calls to f, both when a points to a A and when it points to a B. GCC does that too.

A: A virtual member function can be inlined when the vtable is not dereferenced for the call. This can be accomplished by making an explicitly scoped call to the member function.
class A
{
protected:

    int     a;
public:
    inline virtual void Func()
    {
        a = 0;
    }
};

class B : public A
{
public:
    inline virtual void Func()
    {
        a = 1;
    }
};

B   *obj = new B();

obj->Func();    //  Calls B::Func() through vtable;
obj->A::Func(); //  Inlines calls to A::Func();
obj->B::Func(); //  Inlines calls to B::Func();


text:
Q: Getting Function Key in ARM Template - Fails Intermittently Hi I am getting the Function Key and Trigger Url as Output in our Arm Template, using the following code.
>     "outputs": {
>     "Key": {
>       "type": "string",
>       "value": "[listsecrets(resourceId('Microsoft.Web/sites/functions',
> variables('funcName'),
> parameters('NameOfService')),'2015-08-01').key]"
>     },
>     "functionUrl": {
>       "type": "string",
>       "value": "[listsecrets(resourceId('Microsoft.Web/sites/functions',
> variables('funcName'),
> parameters('NameOfService')),'2015-08-01').trigger_url]"
>     }   }

We have the 'AzureWebJobsSecretStorageType' set to 'Files' in the App Settings as it doesn't work without it in Functions v2, when we execute the ARM template, it works sometimes but other times it throws the following error, not sure what's it's problem, the ARM template is valid as it does work and I can see the Function is successfully deployed in the Azure portal as well, so not sure why exactly it fails, any clues?

[error]BadRequest: {   "error": {
      "code": "BadRequest",
      "message": "System.FormatException: unable to decrypt CfDJ8AAAAAAAAAAAAAAAAAAAAAB93sc99M4b_klhBWrLMfQYRpSN9, the key is either invalid or malformed --->
  System.Security.Cryptography.CryptographicException: The payload was
  invalid.\r\n   at
  Microsoft.AspNetCore.DataProtection.Cng.CbcAuthenticatedEncryptor.DecryptImpl(Byte*
  pbCiphertext, UInt32 cbCiphertext, Byte*
  pbAdditionalAuthenticatedData, UInt32
  cbAdditionalAuthenticatedData)\r\n   at
  Microsoft.AspNetCore.DataProtection.Cng.Internal.CngAuthenticatedEncryptorBase.Decrypt(ArraySegment1
  ciphertext, ArraySegment1 additionalAuthenticatedData)\r\n   at
  Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.UnprotectCore(Byte[]
  protectedData, Boolean allowOperationsOnRevokedKeys, UnprotectStatus&
  status)\r\n   at
  Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.DangerousUnprotect(Byte[]
  protectedData, Boolean ignoreRevocationErrors, Boolean&
  requiresMigration, Boolean& wasRevoked)\r\n   at
  Microsoft.AspNetCore.DataProtection.KeyManagement.KeyRingBasedDataProtector.Unprotect(Byte[]
  protectedData)\r\n   at
  Microsoft.AspNetCore.DataProtection.DataProtectionCommonExtensions.Unprotect(IDataProtector
  protector, String protectedData)\r\n   at
  Kudu.Core.Infrastructure.SecurityUtility.DecryptSecretString(String
  content) in C:\Kudu
  Files\Private\src\master\Kudu.Core\Infrastructure\SecurityUtility.cs:line
  40\r\n   --- End of inner exception stack trace ---\r\n   at
  Kudu.Core.Infrastructure.SecurityUtility.DecryptSecretString(String
  content) in C:\Kudu
  Files\Private\src\master\Kudu.Core\Infrastructure\SecurityUtility.cs:line
  45\r\n   at
  Kudu.Core.Functions.FunctionManager.d__91.MoveNext()
  in C:\\Kudu
  Files\\Private\\src\\master\\Kudu.Core\\Functions\\FunctionManager.cs:line
  203\r\n--- End of stack trace from previous location where exception
  was thrown ---\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  Kudu.Core.Functions.FunctionManager.<GetFunctionSecretsAsync>d__12.MoveNext()
  in C:\\Kudu
  Files\\Private\\src\\master\\Kudu.Core\\Functions\\FunctionManager.cs:line
  220\r\n--- End of stack trace from previous location where exception
  was thrown ---\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  Kudu.Services.Functions.FunctionController.<GetSecrets>d__12.MoveNext()
  in C:\\Kudu
  Files\\Private\\src\\master\\Kudu.Services\\Functions\\FunctionController.cs:line
  141\r\n--- End of stack trace from previous location where exception
  was thrown ---\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__31.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Controllers.ApiControllerActionInvoker.d__0.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Web.Http.Filters.ActionFilterAttribute.d__5.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Filters.ActionFilterAttribute.d__0.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Controllers.ActionFilterResult.d__2.MoveNext()\r\n---
  End of stack trace from previous location where exception was thrown
  ---\r\n   at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
  task)\r\n   at
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
  task)\r\n   at
  System.Web.Http.Controllers.ExceptionFilterResult.d__0.MoveNext()"
  }

A: I Found what was causing this, it was happening during fresh deployments of Function only i.e. when I deleted the function app and then tried the deployment I hit this issue, reason was that I was just deleting the Function App not the Storage Account related to it, so the old storage account was keeping some information about the deleted Function App (I assume) and things got messy, the moment I started deleting the storage account with the Function App the issue went away. Just to add that Storage account is dedicated to this Function App and isn't used by anything else.

A: Based on your error message, I assume the function key looks like CfDJ8AAAAAAAAAAAAAAAAAAAAAB93sc99M4b_klhBWrLMfQYRpSN9. However, this key format doesn't make sense. I've got into the same situation a few times. The key looked exactly like yours.
In that case, the key itself is malformed. It sometimes happens. Therefore the only solution for this is to renew the key. Then it'll be looking a normal base-64 encoded one.


text:
Q: Doesn't htmlspecialchars() protect against javascript when calling in jquery .html() in result through ajax? I wrote a php and jquery-ajax script that works good. But the following scripts work slow and I found that this type of script is vulnerable to XSS attack, I found something regarding it in this link's first answer please see the first answer. Here is my jquery code:

Here is the view_result.php script:
<?php
 function html_converter($val)
  {
    $turned = array('`<b>','`</b>','`<mark>','`</mark>');
    $turn_back = array('','','','');
    $val = str_replace( $turned, $turn_back, $val );
    $val = preg_replace('/(?:(?:\r\n|\r|\n)\s*){2}/s', "\n\n", $val);
    return $val;
  }
  $question = $_POST['question'];
  $question = htmlspecialchars($question, ENT_QUOTES, 'UTF-8');
  echo html_converter($question);
?>

How can I write the whole script only in jquery function without using ajax. Is this script safe?

A: I think you are asking how to simply avoid XSS attacks client-side.  I think you are currently using PHP as a way to "clean" your question data coming from the user.  If this is not what you are asking, please clarify your question.
If you want to use text from a user, don't use .html() to set it, simply use .text():
$('.question').keyup(function(){
  var question = document.forms['myForm']['question'].value;
  $('#show_typing_question').text(question);
});

Then, no escaping is necessary since you're using text in a text context.


text:
Q: Rails - where with custom model method condition i have a custom method on my model and i want to use it in a where condition, i already accomplish this for sorting with custom methods, but can't find a way for search with custom conditions.
Now i have this, in my model
attr_accessible :end, :start
def time_left
  self.end.to_i - Time.now.utc.to_i - Time.now.utc_offset
end
def time_left_to_start
  self.start.to_i - Time.now.utc.to_i - Time.now.utc_offset
end
def status
  if self.time_left_to_start > 0
    1 #proximamente
  elsif self.time_left_to_start < 0 and self.time_left > 0
    2 #funcionando
  else
    3 #finalizado
  end
end

and for my controller
def index
  @next_events = Event.all.sort_by(&:time_left).reverse!.reject { |e| e.status != 1 }.take(5)
end

i know i can write the entire condition on the where method, but my idea is don't repeat my self and avoid to loop for all the events to remove each one where the status isn't 1, i just need the last 5 each time and looks to me really bad idea ask to the db for all the records each time.
Thanks in advance, regards!

A: After refactoring my code i came across with this
  def time_left
    (self.end - Time.now).to_i
  end
  def time_left_to_start
    (self.start - Time.now).to_i
  end

  def status
    if self.start  < Time.now and self.end > Time.now
      1 #En curso
    elsif self.start  > Time.now
      2 #Proximamente
    else
      3 #Finalizado
    end
  end

  def self.status(status)
    if status == 1 #eventos en curso
      where("(events.start < ?) AND (events.end > ?)", Time.now, Time.now)
    elsif status == 2 #proximos eventos
      where("events.start > ?", Time.now)
    elsif status == 3 #eventos finalizados
      where("events.end < ?", Time.now)
    elsif status == 4 #eventos proximos y en curso
      where("events.end > ?", Time.now)
    end
  end

and making queries like this
  @next_events = Event.status(2).order('events.start DESC').reject { |e| e.time_left_to_start > 12.hour }.take(18)

Thanks for your time, regards!


text:
Q: AngularJS ui-router/session error handling I have a single page application utilizing angular and ui-router for our community users on our community site. All works great until their session is invalidated (they logout) or it times out. At which point the remoting function calls will fail (with errors like code 500 Visualforce Remoting Exception: Page not allowed for the profile) which I can likely handle by checking for the statusCode of 500 and redirect to login screen. The bigger concern is how to handle the routing issues. If their session is no longer valid and you hit a route or try to load a view (to show a popup as an example) from the static resource which it can't access without a session (receive a Error: [$compile:tpload] error). This one I think can only be handled with some deep diving into the angular code. I was wondering if anyone had recommendations on handling session timeouts or logouts since unless someone has the JS console open, they wouldn't understand the issue. Thanks!

A: I had a template I was displaying when there was an error on the remoting calls. I moved that to text/ng-template so it would always be accessible and then detected the statusCode 500 or 402 to display the popup. For the ui-router template error I used a generic error handler to capture the failed template load to display. Might help someone in the future
.run(function($state) {
    $state.defaultErrorHandler(function(error) {
        // make noise
        alert('failed on route');
    });
})


text:
Q: Registering error message from backend to frontend with Axios, but in the same time the success message occurs coming with a short question.
I've been trying to retrieve the error from the backend by fetching the API data through Axios GET method to display on the frontend, that the email has already been registered, and it works, but the issue is the success message is also showing up. Therefore I'm looking for other solution to display the error when the error occurs, and the success when the form is submitted correctly.
For backend I'm using PHP, and for frontend I'm using ReactJS, with Axios to be able to connect the frontend to backend.
I tried with .then(successMessage) to reset with an empty string, and .catch(errorMessage) to display the error, but even after completing the form correctly, the error keeps showing up in that way. The code and the input can be seen down below.
const handleSubmitForm = (event) => {
    event.preventDefault();

    if (validationForm()) {

      const object = {
        full_name: full_name,
        email: email,
        type_of_inquiry: type_of_inquiry,
        inquiry_description: inquiry_description,
      }

        axios.post("http://localhost/bachelor_exam/api-contact.php", object)
        .then(setSuccessMessage("Your contact details has been registered, we'll get in touch as fast as you say fish! ;D"))
        .catch(setErrorMessage(""));

        axios.get("http://localhost/bachelor_exam/api-contact.php", object)
        .catch(setErrorMessage("The email has already been registered!"))

  }
}

The input
Thank you for your time!


text:
Q: Can atoms have nonzero dipole moments? Let's make the question easier by considering two-level atoms(with spin states, i.e. spin up $|\uparrow\rangle$ and spin down $|\downarrow\rangle$). An article I recently read claims that atoms do not have dipole moments when they are in energy eigenstates (i.e. when you put it into a magnetic field in z direction).
I was thinking if it's an eigenstate, since the spin cannot be pointing in z direction (remember it's actually pointing in a cone area), how could it not have a dipole moment?

A: The claim you read is probably

Electronic eigenstates of an atom, or of an inversion-symmetric molecule, always have vanishing electronic dipole moment about the atomic nucleus or the molecular inversion centre.

This is because if you invert the system you must be left with exactly the same eigenstates, but the electric dipole, being a vector quantity, must switch sign.

Magnetic dipole moments, on the other hand, can indeed be nonzero. This is because magnetic dipoles are pseudovector quantities and do not change sign upon inversion. Thus an atom like boron, which has five electrons and therefore a single 2p electron and orbital angular momentum $l=1$, can have a nonvanishing magnetic dipole moment (which will be proportional to the angular momentum of the p electron, so it obeys the standard QM restrictions: e.g. it can only have well-defined components along only one axis at a time).
Electron spin is also a pseudovector quantity, and so atoms and molecules can have spin-induced magnetic dipole moments without violating inversion symmetry.


text:
Q: Spark: Convert/concat an WrappedArray of Row to a String I have a Spark dataframe with column that has array<struct<_1:long,_2:string>> datatype and following sample data:
WrappedArray([Value,Title1], [Value,Title2], [Value,Title3])

I want to convert this column from WrappedArray to a single String
Here is the desired output:
Value+Title1,Value+Title2,Value+Title3

I tried the following udf passing that column of the dataframe:
val f = (x:Seq[Row]) => x.mkString(",")
sqlContext.udf.register("f", f)

But the result is [Value,Title1],[Value,Title2],[Value,Title3]

A: try this:
val f = (x:Seq[Row]) => x.map(row => "%s+%s".format(row.getString(0),
row.getString(1))).mkString(",")


text:
Q: Access higher TTYs and the role of getty I have a few dark areas when trying to understands TTYs.

*

*On my system, I have /dev/tty[1-63]. Is udev creating these character devices? And how can I access them (like tty2 can be accessed with Ctrl+Alt+F2)? How can I access /dev/tty40 for example?

*As I understand, when I access /dev/tty1, agetty is called, which then calls login. What really is the role of agetty outside of calling login?

A: These are virtual consoles, known in Linux as virtual terminals (VT). There is a single hardware console (a single screen and a single keyboard), but Linux pretends that there are multiple ones (as many as 63). At a given point in time, a single VT is active; keyboard input is routed to that console and the screen shows what that console displays.
You can use the command chvt to switch between VT (you need to have direct access to the current virtual console, which you won't have if logged remotely or running under X). You can also use keybindings set with the keymap loaded by loadkeys or by the X server. By default, outside X, Alt+Fn switches to console number n and Alt+Shift+Fn switches to console number n+12; Alt+Left and Alt+Right switch to the previous/next console.
A console needs to be allocated in order to switch to it. You can use openvt to allocate a console (this requires root) and deallocvt to deallocate one.
The program getty is not directly related to virtual consoles, in particular it has nothing to do with VT allocation. The role of getty is to prepare the console (set up serial port parameters, possibly blank the screen, display a welcome message, etc.) and call login, then wait for the login session to terminate and repeat. In a nutshell, the role of getty is to call login in a loop.
You don't have to run getty to use a console. For example, you can start any program on a console with openvt. You can start an X server on a new console with startx.


text:
Q: AJAX requests failing for ASP.NET Core app in Amazon Linux 2 vs Amazon Linux 1 I have an ASP.NET Core v.3.0 web application hosted in Amazon AWS Elastic Beanstalk using Docker. The application works fine in Docker running 64bit Amazon Linux (v2.16.11). When I update to Docker running 64bit Amazon Linux 2 (v3.4.12) the requests work fine except for AJAX requests which fail with Status Code Error 400 "Bad request". Nothing else has changed in the source code, dockerfile etc. Only the Linux version has changed from Amazon Linux to Amazon Linux 2. Does anybody have an idea what is different between Amazon Linux 1 and Amazon Linux 2 that may be the cause leading to AJAX requests failing?
More info:

*

*I cannot replicate this error with the official ASP.NET core 3.1 examples. I have not updated my application to v3.1, I will do it soon and I will update this question.

*The relevant action inside the controller does not return the partial view in Amazon Linux 2. The controller provides a log just before returning the partial view and this is not triggered in Amazon Linux 2.

*The nginx access.log file shows the following response of the load balancer:

Amazon Linux 1:
{IP} - - [10/Apr/2022:07:36:01 +0000] "POST {url} HTTP/1.1" 200 3882 "{url2}" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36" "{IP2}"
Amazon Linux 2:
{IP} - - [10/Apr/2022:07:00:14 +0000] "POST {url} HTTP/1.1" 400 0 "{url2}" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36" "{IP2}"

*The call is made with jQuery 3.4.1:
var $form = $("#inputForm");
if ($form.length <= 0) return;
var data = $form.serialize();
$.ajax({
    url: "...",
    type: "POST",
    data: data,
    error: function (jqXHR, textStatus, errorThrown) {
        alert("There was an error when loading the results (error type = " + errorThrown + ").");
    },
    success: function (result) {
        $("#calculationTarget").html(result)
    });

A: The issue is no longer present if the project is updated from ASP.NET Core 3.0 to ASP.NET Core 3.1.

A: There is a very simple fix, which is updating to ASP.NET Core 3.1.
In this version, the issue that you have having is fixed.

See the steps below for updating.

*

*If you have a global.json file to target a specific .NET Core SDK version, update the version property.
{
  "sdk": {
    "version": "3.1.101"
  }
}

*Update the TFM to netcoreapp3.1, as described below.
<Project Sdk="Microsoft.NET.Sdk.Web">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
  </PropertyGroup>
</Project>

*You need to update the package references. To do this, update every Microsoft.AspNetCore.* (* meaning wildcard) to 3.1.0 (or any version later).

*If you are using Docker (which I think you are), then you need to use an ASP.NET Core 3.1 base image. See an example below.
$ docker pull mcr.microsoft.com/dotnet/aspnet:3.1

For extra steps and information, see the official guide from migrating to ASP.NET Core 3.1.

In summary, upgrading your current application to ASP.NET Core 3.1 should fix your issue.


text:
Q: How can I insert a ">" in a quoted knockout area in a MVC .cshtml file? I have the following:
<select id="countries"
   data-bind='
      options: selectedContinent() ? countries : null,
      optionsValue : "Id",
      optionsText: "Name",
      optionsCaption: "[Please select a country]",
      value: selectedCountry,
      visible: (countries() && countries().length > 0)'>
</select>

Unfortunately this shows an error in the IDE that's caused by the ">" on the last line of the data-bind.  Is there a way that I can escape this so it will not show an error?

A: Have you tried putting the data-bind attribute in double quotes, and the values inside the attribute in single quotes? You might also need to have the first value of it starting on the same line too:
<select id="countries"
   data-bind="options: selectedContinent() ? countries : null,
      optionsValue : 'Id',
      optionsText: 'Name',
      optionsCaption: '[Please select a country]',
      value: selectedCountry,
      visible: (countries() && countries().length > 0)">
</select>


text:
Q: Power-flickering Apple Cinema Display in Ubuntu 12 Web search hasn't turned up anything diagnostic for this.
User has a 2008-era 30" Apple Cinema Display with a newer workstation running Ubuntu 12.04.  Video card is GeForce GTX 550 Ti.  Keyboard and mouse are Apple, plugged into the USB2 port on the back of the monitor.
Problem:  the system will sometimes power down the screen randomly.  Worse, when the system sleeps overnight, the monitor can't start properly the next morning - the keyboard or mouse or power button on the Cinema Display all wake up the monitor into a "flashing" state, where it turns off and on again about once every half-second or so.  Temporary fix:  unplugging the power brick on the monitor for a second or two will straighten it out - but we have to do it fast, or the box no longer recognizes the keyboard or mouse.  If we're fast enough, it will pick up the mouse and keyboard again after about 10 seconds.
Up to this point, it seems like a hardware problem in the monitor or power brick, maybe age-related.  Here's the kicker:  he has a older, second workstation running Ubuntu 8 that never shows this problem - the problem only arose when we switched to the new box.  If he uses the old box along with NX to screen-share into the U12 box, there are no problems at all.  However, we want to retire his older box - right now he's only using it to keep his monitor working.
Display issues aren't an area we know much about.  Assuming we don't want to buy newer screens, keyboard, and mouse that are known to be compatible (since it "works" under the right setup, that seems wasteful), we're not sure how to debug this, except by leaving his Frankensystem intact for now.
EDIT:  Just to be clear, we're willing to go into the weeds - for example, I'd like to know if there are any standard tools for observing communication between the OS / video card and the monitor that I could try when this problem occurs.


text:
Q: Tabloid Construction of Permutation Representation of Hyperoctahedral Group For a partition $\lambda \vdash n$, the permutation representation $M^{\lambda}$ of the symmetric group can be constructed in two ways. First, it may be written as the induced representation $M^{\lambda} = 1\uparrow_{S_{\lambda}}^{S_n}$. Second, it may be written as the $S_n$-module spanned by tabloids of shape $\lambda$, $M^{\lambda} = \mathbb{C}\{\{t_1\},\ldots, \{t_n\} \}$, with action given by $\pi\{t_i\} = \{ \pi t_i\}$
I have been working a bit with the permutation representations of the Hyperoctahedral group indexed by bi-partions $M^{\lambda,\mu}$, where $(\lambda, \mu) \vdash n$. In several places (for instance in Geissinger and Kinch), I have seen these representations defined as $M^{\lambda,\mu} = 1\uparrow_{S_{\lambda} \times B_{\mu}}^{B_n}$, where $B_{\mu}$ is the semidirect product of $S_{\mu}$ and $E(m)$, with $\mu$ a partition of $m$ and $E(m)$ the subgroup of $m \times m$ diagonal matrices with diagonal entries $\{\pm 1\}$.
This definition is clearly analogous to the first definition for $M^{\lambda}$. Is there an equivalent definition of $M^{\lambda, \mu}$ as a module of B(n) spanned by some sort of bi-tabloid or other tableaux like object? My end goal here is to understand the specific permutation modules $M^{h_k, \emptyset}$ and $M^{\emptyset, h_k}$ (what does it look like evaluated at some element?). The second definition for $M^{h_k}$ led to a particularly intuitive view of the module, so I was hoping something similar existed for $M^{\lambda, \mu}$


text:
Q: Is it possible to access a shared note via the evernote SDK? I'm wondering if its possible to access a note from the Evernote SDK that a user has shared publicly based on its URL?
Obviously you can pull the page itself down without the API, and you can't write to it either way, but I was wondering if it was possible to get a readonly copy via the API so that you could get the note data without having to attempt an unreliable screen scrape.

A: Yes, you can. The shared note url is of the format : hostname/shard/shardId/notGUID/noteKey .

*

*You can parse this URL, to get all the fields separated out. Then, use authenticateToSharedNote API.

*You can then use the AuthenticationResult to create a note store :
sharedNoteStoreUrl = AuthenticationResult.noteStoreURL;
TBinaryProtocol sharedNoteStoreProt = new TBinaryProtocol(new     THttpClient(sharedNoteStoreUrl));
NoteStore.Client sharedNoteStore = new NoteStore.Client(sharedNoteStoreProt,sharedNoteStoreProt);

*You can then access the note with the getNote API, using the auth token from step 2.


text:
Q: Mui theme not applying if within a wrapper component With React (typescript) and MUI (5.4.2), I'm trying to put everything regarding styles within a single file, wrapping everything in my App.tsx.
Issue: The custom MUI theme does not apply to the rest of my app (fallback to default MUI theme)
The whole thing worked fine when the ThemeProvider component was placed directly within the App.tsx file, but broke as soon as I placed it elsewhere. I need to keep a separated component, for I'll add Elastic UI on top of MUI later on.
My App.tsx file:
function App() {
   <UiProvider>
      // ...whole app
   </UiProvider>
}

The UiProvider component is a simple wrapper component as it follows:
import {ThemeProvider} from "@mui/styles";
import {CustomTheme} from "../../themes/CustomTheme";
import {createTheme, Theme} from "@mui/material/styles";

const UiProvider = (props: any) => {

    return (
        <ThemeProvider theme={CustomTheme}>
            {props.children}
        </ThemeProvider>
    )
}

export default UiProvider

A: Because @mui/styles is the legacy styling solution for MUI, if this is for v5, perhaps the import for ThemeProvider should be:
import { ThemeProvider } from '@mui/material/styles';


text:
Q: Why is my Camel http response body empty despite stream caching? I have a JPA consumer route which makes a POST and enriches the original Exchange:

@Component
public class GetDocumentPlaceholderRoute extends LateDeadLetterRoute {

    private static final AggregationStrategy finalizeImageProcess = (request, response) -> {
        var documentId = response.getMessage(DocumentResponseDto.class).getIntId();
        var imageProcess = request.getIn().getHeader("image-process",ImageProcess.class);
        imageProcess.setDocumentId(documentId);
        imageProcess.setDocumentIdReceivedTime(LocalDateTime.now(ZoneId.of("America/New_York")));

        imageProcess.setImageStatus("complete");
        imageProcess.setStepNote(null);
        var step = Optional.ofNullable(request.getIn().getHeader(STEP)).map(String::valueOf).orElse(null);
        imageProcess.setStep(step);

        return request;
    };

    @Autowired
    private ImageProcessJpaConsumerProperties jpaProps;

    @Autowired
    private AuditorServiceProperties auditorProps;

    @Autowired
    private DocumentIdFetcherProperties routeProps;

    @Override
    //@formatter:off
    public void configure() throws Exception {
        super.configure();

        HttpComponent httpComponent = getContext().getComponent("https", HttpComponent.class);
        httpComponent.setHttpClientConfigurer(new SelfSignedHttpClientConfigurer());

        from(
                jpa(ImageProcess.class.getName())
                        .query(routeProps.getJpaQuery())
                        .delay(jpaProps.getQueryDelay())
                        .maximumResults(jpaProps.getMaxResults())
                        .consumeDelete(jpaProps.getConsumeDelete())
                        .advanced()
                            .sharedEntityManager(true)
        )
                .streamCaching()
                .autoStartup(routeProps.isAutostart())
                .routeId("bill-image-document-id-placeholder-route")
                .description("Retrieves a document ID from the Auditor service")
                .setHeader(STEP, constant(routeProps.getStep()))
                .setHeader("image-process", simple("${body}"))
                .bean(DocumentRequestDto.class, "constructFromImageProcess")
                .setHeader(Exchange.HTTP_METHOD, constant("POST"))
                .bean(ClientCredentialGrant.class, "setTokenHeader")
                .setHeader(Exchange.CONTENT_TYPE, constant("application/json"))
                .marshal().json()
                .enrich(auditorProps.getBaseUrl() + auditorProps.getPath(),
                        finalizeImageProcess);
    }
    //@formatter:on
}

Breaking at the beginning of the AggregationStrategy, this is the response Exchange in:

*

*CameHttpResponseCode: 200

*CamelHttpResponseText: ""

*body is CachedOutputStream, with a currentStream of CachedByteArrayOutputStream containing my data

*I've tried replace the call to "enrich" with a plain "to" but I have the same problem, even without the aggregation strategy

*When I try making the same call with Spring's RestTemplate, I get back the expected data without a problem

A: It was just a matter of targeting the CachedInputStream like this:
response.getIn().getBody(String.class)


text:
Q: Hibernate not automatically creating tables I have hibernate set up in my spring project, once the tables are created in my database it works no problem, however I want my hibernate to automatically create my tables for me. I am not using xml for the configuration I am using application.properties file and a hibernateConfig.java class.
application.properties
hibernate.format_sql = true
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update

HibernateConfig.java
  private Properties hibernateProperties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
    properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
    properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
    properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));

    return properties;
}

Any suggestions would be greatly appreciated!

A: Change the property to hibernate.hbm2ddl.auto=create

A: Take a look at https://docs.spring.io/spring-boot/docs/current/reference/html/howto-database-initialization.html
and set the property hibernate.dbm2ddl.auto=create.
That should solve the problem.


text:
Q: How to simulate simultaneous touch in iOS Simulator I currently have two buttons on my screen , one on the left and one on the right , I wanted to know if there is a way in the iOS Simulator to simulate both buttons being pressed at the same time. I tried pressing ⌥ Alt on the simulator as a result two circles appear. I can position one circle to the first button on the left however I am not sure how to position the next circle on the right button.

A: Once you have the two circles (using the Alt key), move the circles together, then hold the shift key: this will allow you to move the two circles anywhere on the simulator screen.
Then let go the key and click.
I just tried it with this code:
-(void)tapTwo:(UITapGestureRecognizer*)recognizer
{
    CGPoint p1 = [recognizer locationOfTouch:0 inView:self.view];
    CGPoint p2 = [recognizer locationOfTouch:1 inView:self.view];
    NSLog(@"Points: %@ and %@",NSStringFromCGPoint(p1),NSStringFromCGPoint(p2));
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UITapGestureRecognizer* r = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapTwo:)];
    r.numberOfTouchesRequired = 2;
   [self.view addGestureRecognizer:r];
}

and it worked as expected.

A: For the two Circles, all you need to do is click windows + alt button together and to move those two circles to desired position you need to press shift button and drag your cursor to that position.
(The solution is for windows keyboard)


text:
Q: Efficient way to rotate a 2D array of integers of n size in Python I want to rotate (anti-clockwise) a 2D nxn array of integers and the 2D array is stored as a list of lists.
For example:
a = [[1, 2, 3],
     [4, 5, 6],
     [7, 8, 9]]

After rotation, the output should look like:
b = [[3, 6, 9],
     [2, 5, 8],
     [1, 4, 7]]

I have written a function which performs the above rotation:
def rotate_clockwise(matrix):
    transposed_matrix = zip(*matrix) # transpose the matrix
    return list(map(list, reversed(transposed_matrix))) # reverse the transposed matrix

The function works well and the code looks pretty Pythonic to me.
However, I am having trouble understanding the space and time complexity of my solution.
Can someone explain both the complexities of the constructs I have used, namely zip(*matrix), reversed(list), map(list, iterator) and list(iterator)?
How can I make this code more efficient?
Also, what would be the most efficient way to rotate a 2D matrix?
NOTE: As mentioned by @Colonder in the comments, there might be a similar question to this. However, this question focuses more on discussing the space and time complexities of the problem.

A: The most efficient is probably using numpy for this:
>>> import numpy as np
>>> na = np.array(a)
>>> np.rot90(na)
array([[3, 6, 9],
       [2, 5, 8],
       [1, 4, 7]])

About the efficiency of your current approach. If the matrix is an n×n-matrix, then zip will work in O(n2), reversed will here work in O(n) (since it does this in a shallow way), the list function will work in O(n), but we do this n times since it is done in a map(..), so map(list,..) will work in O(n2). Finally the outer list will again work in O(n). There is however no way to rotate explicitly in less than O(n2), since we need to move O(n2) items.
In terms of space complexity zip, map, etc. work in an iterative way. But reversed will force the fact that zip will be fully enumerated. Each tuple from zip requires O(n), so the total amount of memory allocated will be O(n2). Next the map(list,..) works again iteratively, and each tuple will be converted to a list, that requires again O(n). We do this n times. So it will produce O(n2) memory complexity.
In numpy, if you do not rotate inplace, this will require O(n2) as well: this is a lower bound, since the new matrix will require O(n2) memory. If you do however rotate inplace, the memory compexity can be reduced to O(1).

A: I might be late but if it helps, this is w.r.t python3.x

Can someone explain both the complexities of the constructs I have
used, namely zip(*matrix), reversed(list), map(list, iterator) and
list(iterator)?

*

*zip() -> O(1) time and space, it returns the iterators of zip object something like <zip object at 0x104f18480>. But in your case, you've to convert it to a list access the items, which makes it O(n) time and space.

*reversed() -> return iterators of list object <list_reverseiterator object at 0x100ffd1c0> and takes O(n/2) = O(n) time and O(n) space

*list() -> iterates over n items and stores n items so O(n) time and space

*map() -> iterates over m items n times so O(n*m) time and O(n+m) space.
So your code will run in O(n*m) time and O(n+m) space.
def rotate_clockwise(matrix):
    transposed_matrix = list(zip(*matrix)) # O(n) and O(n)
    return list(map(list, reversed(transposed_matrix))) # O(m*m) and O(n+m)

You could also use something like
def rotate_clockwise(matrix):
   return [list(element) for element in zip(*reversed(matrix))]

def rotate_anticlockwise(matrix):
   return [list(element) for element in reversed(zip(*(matrix)))]

or shallow copy (inefficient for larger inputs)
def rotate_clockwise(self, matrix):
    return [list(x) for x in zip(*matrix[::-1])]

def rotate_anticlockwise(self, matrix):
    return [list(x) for x in zip(*matrix)[::-1]]

All of these are very pythonic ways of approaching the question, however these do take extra space which should be alright for most cases. However, from a interview perspective as per your comment for in-place, you could try something like
def transpose(self, mat):
    rows = len(mat)
    cols = len(mat[0])

    for row in range(rows):
        for col in range(row+1, cols):
            mat[row][col], mat[col][row] = mat[col][row], mat[row][col]

def flip(self, mat):
    for row in mat:
        l,r = 0, len(row) - 1
        while l < r:
            row[l], row[r] = row[r], row[l]
            l += 1
            r -= 1

# Clockwise  - call transpose then flip
# Anti-clock - call flip then transpose

If this is for your work, go with pythonic code. In most cases using in-built functions or imported libraries are way better than writing up your own solutions because they are optimised with cPython and are generally faster for all scenarios which can't be achieved with your own solution. Saves a lot of time and efforts.


text:
Q: iOS - Debug my Framework in my App XCode project I have created an iOS Framework "MySDK" which exposes API to my App "MyApp" to send an Alert to my backend. I'd like to walk through the Alert sending code from XCode in debugger. MySDK and MyApp have their own workspaces.
I build my SDK in XCode, and then I build my App with Cocoapods (do a pod install to get the correct versions of all libraries, followed by building manually in XCode) The Podfile for MyApp references the framework as shown.
What is the best/most elegant/non-intrusive way to create a symbolicated/debug version of MySDK and then build my App with it? The end goal is to be able to walk through any part of MyApp or MySDK in one XCode session.


text:
Q: iOS position UILabel in circle view I defined a view which contains an UImageView and a UILabel. I setted constraints for each elements.
In wanted to do a circle with the first view, so I did that in the code :
    self.mainView.layer.cornerRadius = self.mainView.frame.size.width / 2;
    self.mainView.clipsToBounds = YES;

So it works, I have a circle, BUT the UImageView and the UILabel seems don't follow the constraints setted in the storyboard.
For example, on my UILabel, I setted a margin left and right 5px to the mainView, but I can see my UILabel "out" the mainView....
I tried to do a "setNeedsUpdateConstraints", but it's not the solution.
So, what I need to do to have my UILabel correctly positioned ?
Thanks,

A: I think this is what you are looking for:
 self.mainView.layer.masksToBounds = YES;

A: Your problem is that when changing the mainView's layer you are not actually changing the bounds of the view. The bounds of the view are still represented in a rectangle manner. what you need to do is change the width constraint of the UILable.
To do so just create a autolayout constrain to your UILable (is you don't have it already). Control-Drag it to your viewController and change it dynamically using the constant value in the constraint.
If you don't need to set it dynamically just set the left & right margins to a bigger margin


text:
Q: How to get JSON string from HTTP GET request I have a mysql database that stores data such as usernames. I have a PHP file called result which retrieves the results from the database and encodes them into a JSON string. I then want the same PHP file to output the results without a page reload (via ajax). Effectively I want the same page to get the JSON string as a HTTP request, how do I go about this
this is results.php so far
            <?php

        $link = mysql_connect('', '', '');
        if (!$link) {
            die('Could not connect: ' . mysql_error());
        }

        $db_selected = mysql_select_db('test', $link);
        if (!$db_selected) {
            die ('Can\'t use test : ' . mysql_error());
        }

        $result = mysql_query("SELECT user_name FROM users");
        if (!$result) {
            die('Invalid query: ' . mysql_error());
        }

        $names = array();

        while ($row = mysql_fetch_assoc($result)) {

            foreach ($row as $key => $val) {

                $names[][$key] = $val;
            }
        }

        if ($_GET['myvar'] == "done")
        {
            $ennames = json_encode($names);
            echo $ennames;
            exit();
        }

        ?>

A: The only adjustment that your PHP will need for this is to add an if statement immediately after the assignment of $ennames:
if ($_GET['myvar'] == "specific-value-that-you-choose")
{
   echo $ennames;
   exit();
}

For the polling, you will need to do some kind of client-side script - most likely javascript, and most easily written in jQuery. Look into the .getJSON() jQuery function and the setTimeOut() to create logic to do this polling. It will probably look something like this:
function getJSON()
{
   $.getJSON("result.php", { myvar: "specific-value-that-you-choose" }, function(data) {
      var namesHTML = "";

      $.each(data, function(key, val) {
          namesHTML = namesHTML + val + "
";
        });

      $("#divForNames").html(namesHTML);
   });
   setTimeOut(getJSON, 5000); //the 5000 here means 5 seconds
}

Then somewhere in the HTML for the non-JSON page, you need to include a
 with the id set to match the one you using inside the $.getJSON() function (in this case, I'd need an empty
 but you can change the names to fit your preferences.


text:
Q: How to uninstall python 3.7 from Ubuntu 19.10? I'm using Ubuntu 19.10, in which there is python of version 3.7. After the release of python 3.8, which I have installed, now I want to uninstall python 3.7 so that whenever I would call python3 in my terminal, it would always call python3.8?

A: You do not need to uninstall old version for this.
You need to update your update-alternatives , then you will be able to set your default python version.
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.4 1
sudo update-alternatives --install /usr/bin/python python /usr/bin/python3.6 2

Then run :
sudo update-alternatives --config python
Set python3.6 as default.

Or use the following command to set python3.6 as default:
sudo update-alternatives  --set python /usr/bin/python3.6
This should do it.

A: I suggest you do not touch your default OS python instalation. Other parts of the system may depend on it and there is no way to know if an upgrade can break something, even if it should not.
I also suggest that you learn (if you haven't already, but I suppose you did not because of the question) about using a python virtual environment, like virtualenv. This allows you to setup specific python environments for each project you write. This means each environment can have its own python version, and, besides the standard python lib for that version, any other third-party python lib you would like to install with pip for that project. This isolates projects from each other. You won't break one because of an upgrade of another.
That said, if you want to keep cutting edge with Python versions, make an install from source, and then install it in the system with the altinstall parameter (see the README.rst of the Python distribution. This way all the installed versions are available with different names (the same for pip) and then you create each of your virtual environments with the wanted version. There is a parameter for virtualenv to apply a specific (older) version if you want.
Quoting the README on the "Installing multiple versions" section:

On Unix and Mac systems if you intend to install multiple versions of Python
  using the same installation prefix (--prefix argument to the configure
  script) you must take care that your primary python executable is not
  overwritten by the installation of a different version.  All files and
  directories installed using make altinstall contain the major and minor
  version and can thus live side-by-side.  make install also creates
  ${prefix}/bin/python3 which refers to ${prefix}/bin/pythonX.Y.  If you
  intend to install multiple versions using the same prefix you must decide which
  version (if any) is your "primary" version.  Install that version using make
  install.  Install all other versions using make altinstall.
  For example, if you want to install Python 2.7, 3.6, and 3.8 with 3.8 being the
  primary version, you would execute make install in your 3.8 build directory
  and make altinstall in the others.

Finally, the other answers are ok to do exactly what you asked, if you still want to.

A:
so that whenever I would call python3 in my terminal, it would always call python3.8

You can simply create an alias for Python 3.8 in your .bashrc file in your /home path.
Open ~/.bashrc with your preferred editor, and go to the last line.
Append this line:
alias python='python3.8'

And whenever you call python in your terminal, it opens Python 3.8.
Note: This doesn't work as expected when creating virtual environments with specific version. You might want to keep that in mind.


text:
Q: What kind of sort does Cocoa use? I'm always amazed by the abstractions our modern languages or frameworks create, even the ones considered relatively low level such as Objective-C/Cocoa.
Here I'm interested in the type of sort executed when one calls sortedArrayUsingComparator: on an NSArray. Is it dynamic, like analyzing the current constraints of the environment (particularly free memory) and the attributes of the array (length, unique values), and pick the best sort accordingly, or does it always use the same one, like Quick or Merge Sort?
It should be possible to test that by analyzing the running time of the method relatively to N, just wondering if anyone already bothered to.

A: This has been described at a developers conference. The sort doesn't need any memory. It checks if there is a sorted range of numbers at the start or the end or both and takes advantage of that. You can ask yourself how you would sort an 100,000 entry array if the first 50,000 are sorted in descending order.


text:
Q: What is the challenge/response method to securely authenticate with a Server without HTTPS (without sending out password)? What is the challenge/response method to securely authenticate with a Server without HTTPS (without sending out password)?
I have an app (Javascript client) that connects over CORS (authenticate) to our backend which in turns will return a token containing the claim (JWT) over non-HTTPS. The REST is stateless so we do token-based and not have session at all.
When the client gets that token, (containing claim) it is added to the header for each request of the client and therefore the backend knows which User Id is doing that request and do the appropriate thing. So far this works for us. My concern is with the authentication process and with the security of each request.
To authenticate the clients sends out email and hashed password pair, however I want to know if there's a more secure way even without using HTTPS for now. I've read to not send the password but do a challenge/response, but what is the implementation of that idea?
And last question would be, even if we get around with the authentication process securely, how about on each request which contains the token with claim can it be secured also?

A: There is no possible way to do this securely without HTTPS. For your server to authenticate users, you need some kind of token (cookie, adding to requests like you have, etc.) However, the problem is that, without https, an eavesdropper can add javascript to your page. They can then capture the token and use it themself (stealing all the user's data), or modify it. If you want your product to be in any way secure, you need HTTPS.
Edit: I guess you could store some information about the device sending the request (user agent and such), and only allow the token to be used on that device. However, an attacker could just fake the user agent when they reuse the token, so this wouldn't be too hard to bypass.

A: Challenge response is a mechanism to send passwords in non-clear way.
1°/ client and server must share a cyphering key : best is to manually add certificate on client but could be a little bit heavy. Another solution is to store the key only one time into localStorage.
2°/ client requests a challenge to server : this is a "phrase" generated by server
3°/ client concats its password with this "passphrase", ciphers and send response to server : Challenge => Response
4°/ server decrypt message, search and remove its passphrase to get password.


text:
Q: How to "require" text files with browserify? I am using browserify (using browserify-middleware)
how can I require simple text files, something like:
var myTmpl = require("myTmpl.txt");

I cheked stringify plugin for browserify but the code in the documentation is not working with browserify V2

A: stringify:
https://github.com/JohnPostlethwait/stringify
Here's author example:
var bundle = browserify()
    .transform(stringify(['.hjs', '.html', '.whatever']))
    .add('my_app_main.js');

A: If you really want to use require(), you may want to look at partialify:
my.txt:
Hello, world!

index.js:
alert( require( "my.txt" ) );

Where Browserify is configured:
var partialify = require( "partialify/custom" );
partialify.alsoAllow( "txt" );

bundle.add( "./index.js" );
bundle.transform( partialify );

Theoretically you will get a "Hello, world!" message in browser.
P.S. I haven't tried this myself.
Edit: note that this solution breaks NodeJS compatibility - it only works in browserified state, as NodeJS doesn't know how to require .txt files.

A: require() is really best for just javascript code and json files to maintain parity with node and to improve readability of your code to outsiders who expect require() to work the way it does in node.
Instead of using require() to load text files, consider using the brfs transform. With brfs, you maintain parity with node by calling fs.readFileSync() but instead of doing synchronous IO as in node, brfs will inline the file contents into the bundle in-place so
var src = fs.readFileSync(__dirname + '/file.txt');

becomes
var src = "beep boop\n";

in the bundle output.
Just compile with -t brfs:
browserify -t brfs main.js > bundle.js

More discussion about why overloading require() too much is a bad idea: http://mattdesl.svbtle.com/browserify-vs-webpack


text:
Q: When i minimize the page, body color not filled entire window My problem is that the red color does not fill the entire window when I view it in a browser. I want it to use 100% height of the space available. I think the body and html width isn't working, I've also included a CSS reset on my page.

<!doctype html>

    <meta charset="utf-8">
    <title>Untitled Document</title>

A: Here is working fiddle
http://jsfiddle.net/s3bjkqj4/8/

<!doctype html>

    <meta charset="utf-8">
    <title>Untitled Document</title>


text:
Q: Webpack 4 generate only css I have a project without javascript but would like to use webpack 4 and postcss. Every time I run webpack --mode development, a "style.js" is automatically created in the ./dist folder.
How can I prevent this?
webpack.config.js:
module.exports = {
 entry: { style: "./src/8px.css" },
 output: {
   path: path.resolve(__dirname, "dist")
 },
 plugins: [
   new MiniCssExtractPlugin({
     filename: "8px.css"
   })
 ],
 module: {
   rules: [
     {
       test: /\.css$/,
       use: [
         MiniCssExtractPlugin.loader,
         { loader: "css-loader", options: { importLoaders: 1 } },
         "postcss-loader"
       ]
     }
   ]
 }

};

A: you can use webpack-shell-plugin to automatically remove that style.js for you.


text:
Q: Design suggestion for Add / Edit scenario in Angularjs Here is my scenario. I have a addPersonController and editPersonController with addPersonView and editPersonView respectively. In both controller, I am uploading the Person's picture. My upload functionality uses scope variables / functions to handle file upload within controllers.  As a result I am end up with having same code in two different controller. Any suggestion how to reuse the upload functionality? I am using ng-flow directive to upload
$scope.personImageUploaderConfig = {
    target : '/personImageUpload',
    singleFile:true,
    chunkSize : $scope.maxChunkSize,
    query: function (flowFile, flowChunk) {
        // function will be called for every request
        return {
            personId: $scope.newPersonIdentifier, source: 'flow_query'
        };
    }
};

$scope.onUploadCompleted = function () {
    //event triggers by ng-flow when upload completes
};

//calls by controller logic supplying personId
$scope.handleUpload = function(personId){
    if($scope.personPicture){
        $scope.newPersonIdentifier = personId;
        $scope.image.flow.upload();
    }
};
//event triggers by ng-flow when image selected
$scope.imageSelected= function () {

    else {

        $scope.getBinrayFromFile($scope.image.flow.files[0].file).then(function (binary) {
            $scope.personPicture = binary;
        });
    }
};

$scope.getBinrayFromFile=function(file){
    var deferred = $q.defer();
    var r = new FileReader();
    r.onloadend = function(e){
        var data = e.target.result;
        deferred.resolve(data);
    };
    r.readAsBinaryString(file);
    return deferred.promise;
};

A: You could create a directive to handle that, using scope: false to make scope in the directive be the same as the scope in the controller.


text:
Q: setting language in a Locale I would like to know why the following compiles:
Locale aLocale = new Locale.Builder().setLanguage("trollolo").setRegion("CA").build();
System.out.println(aLocale.getLanguage());

Since "trollolo" is not a language. Why does it not return a run time exception but instead it "trollolo" gets even returned when called getLanguage()?

A: This is permitted behavior. From the javadoc

The Builder only checks if an individual field satisfies the syntactic requirement (is well-formed), but does not validate the value itself.

The syntax (IETF BCP 47) is defined in Tags for Identifying Languages


text:
Q: Combining js files efficiently So, I have my main custom_js.js as shown below:
(function ($, root, undefined) {
    $(function () {
        'use strict';
             //js goes here

        // Default line End
    });
})(jQuery, this);

Now, I have an external js file from blazy lazy load.
I tried to put the code in my custom_js.js as below (by just copying and pasting)
(function ($, root, undefined) {
    $(function () {
        'use strict';
        //blazy v.1.5.1
            (function(k,f){"function"===typeof.....
        // Default line End
    });
})(jQuery, this);

But I am getting an error (that "blazy" was not found).
I am simply trying to consolidate the external js into my custom_js file.
What am I doing wrong?
EDIT:
This is the setup:(Everything in footer)
Using the external js.
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

  <script type="text/javascript" src="https://raw.githubusercontent.com/dinbror/blazy/master/blazy.min.js"></script>

  <script type="text/javascript" src="http://example.com/js/custom_js.js"></script>

A: What about pasting it at the end of custom_js.js like that:
(function ($, root, undefined) {
    $(function () {
        'use strict';
             //js goes here

        // Default line End
    });
})(jQuery, this);

//blazy v.1.5.1
(function(k,f){"function"===typeof.....


text:
Q: BitmapData - triangular transformation Hey, this is really annoying me.
I have a big code, but essentially, this part comes to transformation of a BitmapData to triangle points, using affine transformation.
Also - I know that BitmapData is rectangular - the last, fourth point of the transformation is just the first one reflected over the axis defined by the other two points.
A small thing so you can see which point is which one:
1........2
. / / / /|
./ / / /
. / / /  |
./ / /
. / /    |
./ /
. /      |
./
3 - - - -4 - 4th point reflected

This whole process would come to scaling, rotating and skewing the BitmapData based on the angles between the points...
But somehow my code still does not work.
Looking at a similar thing in PaperVision 3D - still didn't work?
Can anybody please post a code, or a link to code for this?
Thanks.

A: have a look at this, might help:
triangles and uvs in flash


text:
Q: mySQL Select All where date is less than 1 day from max date in data I am having a table name "raw".
The date column is not having all the dates of month as it does not record holidays or when there were no sales for the day.
I am trying to get the data form the date less than a day of specific date or max date but it is not returning the search as before the max date was holiday.
here are the dates:
2021-07-09
2021-07-07
2021-07-03
2021-07-02
2021-07-01
2021-06-30
SELECT *
    FROM raw
    WHERE date=(SELECT MAX(date) - 1 FROM raw);

or

SELECT *
FROM raw
WHERE date=(SELECT MAX(date) - interval 1 day FROM raw);

    \begin{table}[]
\begin{tabular}{lll}
Name  & Date       & Sales \\
ACC   & 2020-07-09 & 2000  \\
BEL   & 2020-07-09 & 200   \\
Dabur & 2020-07-09 & 600   \\
ACC   & 2020-07-07 & 450   \\
GMR   & 2020-07-07 & 12    \\
ACC   & 2020-07-03 & 450   \\
ITC   & 2020-07-03 & 45    \\
Dabur & 2020-07-03 & 350   \\
GMR   & 2020-07-03 & 450   \\
BEL   & 2020-06-30 & 500   \\
GTL   & 2020-06-30 & 850   \\
Dabur & 2020-06-30 & 100   \\
ACC   & 2020-06-27 & 50    \\
Dabur & 2020-06-27 & 125
\end{tabular}
\end{table}

A: The query posted by TheWinterCoder should work perfectly if you just change the Order by clause to
rank() over ( order by date desc) date_rank

However, If that somehow doesn't work, You may try below query -
SELECT *
    FROM raw
    WHERE date = (SELECT MAX(date)
                    FROM raw
                   WHERE date < (SELECT MAX(date) FROM raw));

A: If you want the data from the day before a specific date, then use:
SELECT r.*
FROM raw r
WHERE r.date = (SELECT MAX(r2.date) FROM raw r2 WHERE r2.date < ?);

The ? is the specific date.
For the date previous to the maximum date, you could use:
SELECT r.*
FROM raw r
WHERE r.date = (SELECT MAX(r2.date)
                FROM raw r2
                WHERE r2.date < (SELECT MAX(r2.date) FROM raw r3)
               );

Ouch.  Two levels of subqueries.  That seems cumbersome.  A simpler method is:
SELECT r.*
FROM raw r
WHERE r.date = (SELECT DISTINCT r2.date
                FROM raw r2
                ORDER BY r2.DATE DESC
                LIMIT 1 OFFSET 1
               );

A: Since you have breaks in your dates, you can't just subtract 1 from the max date. You would need to rank the dates and then select the top two ranks.
This should help and your query will look something like this:
with order_dates AS(
      Select *,
             dense_rank() over ( order by date desc) date_rank
      from raw
)
select *
from order_dates
where date_rank <=2


text:
Q: AudioManager's isSpeakerphoneOn() returning false in onCreate() My app needs to know early on at onCreate() whether the headset is plugged in or not (if it isn't, it should simply display a dialog and exit, as this is a headset-only app, not to be used with a speaker).
Because registering a receiver for ACTION_HEADSET_PLUG or ACTION_AUDIO_BECOMING_NOISY is recommended to be done in either onStart() or onResume(), relying on these messages in onCreate is out of question.
So, I turned instead to Audio Manager's isSpeakerphoneOn() with the hope that my app's onCreate() will find it reflecting the correct status of the speakerphone.
Unfortunately however, isSpeakerphoneOn() always return false, despite the speakerphone being on and nothing else plugged in (neither wired nor bluetooth headset).
My questions are:

*

*Why? What are the conditions for this isSpeakerphoneOn() method to correctly reflect the phone's status?

*Is there a way to determine in onCreate() whether the headset is plugged in or not?


text:
Q: Differential equation with complex roots and undetermined coefficients Hey guys i need help with this problem:
$y''-4y'+5y=6e^{2x}sinx$
I get the roots from the characteristic equation.
$r^2-4r+5=0$
$\implies r=2\pm i $
Then i set up:
$y_{h}=c_{1}e^{2x}sinx+c_{2}e^{2x}cosx$
And i know that:
$y_p=e^{2x}(Asinx+Bcosx)x $
But the problem arrives when i differentiate. The problem is the x on the end i dont know how to work with it, i can solve the other differential equation types.  For this problem i end up with:
$$-xBcosx-2Bcosx+4Acosx-2xBsinx-xAsinx+2Bsinx$$
After differentiating and putting it back into the equation. But i dont know what to do with the x's.

A: If I may suggest.
You can make your life much easier if you start from the very beginning using $$y=e^{2x}z \implies y'=e^{2 x} \left(z'+2 z\right)\implies y''=e^{2 x} \left(z''+4 z'+4z\right)$$ This makes the differential equation to be $$z''+z=6\sin(x)$$ and then, almost as you wrote, the particular solution will be $$z_p=x(A \sin(x)+B \cos(x))$$ $$z'_p=\sin (x) (A-B x)+\cos (x) (A x+B)$$ $$z''_p=\cos (x) (2 A-B x)-\sin (x) (A x+2 B)$$ $$z_p''+z_p=2 A \cos (x)-2 B \sin (x)=6\sin(x)$$ which is easy to solve.

A: The first derivative of $y_p$ should be $$Be^{2x}\cos x + 2B e^{2x}x\cos x - Be^{2x}x \sin x + A e^{2x}x\cos x + Ae^{2x} \sin x + 2Ae^{2x}x \sin x $$
and the second derivative should be
$$-Be^{2x}x \cos x + 4Be^{2x}\cos x +4Be^{2x}x\cos x - 2Be^{2x} \sin x - 4Be^{2x}x \sin x + 2Ae^{2x}\cos x + 4Ae^{2x}x \cos x - Ae^{2x}x\sin x + 4Ae^{2x}\sin x +4Ae^{2x}x \sin x,$$
and plugging back into the original equation, everything cancels out nicely so that you can solve for $A$ and $B$.


text:
Q: Separate value selected from primereact dropdown In this code I have the possibility to upload images and display them with a category for each one. The image and category are saved in an array. The problem is when I want to select a value of a dropdown, the value selected doesn´t change in the dropdown to see the value that I selected, but this value is saved when I clicked it in the array field in the dropdown.
import {  faHandHoldingUsd, faTrash, faUpload } from '@fortawesome/free-solid-svg-icons';
import  { Fragment, useCallback} from 'react'
import SetIcon from '../../../../Components/Forms/SetIcon';
import MessageError from '../../../../Components/MessageError';
import '../Css/FrmImages.css';
import { Image } from 'primereact/image';
import { Dropdown } from 'primereact/dropdown';
import { CATEGORIES } from '../../../../constants';

type Props={
    setValue:any,
    errors:any,
    getValues:any,
    watch:any,
    control:any,
    trigger:any,
}

const FrmImages : React.FC<Props> = ({setValue,errors,getValues,watch,control}) => {

    const deleteHandler=useCallback((index_image:any)=>{

        setValue('images',getValues('images').filter((e:any,index:any) => index !== index_image));
        watch('images')
    },
      [setValue,getValues,watch],
    )

    const handleChange = (event:any) => {
        let files = event.target.files;

        for (let i = 0; i < files.length; i++) {
          const file = files[i];

          const reader:any = new FileReader();
          reader.readAsDataURL(file);
          reader.onloadend = () => {
            const image = reader.result.split(',')[1];
            //append({'arrayField.image':{image:'',product_image_type_id:0}})
            setValue('images',getValues("images").concat({image}));
            watch('images')
          };

        }
        event.target.value="";

    };

      const handleCategoryChange = (index:any, event:any) => {

        //--------------------LINEAS DE CODIGO PARA GUARDAR LA CATEGORIA EN EL ARREGLO QUE SE VA A ENVIAR EN EL FORMULARIO EN EL PARAM images-----------------------

         const newCategories = [...getValues('images')];

         newCategories[index].product_image_type_id = Number(event.value);
         console.log(newCategories);

        //setValue('images',newCategories);

        //-------------------------------------------------------------------------------------------------------------------------------------------------------------

    };

    const ImageError = () => {
        return (

                { errors.images && errors.images.length ? errors.images.map((image:any, index:any)=>{
                    return (

                            <MessageError name={image?.product_image_type_id} message={image?.product_image_type_id ? 'La imagen ' + (index + 1) + ' ' +  image.product_image_type_id?.message  : '' }/>

                    )
                    }) :
                    <></>
                }

        )
    }

  return (

                <SetIcon icon={faUpload}/>Subir

                 Hasta 10 imagenes
                <input
                className='input-file'
                type="file"
                onChange={handleChange}
                multiple
                accept="image/*"
                />

                {

                        getValues('images').map((image:any, index:any) => {

                            return (

                                        <Image src={`data:image/png;base64,${image.image}`} height="130" width='150' alt="upload" preview className='image-base64'/>

                                            <button onClick={() => deleteHandler(index)} >
                                                <SetIcon icon={faTrash} className='icon-trash'/>
                                            </button>

                                            <Dropdown optionLabel="name" optionValue="id" value={image.product_image_type_id} options={CATEGORIES} onChange={(e) => handleCategoryChange(index,e)} placeholder="Select a City"/>

                                             {index+1}

                            )
                        })

                }

            <ImageError/>

            {getValues('images').length > 0 &&
                (getValues('images').length > 10 && (

                    No se permite subir mas de 10 imagenes

                    Por valor elimina  {getValues('images').length - 10}  de estas{" "}

                ))}

  )
}

export default FrmImages

I expected that when I clicked an option of just one dropdown, I can see the value that I selected in the dropdown. Usually this process commonly is done with a useState in the onChange event to manage the change in the state, but unfortunately due to I have more than one dropdown, the selected value appears in all the dropdowns. Thanks for helping me.


text:
Q: How do I write $ba$ in the form $a^i b^j\ $?
Let $p$ be a prime number and $q \in \Bbb N$ be such that $q\ |\ (p-1).$ Let $u \in \Bbb Z_p^*$ be an element of order $q.$ Now consider the group $G$ defined by $$G = \left \langle a, b\ \big |\ a^p = b^q = e,\ b^{-1} a b = a^u\ \right \rangle.$$ Prove that any element of $G$ can be written as $a^i b^j,$ for some $0 \leq i \lt p$ and $0 \leq j \lt q$ and hence $|G| = pq.$

My question is $:$ How do I write $ba$ in the form of $a^ib^j\ $? Can anybody please help me in this regard.
Thanks for your time.

A: Since $b^{-k}ab^k=a^{u^k}$, then we have $ba=b^{-(q-1)}ab^{q-1}b=a^{u^{q-1}}b$.


text:
Q: MySQL query to select a certain day in the past? I have a joomla website and I want to make a query that it could run with a cronjob every day. It would look for any articles 30 days old and delete the articles this specific day.
I can make a simple query like this:
SELECT * FROM  `ibps6_content`
    WHERE created > '2013-10-16' AND created < '2013-10-16'

But I don't know how to make it specify the last 30 days, instead of hardcoding the dates.

A: Which rdbms?
In oracle you can use select based on sysdate which represents the current date/time.
Example:
select * from ibps6_content WHERE created between sysdate - 30 and sysdate

A: In T-SQL, you could use the following:
SELECT
    *
FROM
    ibps6_content
WHERE
    created BETWEEN DATEADD(DAY, -30, GETDATE()) AND GETDATE()

Note that this will give you the articles written up to the specific time that you run the article. To remove the times and utilize just the dates, you could use:
DECLARE @CurDate DATETIME;
SET @CurDate = DATEADD(dd, 0, DATEDIFF(dd, 0, GETDATE()));

SELECT
    *
FROM
    ibps6_content
WHERE
    created BETWEEN DATEADD(DAY, -30, @CurDate) AND @CurDate

A: If created is a date datatype in the table
DELETE FROM ibps6_content WHERE created = CURRENT_DATE -INTERVAL 30 DAY

If it's datetime use DATE(created)

A: You need mysql DATE_FORMAT(date,format) function.
Please try to set your query as:
DELETE FROM `ibps6_content` WHERE created > DATE_FORMAT(NOW() - INTERVAL 1 MONTH, '%Y-%m-%d');

Hope this helps


text:
Q: Vagrant 'permission denied' on Windows I am having trouble accessing files through Vagrant on Windows. I have been using it on OS X for quite some time and have my Vagrantfile setup correctly which works every time.
I have sent my colleague the same Vagrant file, he is on Windows and receives 'Permission Denied' when trying to access files through the browser.
Just to be clear, the permission errors are returned by the server when accessing 'dev.local' in the browser and not from Vagrant itself... it will be a configuration error on Windows or within the VM.
The VM is CentOS 6.5
Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagrantfile API/syntax version. Don't touch unless you know what you're doing!
VAGRANTFILE_API_VERSION = "2"

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
  config.vm.box = "chef/centos-6.5"
  config.vm.network "private_network", ip: "192.168.33.21"
  config.vm.network :forwarded_port, guest: 80, host: 8080
  config.vm.provision :shell, :path => "install.sh"
  config.vm.hostname = "dev.local"
  config.vm.synced_folder ".", "/home", id: "vagrant", :nfs => false, :mount_options => ["dmode=777","fmode=777"]
  config.ssh.insert_key = false
  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"
end

Can any Windows Vagrant users shed any light on this?

A: It was VBGuestAdditions out of date. The permission error was caused by not being able to sync to my local folder (which contained an index.php) so it was using the servers /home folder which didn't contain anything and since viewing directory structure is disabled it returned permission errors.
I had 4.X.X installed, and VirtualBox is on 5.X.X Here is the fix:
run command: vagrant plugin install vagrant-vbguest
the run vagrant up which may still throw an error as the plugin fails to copy a file.
vagrant ssh to get into the box and run the following command:
sudo ln -s /opt/VBoxGuestAdditions-5.X.X/lib/VBoxGuestAdditions /usr/lib/VBoxGuestAdditions
Replace 5.X.X with the version of your VirtualBox.
logout and run vagrant reload
do a happy dance


text:
Q: Selenium problems with PDF download in Firefox I'm working on an upgrade of our internal Java Selenium framework to the latest version 3.14.0 in combination with Firefox 61.0 and Geckodriver 0.21.0.
I face problems when it comes to an automated download of a PDF file with Firefox. For example at this link there is a download button where I can let selenium perform a click on. Instead of downloading the pdf, a built-in viewer will be opened. The preference pdfjs.disabled should deactivate the viewer so created the driver instance with a profile (and also tried some more preferences).
FirefoxProfile firefoxProfile = new FirefoxProfile();
firefoxProfile.setAcceptUntrustedCertificates(true);
firefoxProfile.setAssumeUntrustedCertificateIssuer(true);
firefoxProfile.setPreference("browser.download.folderList", 2);
firefoxProfile.setPreference("network.cookie.cookieBehavior", 0);
firefoxProfile.setPreference("network.cookie.alwaysAcceptSessionCookies", true);
firefoxProfile.setPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
firefoxProfile.setPreference("browser.helperApps.neverAsk.openFile", "application/pdf");
firefoxProfile.setPreference("browser.helperApps.alwaysAsk.force", false);
firefoxProfile.setPreference("browser.download.manager.showAlertOnComplete", false);
firefoxProfile.setPreference("browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.panel.shown", false);
firefoxProfile.setPreference("browser.download.manager.focusWhenStarting", false);
firefoxProfile.setPreference("browser.download.manager.closeWhenDone", false);
firefoxProfile.setPreference("browser.download.manager.useWindow", false);
firefoxProfile.setPreference("services.sync.prefs.sync.browser.download.manager.showWhenStarting", false);
firefoxProfile.setPreference("browser.download.manager.alertOnEXEOpen", false);
firefoxProfile.setPreference("pdfjs.disabled", true);

FirefoxOptions firefoxOptions = new FirefoxOptions();
firefoxOptions.setProfile(firefoxProfile);
WebDriver webdriver = new FirefoxDriver(firefoxOptions);

Unfortunately with the used Firefox version this config has no effect. Unless you change pdfjs.disabled to true at runtime within the about:config page. Only when first changed at runtime, the pdf viewer is really disabled. Seems to be a bug in Firefox. Ok anyway, I found a way to change this at runtime with selenium.
But now that the pdf viewer is skipped another popup is interrupting the download. Selenium is not even aware of this popup.
On the preferences page about:preferences under Applications I can see now that for the Content Type PDF document the Action was changed to nothing, which seems to be the same as Always ask. Before it was Preview in Firefox but it has to be Save File in order to reach my goal which is to immediately download the PDF without any questions.
Not with a single config you could possibly change this to "Save File". Am I wrong? But when I checked profile folders for differences I found out that there is a handlers.json that contains the settings from the picture above. It is read in during the browser startup and first adapted on browser close.
Normally selenium creates a new temporary profile folder for each new browser instance. If I want to have an influence on the desired setting, I need to define a custom profile. That was my thought. So I tried this:
firefoxOptions.addArguments("-profile", "/tmp/my.profile");

I think this is correct, but now yet another problem... becauses though Firefox creates the neccessary files in the given directory, the the communication between selenium and firefox fails. The browser window is opened and healthy, but Selenium is not able to start the session.
org.openqa.selenium.WebDriverException: connection refused

            at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
            at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
            at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
            at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
            at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$new$0(W3CHandshakeResponse.java:57)
            at org.openqa.selenium.remote.W3CHandshakeResponse.lambda$getResponseFunction$2(W3CHandshakeResponse.java:104)
            at org.openqa.selenium.remote.ProtocolHandshake.lambda$createSession$0(ProtocolHandshake.java:122)
            at java.util.stream.ReferencePipeline$3$1.accept(ReferencePipeline.java:193)
            at java.util.Spliterators$ArraySpliterator.tryAdvance(Spliterators.java:958)
            at java.util.stream.ReferencePipeline.forEachWithCancel(ReferencePipeline.java:126)
            at java.util.stream.AbstractPipeline.copyIntoWithCancel(AbstractPipeline.java:498)
            at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:485)
            at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
            at java.util.stream.FindOps$FindOp.evaluateSequential(FindOps.java:152)
            at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
            at java.util.stream.ReferencePipeline.findFirst(ReferencePipeline.java:464)
            at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:125)
            at org.openqa.selenium.remote.ProtocolHandshake.createSession(ProtocolHandshake.java:73)
            at org.openqa.selenium.remote.HttpCommandExecutor.execute(HttpCommandExecutor.java:136)
            at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:83)
            at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:548)
            at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:212)
            at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:130)
            at org.openqa.selenium.firefox.FirefoxDriver.<init>(FirefoxDriver.java:140)
            …

So the general question is: How can I force Firefox (controlled by selenium) to download the PDF file to my file system when clicked on the button? Any possibilities are reasonable.
As I am running out of ideas it would be great if somebody could help or at least confirm that these things are problems with Firefox.

A: *

*close firefox

*run firefox profile manager (Win+R: firefox -p)

*create a new firefox profile called let's say selenium_profile

*run firefox in selenium_profile

*download manualy your desired PDF file and set up to always download such file types

To run webdriver with selenium_profile, use this:
public static void setUpClass() {
    FirefoxOptions options = new FirefoxOptions();
    ProfilesIni allProfiles = new ProfilesIni();
    FirefoxProfile selenium_profile = allProfiles.getProfile("selenium_profile");
    options.setProfile(selenium_profile);
    options.setBinary("C:\\Program Files (x86)\\Mozilla Firefox\\firefox.exe");
    System.setProperty("webdriver.gecko.driver", "C:\\Users\\pburgr\\Desktop\\geckodriver-v0.20.0-win64\\geckodriver.exe");
    driver = new FirefoxDriver(options);
    driver.manage().window().maximize();}

Just edit paths.

A: Add pdfjs.enabledCache.state to false.
FirefoxOptions options = new FirefoxOptions();
options.addPreference("browser.download.folderList", 2);
options.addPreference("browser.download.dir", pathToDownload);
options.addPreference("browser.helperApps.neverAsk.saveToDisk", "application/pdf");
options.addPreference("pdfjs.enabledCache.state",false);
WebDriver driver = new FirefoxDriver(options);

Geckodriver Selenium Auto Download PDFs


text:
Q: Using regex to split text content into dictionary I have a text file that follows this format.

LESTER HOLT (00:00:01): Breaking News Tonight: A deadly mass shooting
  at the airport. A gunman opens fire at baggage claim in Fort
  Lauderdale, witnesses describing scenes of sheer horror. A silent
  killer shooting people in the head as they tried to run and hide.
  Tonight, a storm of questions. Why did he do it? The suspect, a
  passenger with a firearm in his checked bag. New concerns about
  airport security before the checkpoint.
(00:00:25): Also breaking tonight the new report from U.S.
  intelligence: Vladimir Putin himself ordered the effort to influence
  the election, aimed at hurting Clinton and helping Trump win. What the
  President-elect is saying after his top-secret briefing.
(00:00:39): And States of Emergency: Millions from coast to coast
  paralyzed by a massive winter storm.
(00:00:45): NIGHTLY NEWS begins right now.

I am trying to parse this information into a Python Dictionary, where the speaker is a dictionary, of dictionaries, which has timecode keys, and the content is the value, I can't consistently split because of potential information before the timecode, (IE the first quote), as well as the fact that the split character : is also a character involved with the timecode itself 00:00:00.
Trying to split according to the regex.
for line in msg.get_payload().split('\n'):
    regex = r'\d{2}:\d{2}:\d{2}'
    test = re.split(regex, line)
    print(test)
    sleep(1)

Appears to work in splitting it properly, but it causes me to lose the value I am splitting on (timecode), which I intend to use as a key. How can I properly split the above content, get the speaker, and then get the timecode as a key, and the content as a value.It is possible he may be present later in the text as well, and it should append to the list of timecodes./
The output format I am targeting is something along the lines of
{speakers:{'Lester Holt': {'00:00:01':content..., '00:00:0025': content...},
'speaker2':{etc,etc,etc} }}

Ive tried using the split as mentioned above, but it removes my timecode variable.
Any thoughts and guidance is appreciated.

A: Don't bother with split. You're trying to get 2-3 pieces of information out of each line, so try the following:
for line in msg.get_payload().split('\n'):
    match = re.search(r'^\s*([^(]*?)\s*\((\d{2}:\d{2}:\d{2})\):\s*(.*)$', line)
    if match:
        (speaker, time, message) = match.groups()

Speaker will be an empty string if none was present on that line.
Regex explanation:
^                    # Start of line
\s*                  # Drop leading whitespace
([^(]*?)             # Capture the speaker if present (non-paren characters)
\s*                  # Drop whitespace between name and time
\(                   # Drop literal open paren
(\d{2}:\d{2}:\d{2})  # Capture time
\):\s*               # Drop literal close paren, colon and whitespace
(.*)                 # Capture the rest of the line
$                    # End of line

A: Splitting message in lines when you need to split it in time-stamped paragraphs is a waste. re.split can easily save the tokens that it split on, if you only look at the documentation. Here's my solution:
toks = re.split(r"\((\d\d:\d\d:\d\d)\):", msg.get_payload())[1:]
answer = dict(zip(toks[::2], toks[1::2]))

This creates a dictionary of timestamps and paragraphs. Feel free to use the same approach to split by speaker as well.
Result:
    {
        '00:00:01': ' Breaking News Tonight: A .....',
        '00:00:25': ' Also breaking tonight ......', ....
    }


text:
Q: OpenVPN cannot ping I have configured OVPN server on Mikrotik router.
My LAN have adresses: 192.168.0.0/24
I have set vpn local address to: 192.168.1.5 and remote address 192.168.1.6
Router on which VPN server is runing has ip 192.168.0.30
The problem is that I can only ping 192.168.0.30 and 192.168.1.5 (local vpn address). I cannot ping other devices in network.
In firewall rules I have:

*

*accept chain:input; protocol: tcp; dst. port 1723

*accept chain: input/output/forward; src: 192.168.1.5

In routes I have set:

*

*dst.: 192.168.0.0/24 with gateway ovpn-test

I am not very familiar with networking and linux systems so every suggestion how to improve this question and provide more details is also welcomed.
My client script:
dev tun
proto tcp-client
remote xx.xx.xx.xx 11723

ca ca.crt
key picom.key
cert picom.crt

tls-client
port 11723

persist-tun
persist-key

verb 3
auth SHA1
pull
auth-user-pass

route-method exe
route-delay 2

route 192.168.0.0 255.255.255.0
route 192.168.1.0 255.255.255.0

Edit:

*

*Router IP address is 192.168.0.30

*VPN server local address is 192.168.1.5

*Remote address is 192.168.1.6

*VPN client gets address 192.168.1.6. I don't know if I understand this question right?

*VPN client is connected to different network using another ISP

*Port 11723 in router which has external IP is forwarded to 1723 of my router   with VPN server. Unfortunately I dont have access to this router config.

A: You cannot use the same network address range in two distinct places.

*

*Your LAN is 192.168.0.0/24. No other addresses must be used on the LAN itself.

*Your OpenVPN route must not be 192.168.0/24. Use addresses 192.168.1.0/24 or indeed from any other RFC1918 address. But not 192.168.0.0/24.

*If you are going to set up a static route on your Router to the VPN Server for the VPN subnet 192.168.1.0/24 you must reference the VPN Server with its LAN address 192.168.0.30 (see point #1).

You will also probably need to enable forwarding. To test (until the next reboot) that this works you can run
sysctl -w net.ipv4.ip_forward=1

Once you're happy you can add net.ipv4.ip_forward=1 into the system file /etc/sysctl.conf or create your own file under /etc/sysctl.d/. You may find the line already present but just commented out. Obviously in this case you could just uncomment the line.
I see from the comments that you've added a route from your clients to the LAN. Don't forget the reverse entry for your LAN clients back to the VPN.

A: There is need to set NAT masquarade for srcnat chain with 192.168.1.0 (OpenVPN  as a source address.