text:
Q: File ending error while deploying to azure devops from .yaml file? How to get rid of CRLF will be replaced by LF while deploying code from . yaml file
i tried to put git config --global core.autocrlf true but it didnt work.
Error:
/usr/bin/bash --noprofile --norc /home/vsts/work/_temp/3593ff85-827d-4f46-b0bc-685e80981d5c.sh
warning: CRLF will be replaced by LF in GTVisualization/src/gtvisualization.py.
The file will have its original line endings in your working directory
diff --git a/GTVisualization/src/gtvisualization.py b/GTVisualization/src/gtvisualization.py
index f42a167..7fe52ae 100644
--- a/GTVisualization/src/gtvisualization.py
+++ b/GTVisualization/src/gtvisualization.py

this is my yaml file :
# Docker
# Build a Docker image
# https://learn.microsoft.com/azure/devops/pipelines/languages/docker

trigger:
  - master

resources:
  - repo: self

variables:
  tag: "$(Build.BuildId)"
  imageName: 'pipelines-pytest-docker'
  dockerfilePath: $(Build.SourcesDirectory)/GTEstimation/Dockerfile
  workdir: /opt/app

stages:
  - stage: Check
    jobs:
      - job: CheckJob
        displayName: Build
        pool:
          vmImage: "ubuntu-latest"
        steps:
          - task: Cache@2
            inputs:
              key: "$(Agent.OS) | docker | db-lz-check"
              path: $(Pipeline.Workspace)/docker
              cacheHitVar: DOCKER_CACHE_RESTORED
            displayName: "Caching Docker image"
          - checkout: self
            clean: true
            lfs: true
            path: src/
            displayName: "Check out repository"
          - script: git config --global core.autocrlf true
            displayName: "Line endings new"
          - script: git diff --exit-code
            displayName: "Line endings"
          - script: |
              docker load < $(Pipeline.Workspace)/docker/dockerfile-lint.tar
              docker load < $(Pipeline.Workspace)/docker/autopep8.tar
            condition: and(not(canceled()), eq(variables.DOCKER_CACHE_RESTORED, 'true'))
            displayName: "Load docker images"
          - script: |
              mkdir -p $(Pipeline.Workspace)/docker
              docker pull projectatomic/dockerfile-lint
              docker save projectatomic/dockerfile-lint > $(Pipeline.Workspace)/docker/dockerfile-lint.tar
              docker pull unibeautify/autopep8
              docker save unibeautify/autopep8 > $(Pipeline.Workspace)/docker/autopep8.tar
            condition: and(not(canceled()), or(failed(), ne(variables.DOCKER_CACHE_RESTORED, 'true')))
            displayName: "Store docker images to cache"
          - task: Bash@3
            inputs:
              targetType: "filePath"
              filePath: "ci-scripts/docker-linter.sh"
            displayName: "Docker linter"
          - task: Bash@3
            inputs:
              targetType: "filePath"
              filePath: "ci-scripts/python-formatter.sh"
            displayName: "Python format PEP 8"
  - stage: Build
    displayName: Build image
    jobs:
      - job: Build
        displayName: Build
        pool:
          vmImage: "ubuntu-latest"
        steps:
          - task: Docker@2
            displayName: Build an image
            inputs:
              command: build
              dockerfile: "$(Build.SourcesDirectory)/src/Dockerfile"
              tags: |
                $(tag)
  - stage: Test
    jobs:
      - job: Test
        pool:
         vmImage: "ubuntu-latest"
        steps:
        - task: Docker@2
          displayName: Build an image
          inputs:
             repository: $(imageName)
             command: build
             dockerfile: $(dockerfilePath)
             tags: |
              $(tag)
        - script:
             docker run $(imageName):$(tag) bash -c "pylint $(workdir)/src/map_matched.py"
        - script:
             docker run $(imageName):$(tag) bash -c "pytest -v --cov-report xml --cov=. --junitxml=/tests/test-reports/pytest-report.xml"

Since i'm new to azure devops and docker, if i'm going in wrong direction then please correct me.
anything wrong with my git attributes files? below is the file.
# .gitattributes
# More information about this file:
#   https://git-scm.com/docs/gitattributes
#

# Set default behavior to automatically normalize line endings.
* text=auto
* text eol=crlf

A: You should use git config --global core.autocrlf false instead of git config --global core.autocrlf true. Please refer to this ticket for more details.


text:
Q: How to change the visibility of a class field or member for Xamarin Android bindings? I know ways to do this for methods, but none for fields. Any help would be appreciated. Thanks
<Java Code>
public class foo
{
    private int var1;

    private int mtd(){
    ---
    }
}

If it is a method, I know to track the method and change its visibility by incl the following in the metadata.xml file:
<attr path="/api/package[@name='com.xxx.xxx']/class[@name='foo']/method[@name=''mtd]" name="visibility">public</attr>
How to do the same for a member or field?

A:
I know ways to do this for methods, but none for fields. Any help would be appreciated.

The contents in Metadata.xml will be applied to project folder\obj\api.xml and in api.xml fields are defined like below:
MyClass.java:
package com.winffee.libs;

public class MyClass {
    public int abc;
    public int myMethod() {
        return 0;
    }
}

<field deprecated="not deprecated" final="false" name="abc" static="false"
    transient="false" type="int" type-generic-aware="int" visibility="public" volatile="false">

So, you can define following codes in Metadata.xml to modify the Visiblity of abc field:
<attr path="/api/package[@name='com.winffee.libs']/class[@name='MyClass']/field[@name='abc']" name="visibility">private</attr>

redpajama_set_name: RedPajamaStackExchange


text:
Q: scilab plotting of a function and datasets on the same graph I am trying to display 3 curves of both measurements and theory on the same graph for comparison, using scilab. The problem is that while 2 curves have the same size for their datasets, the theoretical curve should be made from a function with a much larger dataset although both have the same range.
D1 and D2 have 13 values to be displayed with the 13 values for the x axis in D0 (tiks should range from 0 to 500).
The theoretical function should be displayed along something like a linspace from 0 to 500 with 500 values and not only 13. Such that all the curves are aligned with tiks from o to 500 on the x axis.
I tried using the code shown below but it will only display the curves of D1 and D2.
My code:
clc;
clear;
xdel(winsid());
    D0 = [0, 40, 80, 120, 160, 200, 240, 280, 320, 360, 400, 440, 480];
//x axis for D1 and D2
    D1 =[4.96, 5, 4.96, 4.96, 4.96, 4.96, 4.96, 4.96, 4.95, 4.96, 4.96, 4.96, 4.96];  //first curve
    D2 =[0, 1.61, 2.73, 3.58, 4.05, 4.24, 4.56, 4.72, 4.93, 4.88, 4.90, 4.90, 4.95];  //second curve
    foo1 = (-5)*(1-%e^((-1)/(0.1)*(linspace(0, 1, 500))));                            //the problematic function that will not show on the plot when the other curves are displayed
scf();
  aa = gca();
  aa.font_size=3;
  aa.thickness=2;
  plot(D0, D1, "r-", "fontsize",5);
  plot(D0, D2, "g-", "fontsize",5);
  plot(linspace(0, 1, 500), foo1);

I want the 3 curves to be on the same graph with x axis of 0 to 500.

A: You made an error for the linspace function you should use something like
   linspace(0, 500, 1000);

First point, last point, number of values.


text:
Q: How does Facebook Instant personalisation work? I just visited http://www.tripadvisor.co.uk/ and without me filling in any login form, it knew my identity, because I was logged on to facebook.
I have found out that Trip Advisor is part of a program Facebook are running called 'Instant Personalisation'.
My question is:  How does this work?  What is going on behind the scenes?  What is being sent by my browser, by what method (eg HTTP POST, iFrame, Ajax etc), and to who?
In particular, I had previously thought that the browsers' cross-domain-scripting security rules made this kind of thing impossible.  I thought that browsers would never let a script on exampleone.com communicate with exampletwo.com.
So how is it possible that tripadvisor.com can gain access to information that I originally sent to facebook.com?  How are they able to get around the cross-domain scripting rules?
PS - Please do not tell me that I can disable Facebook Instant Personalisation.  I already know I can opt out (on this page https://www.facebook.com/settings?tab=applications).  This is a question about the technology that makes Instant Personalisation possible.
EDIT --
A few people have already commented that a request is sent to facebook to obtain my details.  I agree that this must be the case.  But What I'm asking, is how does this request get sent to facebook?  If I visit tripadvisor.com then I'm actively telling my browser to make a request to tripadvisor.com.  NOT to facebook.com.  And I thought that a script running on tripadvisor.com would be blocked by my browser from communicating with facebook.com.
I find this extremely unsettling. Presumably if tripadvisor knows my identity, then their servers could inform facebook servers of the pages I view.  In the specific case of tripadvistor and facebook I'm not too bothered about this. I suspect the data would just be used for better targeting the kind of the ads they show me. Harmless enough....
But if my online identity can be passed around between domains like this without me knowing, in a way I previously thought was impossible, then this means there could be other sites who are using this technology for malicious purposes. So I want to understand whats going on, and understand what exactly I'm exposed to.

A: OK, thanks for your help with this @BassemDy - you gave me 90% of the answer, and I've just figured out the other 10% that I was missing.
I can see that it's possible for tripadvisor to make my browser send a request to facebook without breaking any cross-domain rules.  As BassemDy pointed out, this happens all the time, when you load images from an external domain, or load a shared script from some external domain like google maps etc...
What I couldn't see, was how it was possible for tripadvisor to make my browser send a request to facebook, which could then identify me.
Then the answer hit me.  Of course tripadvisor's scripts can't directly read my facebook cookie...  but when my browser makes the cross domain request to facebook, my browser will send my facebook cookie to facebook.  That was the part I was missing.
Then facebook can respond in some way which tripadvisor's script can read, and hence tripadvisor's script can determine my identity.
All that business with OAuth and tokens is just a way of making the above process secure.  Underneath it all, is the fact that tripadvisor can make me send my facebook cookie to facebook.
As a proof of concept, I ran the following test scripts on 2 different domains I control:
on domainone.com - login.php
<?php setcookie('yourname','Daniel Howard',0,'/');
exit;

on domainone.com - responder.php
<?php header('Content-type: text/javascript'); ?>
window.cookieFromDomainone = <?= json_encode($_COOKIE) ?>;
window.updateMe();

then on domaintwo.com - test.php
<!DOCTYPE html>

First I visit domainone.com/login.php and it sets a cookie with my name in it.  Something similar to this would happen when you login to facebook.
Then I visit domaintwo.com/test.php
It has no way to read my domainone.com cookie.  But it makes my browser send a request to domainone.com and my browser will send along my domainone.com cookie with the request.  Then, in domainone.com/responder the cookie values are fed into some javascript which is returned, and executed on domaintwo.com.
The javascript that is executed makes my identity available on domaintwo.com.  And this is illustrated when my name appears in the p element.
I'm quite appalled at how easy it is to write code that would basically spit out users identities to any site that cared to ask for it.  I wonder how many poorly written attempts at single-sign-on are out there in the wild waiting to be exploited....  Hopefully this OAuth system that facebook and their pals are using is secure.

A: Here's a brief technical explanation about what happens behind the scenes:
When tripadvisor loads the page, it makes a request to Facebook highlighted below:

The request contains a specific ID from tripadvisor and some parameters defining what to return. Facebook validates the request and returns what seems to be an access token to an application that only has access to your public information. This token is only given to their partners.
Your client is always allowed to make HTTP requests to external domains! It's how CDNs work and multiple other web implementations. When you retrieve an image from an external source which is not contained on the server that is serving you the page content you are currently browsing, this is an external request which does not violate cross domain policies.
The response from Facebook is contained in:
xd_arbiter.php?version=25

It's javascript code that is executed on the client side which I presume allows tripadvisor to retrieve your public information.
Tripadvisor doesn't really have to access your cookies or violate cross domain security measures, everything happens on the server side on the Facebook front. Once Facebook validates the origin of the request (i.e. making sure the domain belongs to one of its program partners), it serves the request with the needed data.
If you  try to access the URL outside tripadvisor's scope you get the following:

Further Readings:
1.3.2 Implicit Grant Flow from OAuth specification docs:

The implicit grant is a simplified authorization code flow optimized
for clients implemented in a browser using a scripting language such
as JavaScript.  In the implicit flow, instead of issuing the client
an authorization code, the client is issued an access token directly
(as the result of the resource owner authorization).  The grant type
is implicit as no intermediate credentials (such as an authorization
code) are issued (and later used to obtain an access token).

https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-28#page-8

A: I've a hunch this is closely related to OAuth - perhaps it automatically checks for a currently logged-in token and then initiates OAuth login.


text:
Q: Print HTML Table from an array with condition with Perl CGI i have made a script that returns me an array with several lines like :

DATA:VALUE:VALUE_MAX

I need to fill a table with those value like :
NAME |  Status
--------------------------
DATA |  OK/minor/warning...
.... |  .........
.... |  .........

with VALUE and VALUE_MAX i calculate the percent wich give me the status.
here is my code for print the table :
my @i = my_status();

print <<END;

Name
Status

END
my $inc = 0;
while (@i) {
my @temp = split /:/, @i[$inc];
my $name = $temp[0];
my $percent = ($temp[1] * $temp[2] / 100);
my $status = undef;
if ($percent <= 24 ) {
print "
";
$status = "Critical !";
}
elsif ($percent <= 49 ) {
print "
";
$status = "Danger !";
}
elsif ($percent <= 74 ) {
print "
";
$status = "Warning";
}
elsif ($percent <= 99 ) {
print "
";
$status = "Minor";
}
elsif ($percent == 100 ) {
print "
";
$status = "OK";
}
print "$name	";
print "$status	";
print "
";
$inc++;
}
print <<END;

END

My script "my_status" is a bit long to execute, it's full of server request...
but the thing is, on the HTML page, everything is a mess, i get wrong value, and an endless loop who print only "Critical !" in status colomns
what is wrong with my script ?

A: You are not iterating @i in your while loop. Your line
while (@i) {

means that it will stay in the loop as long as @i is true. Because that's an array, that means that as long as there are items in @i, it will stay in the loop.
You do not remove anything from @i inside of the loop. There are no shift or pop commands, and you also do not overwrite @i. So it will stay indefinitely. You've got yourself an infinite loop.

What you want instead is probably a foreach loop. Then you also don't need $inc. It will put each element inside of @i into $elem and run the loop.
foreach my $elem (@i) {
    my @temp    = split /:/, $elem;
    my $name    = $temp[0];
    my $percent = ( $temp[1] * $temp[2] / 100 );
    my $status  = undef;
    if ( $percent <= 24 ) {
        print "
";
        $status = "Critical !";
    }
    elsif ( $percent <= 49 ) {
        print "
";
        $status = "Danger !";
    }
    elsif ( $percent <= 74 ) {
        print "
";
        $status = "Warning";
    }
    elsif ( $percent <= 99 ) {
        print "
";
        $status = "Minor";
    }
    elsif ( $percent == 100 ) {
        print "
";
        $status = "OK";
    }
    print "$name	";
    print "$status	";
    print "
";
}

You can read up on loops in perlsyn starting from for loops.


text:
Q: RMDIR does not delete nested directories path greater than 255 length I am using below command inside the batch file and running via task scheduler in my server , it deletes most of the nested files/folders but when path length exceed 255 it does not delete those files/folders. Is this issue with RMDIR , What are other alternatives , Robocopy Delete ? Has somebody faced this issue and robocopy was able to solve this issue for them , something like below ?
RMDIR "Path-location" /S /Q -- Does not delete files/folder > 255 length

Robocopy : You need to create empty folder before executing below commands :
robocopy "C:\empty" "C:\Test Folder" /purge
rmdir "C:\Test Folder"  // Once all files/folders are deleted now remove your parent/root directory

A: This is normal behaviour. To be exact, the limit is defined as 260 characters (source). You have multiple options to circumvent this limit:

*

*You can raise this limit to 65535 characters by adding/setting the registry value HKLM:\SYSTEM\CurrentControlSet\Control\FileSystem\LongPathsEnabled of type REG_DWORD to 1. This works since Windows 10, version 1607 (read more). Reboot your machine after this change.

*You can use robocopy in combination with the /PURGE parameter to synchronize an empty folder to the folder that contains the long file paths as you already found out. This might get complicated if you do not want to delete everything, but only certain files.

*You can use UNC paths to describe long paths. Change
C:\very\long\...\path

to
\\?\C:\very\long\...\path


text:
Q: CPU usage increases when switching images I have created a QML component which simulates an "image slider" which displays different images indefinitely.
import QtQuick 2.3

Item {
    id: root

    // Start auto rotating items
    Timer {
        interval: 500; running: true; repeat: true
        onTriggered:{
            itemModel.append(itemModel.get(listView.currentIndex))
            itemModel.remove(listView.currentIndex)
        }
    }

    ListView {
        id: listView

        anchors.fill: parent

        interactive: false

        model: itemModel
        delegate:
            Image {
                id: bg
                width: listView.width
                height: listView.height
                source: bgSource

                asynchronous: true
                cache: false
            }
    }

    ListModel {
        id: itemModel
        ListElement {
            bgSource: "ui_elements/images/slideimage01.png"
        }
        ListElement {
            bgSource: "ui_elements/images/slideimage02.png"
        }
        ListElement {
            bgSource: "ui_elements/images/slideimage03.png"
        }
    }
}

Unfortunately the CPU usage keeps increasing over time until the application halts. If I print the "count" variable of itemModel it stays at 3 as expected.
I run the application like this: qmlscene SlideImageTest.qml.
Qt version: 5.3.2
The three images I use can be found here:

Question
Why does the CPU usage increase?

A: A quick profiling shows that most of the CPU cycles are spent in itemModel.get, trying to convert the internal model structure into a JavaScript object that you would right after move back to the model.
Overall modifying the model is also going to involve QtQuick Items creation and removal that don't seem necessary in this case.
A more efficient way to solve this would be to get the ListView to scroll to the next image instead of altering the model at the position currently highlighted in the ListView:
Timer {
    onTriggered:{
        listView.incrementCurrentIndex()
    }
}

ListView {
    id: listView
    keyNavigationWraps: true
    highlightMoveDuration: 0
    ...
}

If you really need to keep the model modification way, a C++ model would probably avoid the costly conversion to JavaScript.


text:
Q: Display a ContentDialog in UWP, using an ICommand with MVVM I'm creating a UWP application where I want a user to be able to upload photos. I have a ContentDialog with a Button and two TextBoxes. The  ContentDialog should pop up when the user presses the "Upload Photo" Button. How can I do this using MVVM?
The logic for finding the file and posting the files to the database are already done, only the UI is remaining.
Here is my XAML:
<!-- Content -->
<Button Content="Upload a photo to gallery" Margin="40,0,0,0" x:Name="UploadPhotoButton" Command="{x:Bind MyProfileViewModel.OpenContentDialog}"/>
<!-- More content -->

<!-- This is the ContentDialog I want to display when the user presses the button above -->
<ContentDialog x:Name="UploadPhotoContentDialog"
    PrimaryButtonText="Upload" IsPrimaryButtonEnabled="{Binding IsValid}"
    SecondaryButtonText="Cancel" IsSecondaryButtonEnabled="True">
    <ContentDialog.TitleTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <SymbolIcon Symbol="BrowsePhotos"/>
                <TextBlock Margin="10,0,0,0" Text="Upload photo "/>
            </StackPanel>
        </DataTemplate>
    </ContentDialog.TitleTemplate>

    <Grid Padding="10" Margin="0,10,0,0">
        <Grid.RowDefinitions>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="1*"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>

        <TextBlock Text="Photo Title:" VerticalAlignment="Center"/>
        <TextBox Text="{Binding PhotoTitle, Mode=TwoWay}" PlaceholderText="Example: Fun in the sun" Grid.Column="1"/>
        <TextBlock Text="Photo Caption:" Grid.Row="1" VerticalAlignment="Center"/>
        <TextBox Text="{Binding PhotoDesc, Mode=TwoWay}" PlaceholderText="Example: Don't you just love the beach" Grid.Row="1" Grid.Column="1"/>
        <Button Content="Browse files..." Grid.Column="0" Grid.Row="2" Margin="0,20,0,0" Command="{x:Bind MyProfileViewModel.FindFile}"/>
        <TextBox Text="{Binding FileName, Mode=TwoWay}" Grid.Row="2" Grid.Column="1" Margin="10,20,0,0" FontSize="12" Height="32" IsReadOnly="True" />
    </Grid>
</ContentDialog>

So far, here is my C# file (MyProfileViewModel):
public ICommand OpenContentDialog => new CommandHandler(async () => {
    //  What to put in here to find the ContentDialog, then display it?
});

A: One of the methods may bo to pass the ContentDialog as CommandParameter. For example like this:
<Button Content="Upload a photo to gallery" Margin="40,0,0,0" x:Name="UploadPhotoButton" Command="{x:Bind MyProfileViewModel.OpenContentDialog}" CommandParameter="{Binding ElementName=UploadPhotoContentDialog}"/>

and invokation:
public RelayCommand OpenContentDialog => new RelayCommand(async (dialog) => { (dialog as ContentDialog).ShowAsync(); });

A: I found the answer to my problem. I created a new Class that implements ICommand called RelayCommand, with input from Romasz.
His ViewModel and binding in the XAML was correct. I just had to adjust my ICommands. Here is my RelayCommand Class
public class RelayCommand : ICommand {
    private readonly Action<object> _execute;
    private readonly Func<bool> _canExecute;

    public event EventHandler CanExecuteChanged;

    public RelayCommand(Action<object> execute)
        : this(execute, null) {
    }

    public RelayCommand(Action<object> execute, Func<bool> canExecute) {
        _execute = execute ?? throw new ArgumentNullException("execute");
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter) {
        return _canExecute == null ? true : _canExecute();
    }

    public void Execute(object parameter) {
        _execute(parameter);
    }

    public void RaiseCanExecuteChanged() {
        CanExecuteChanged?.Invoke(this, EventArgs.Empty);
    }
}

I had to add <object> for the Action, since the ViewModel logic kept complaining that Action did not take a parameter.


text:
Q: Create parser with subcommands in argparse, customize positional argument(s) I'm very new to this module so please bear with me. I have the following code:
reader.py
import argparse

parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('filename', help='TXT file', type=file, nargs='+')
parent_parser.add_argument('--verbose', '-v', action='store_true',
        help="Verbosity on")

child_parser = parent_parser.add_subparsers(title="subcommand",
        help="Subcommand help")
new_file_command = child_parser.add_parser('new', help="New text file")
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")

args = parent_parser.parse_args()

What I'm trying to achieve might not be the standard way of how parsers and unix command line utilities work. If that is true, please correct me as I'd like to have standardized app.
This is what I'm trying to achieve:

*

*if you run bare script with positional argument(s) like this: python reader.py some.txt I'd like to be able to just parse it and pass it to function that reads the text file, of course I want to accept optional arg verbose as well

*if you run subcommand 'new' (new_file_command), I do not want to have positional argument filename to be required, instead I want to pass a string and create new text file like this: python reader.py new another.txt

*if you run subcommand 'edit' (edit_file_command) I want to pass existing file in path and check for it (like you use type=int in add_argument) and then maybe pass it to function that opens editor, something like this: python reader.py edit some.txt
Again, I'm not sure if this is how command line apps/scripts are supposed to behave. I read the docs and looked at examples but it's still isn't clear to me how sub parsers work. I tried looking at Click module but that seems to me even more complicated.
Any help appreciated. Thanks!

A: So three sample calls are:
python reader.py some.txt
python reader.py new another.txt
python reader.py edit some.txt

The easiest way to handle these is with one 'optional' positional, and one required one.
parser = ArgumentParser...
parser.add_argument('-v','--verbose', ...)
parser.add_argument('cmd', nargs='?', default='open', choices=['open','edit','new'])
parser.add_argument('filename')

For your 3 samples, it should produce something like:
namespace(cmd='open', filename='some.txt')
namespace(cmd='new', filename='another.txt')
namespace(cmd='edit', filename='some.txt')

cmd is an optional positional argument.  If it is missing, the one string will be allocated to filename, and cmd gets its default.  It's easier to do this than trying make a subparsers optional.

As for your current parser:
parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('filename', help='TXT file', type=file, nargs='+')

I would not recommend using type=file.  Better to use FileType or the default string (which lets you open the file in a with context later).
As to the nargs='+', do you really want to allocate 1 or more strings to filename?  Or were you thinking of '?', which would be 0 or 1, i.e. making it optional?
parent_parser.add_argument('--verbose', '-v', action='store_true',
        help="Verbosity on")

child_parser = parent_parser.add_subparsers(title="subcommand",
        help="Subcommand help")
new_file_command = child_parser.add_parser('new', help="New text file")
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")

Mixing this filename positional which accepts a variable number of values, with a subparsers argument (a positional that expects either new or edit) could be a problem.
I expect 'python reader.py some.txt' to object that the subparser command is missing.  'python reader.py new another.txt' will try to allocate new to filename, and another.txt to subparser, and raise an error.
It would be better to expect a subparsers command in all 3 cases:
parent_parser = argparse.ArgumentParser(description="Read text files.")
parent_parser.add_argument('--verbose', '-v', action='store_true',
        help="Verbosity on")
child_parser = parent_parser.add_subparsers(title="subcommand",
        help="Subcommand help", dest='cmd')
open_file_command = child_parser.add_parser('open', help="Open text file")
open_file_command.add_argument('filename', help='TXT file')
new_file_command = child_parser.add_parser('new', help="New text file")
new_file_command.add_argument('filename', help='TXT file')
edit_file_command = child_parser.add_parser('edit', help="Edit existing text file")
edit_file_command.add_argument('filename', help='TXT file')

Each of commands, 'open','new','edit', expects a 'filename'.
Trying to avoid the use of an open command is going to create more difficulties than it's worth.
(There is a bug/feature in the latest argparse that makes subparsers optional, but you shouldn't take advantage of that without really knowing the issues.)

With:
parser = argparse.ArgumentParser()
parser.add_argument('-v', '--verbose')
parser.add_argument('cmd', nargs='?', default='open',
    choices=['open', 'edit', 'new'])
parser.add_argument('filename', nargs='+')

I expect reader.py new customstring to give
namespace(cmd='new', filename=[customstring])

which could be used as:
if args.cmd=='new':
with open(args.filename[0] + '.txt', 'w') as f:
     # do something with the newly created file

open and edit would use different open modes.

Beware that in Py3, subparsers are not required.  That is, if one of the subcommands is not provided, it won't raise an error.  That's an inadvertent change from early versions.
Argparse with required subparser


text:
Q: How to access express route inside basicAuth My NodeJS server, using express, has a bunch of entries to specify various routes:
app.post('list_streams.json',    auth, stream_handler.list_streams);
app.post('add_stream.json',      auth, stream_handler.add_stream);
app.post('delete_stream.json',   auth, stream_handler.delete_stream);
etc...

The auth middleware is written like this:
var auth = express.basicAuth(function(user, pass, callback) {
    user_handler.authenticate_user(user, pass, callback);
});

Inside the user_handler.authenticate_user() function, an access to the database is performed to validate the user. I'd like to add some statistics and keep track of every access that a particular user performs. I'd like to do this inside the authenticate_user() function, as this is where a database is accessed for the user record and I can use the same access to update the statistics info in the user record, but I need to somehow pass an extra argument to the authenticate_user() specifying the type of access that was performed; either the route itself or some token that identifies the route being accessed. And I can't figure out how to do this. The 'req' is not available inside the authenticate_user() function.
Thank You,
Gary

A: I'm not sure what you need can be easily done from your authenticate_user function since it's only called once per session at the first access from any user.
The best approach to log ALL access per user would be to create a new middleware function as described at the end of this post.
But assuming you only wish to log user authentications, one way to solve your problem would be to replace express.basicAuth with your own version that binds the callback function to the express req object, like this:
var util=require('util'),
    express=require('express'),
    app=express(),
    auth=basicAuth(function(username,password,next){
        console.log('auth has access to req as "this": %s',util.inspect(this));
    });

app.get('/',auth,function(req,res){
    console.log('in request for "/", req is: %s',util.inspect(req));
    res.send('SUCCESS');
});

app.listen(4000,function(){
    console.log('running');
});

// Replacement for connect.basicAuth (as used by express)
// lifted from https://github.com/expressjs/basic-auth-connect

function unauthorized(res, realm) { // required by basicAuth
  res.statusCode = 401;
  res.setHeader('WWW-Authenticate', 'Basic realm="' + realm + '"');
  res.end('Unauthorized');
}

function error(code, msg){ // required by basicAuth
  var err = new Error(msg || http.STATUS_CODES[code]);
  err.status = code;
  return err;
}

// replacement basic auth which binds the callback to the "req" object
function basicAuth(callback, realm) {
  var username, password;

  // user / pass strings
  if ('string' == typeof callback) {
    username = callback;
    password = realm;
    if ('string' != typeof password) throw new Error('password argument required');
    realm = arguments[2];
    callback = function(user, pass){
      return user == username && pass == password;
    }
  }

  realm = realm || 'Authorization Required';

  return function(req, res, next) {
    var authorization = req.headers.authorization;

    // 20140601 RR - !!NOTE!! bind callback to req
    callback=callback.bind(req);

    if (req.user) return next();
    if (!authorization) return unauthorized(res, realm);

    var parts = authorization.split(' ');

    if (parts.length !== 2) return next(error(400));

    var scheme = parts[0]
      , credentials = new Buffer(parts[1], 'base64').toString()
      , index = credentials.indexOf(':');

    if ('Basic' != scheme || index < 0) return next(error(400));

    var user = credentials.slice(0, index)
      , pass = credentials.slice(index + 1);

    // async
    if (callback.length >= 3) {
      callback(user, pass, function(err, user){
        if (err || !user)  return unauthorized(res, realm);
        req.user = req.remoteUser = user;
        next();
      });
    // sync
    } else {
      if (callback(user, pass)) {
        req.user = req.remoteUser = user;
        next();
      } else {
        unauthorized(res, realm);
      }
    }
  }
}

If you look at the line marked with "!!NOTE!!" above, you'll see that the callback you pass to the new basicAuth function has been bound to express' req request object, which makes its idea of this a reference to the request.
Now all you need to do is reference this.url to get the original request URL and log it.
As mentioned above, one thing to note is that the callback to auth is only called to authenticate the user once.
Subsequent requests already have the req.user HTTP header variable set, so the request is allowed to pass without calling the authentication callback.
This is why the best way to log all interactions for a particular user would be to add your own middleware after the call to auth, such as:
function logUser(req,res,next){

   // since this middleware is called AFTER auth, the user is already authorized.
   log.info('user "'+req.user+'" called url:'+req.url);

   next(); // pass control to the next stage in fulfilling the request
}

app.get('/',auth,logUser,function(req,res){
    ...
});


text:
Q: When is the supremum\infimum an accumulation point? Trying to show that if a sequence converges, it either has a maximum, a minimum or both, I reached a dead-end. Assuming it is not constant, it is still bounded and its supremum and infimum aren't equal. Then I assumed that the supremum and infimum are not in the sequence.
I want to show that there are two subsequences that converge to each of them but for that to happen I have to show they are accumulation points. I tried to use definition but failed. I know logically that following my assumption they have to be accumulation points but I can't derive it from the definitions. Any help?

A: I assume we are working in $\Bbb R$. Let $A$ be a non-empty, bounded set.  $\sup A$ is uniquely defined as the number $\alpha$ such that for all $a\in A$, $a\le\alpha$, and if $\beta<\alpha$ there is an $a\in A$ such that $\beta<a<\alpha$.  You should be able to use the second statement to show that $\sup A$ is an accumulation point of $A$.

A: Consider the sequence $\{\mathbf{x}_n\}_{n\in\mathbb{N}} \subseteq A$, where $A \subseteq \mathbb{R}^n$. If this sequence is convergent, then it is bounded. Also, the sequence must converge to $\mathbf{x} \in \overline{A}$. Show that for all $\epsilon > 0$, there are finitely many $\mathbf{x}_n \notin N(\mathbf{x}, \epsilon) \cap A$ where $N(\mathbf{x},\epsilon)$ is some neighborhood of $\mathbf{x}$. Then, use the fact that a finite set is bounded and that $N(\mathbf{x}, \epsilon_0) \cap A$ is bounded for some $\epsilon_0$ to prove your claim.


text:
Q: Create Image from imageview and textview? I'm making an app that will allow the user to add a photo to an imageview from the gallery of their phone which I have already been able to code successfully. I now want to be able to allow the user to add text on top of the photo and then save the text and image as one back into the gallery. Is there any way to do this?
XML:
  <LinearLayout
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:orientation="vertical"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <ImageView android:id="@+id/image" android:layout_height="400dp" android:layout_width="fill_parent"/>
    <LinearLayout
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:orientation="horizontal">
        <Button
            android:id="@+id/chooseimage"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:text="Choose Image"/>
        <Button
            android:id="@+id/addtext"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:text="Add Text"/>
        <Button
            android:id="@+id/save"
            android:layout_height="fill_parent"
            android:layout_weight="1"
            android:layout_width="fill_parent"
            android:text="Save"/>
    </LinearLayout>
</LinearLayout>

Member.java
public class MemberActivity extends Activity implements OnClickListener {
    /**
     * Called when the activity is first created.
     */

    private static final int SELECT_IMAGE = 1;
    Button openGallery;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.design);
        openGallery = (Button) findViewById(R.id.chooseimage);
        openGallery.setOnClickListener(this);

    }

    public void onClick(View v) {
        // TODO Auto-generated method stub
        switch (v.getId()) {
            case R.id.chooseimage:
                Intent gallery = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI);
                startActivityForResult(gallery, SELECT_IMAGE);
                break;
            default:
                break;
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK && requestCode == SELECT_IMAGE) {
            Uri selectedImage = data.getData();
            String path = getPath(selectedImage);
            Bitmap bitmapImage = BitmapFactory.decodeFile(path);
            ImageView image = (ImageView) findViewById(R.id.image);
            image.setImageBitmap(bitmapImage);
        }
    }

    public String getPath(Uri uri) {
        String[] filePathColumn = {MediaStore.Images.Media.DATA};

        Cursor cursor = getContentResolver().query(uri, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);

        return cursor.getString(columnIndex);
    }
}

A: Yes there is a way to do this,
You can create an Bitmap of any view using buildDrawingCache() and getDrawingCache()
TextView tv = (TextView)findViewById(R.id.textview);
tv.buildDrawingCache();
ImageView img = (ImageView)findViewById(R.id.imageview);
img.setImageBitmap(tv.getDrawingCache());

You can also check this answer for further reference.

A: *

*create a Canvas based on a mutable Bitmap

*draw the Bitmap you have in there

*draw text on top

*save the Bitmap as image.

A: You can also use TextView instead of ImageView and set image as background to TextView.And after you can also add text to TextView.
Save the all the texts to somewhere and on showing again Gallery again use the texts you save with the images.

A: try this:
 TextView tv1 = new TextView(this);
 LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(80, 100);
    tv1.setLayoutParams(layoutParams);
    tv1.setText("testing 1 2 3");
    tv1.setTextColor(Color.BLACK);
    tv1.setBackgroundColor(Color.TRANSPARENT);

add to it on button click with your layout-->your layout reference and then
.addview(tv1);


text:
Q: Flutter iOS Build Error: framework not found Flutter I am able to run the app in android studios but whenever I try in xcode I get a flutter framework not found.

A: upgrade your flutter by doing
flutter upgrade

and it will upgrade the engine and download necessary tools.
This will even kill flutter daemons.
And run the application again
flutter run

A: *

*Make sure you open .xcworkspace (and not .xcodeproj in XCode).

*Ensure you have 'Flutter.Framework' listed under "Linked Frameworks and Libraries". If not, just drag and drop it from the main project. Like below

A: I was facing the same error whene I try to archive in Xcode
I fixed it by
flutter upgrade

and
flutter run

A: I fixed this by switching to the master channel, and switching back to the stable channel. Also remember to run 'flutter upgrade' after switching.

A: *

*Delete the flutter directory.

*Download new flutter

*Extract it and put it where you want.

*Run the command export PATH="$PATH:`pwd`/flutter/bin"
if the command does not work then specify your path like bellow
export PATH="$PATH: /Users/{your user name}/Documents/src/flutter/bin"
Restart your machine and you are ready to go.
After that - inside your project's ios directory -

*

*delete the .symlink directory

*delete the Pods directory

*delete the Podfile.lock file

and now run -

*

*flutter clean

*flutter packages upgrade

*flutter build ios

A: For me nothing worked except, deleting my flutter files fully and reinstalling.
Use this flutter docs for reinstallation: Flutter Installation Link

A: I tried everything nothing worked except:-
Flutter upgrade
Flutter run
and boom- Build succeeded!

A: Please try the following steps:

*

*Delete the flutter SDK

*Download the same flutter SDK and re-install it

*restart the android studio
It should be worked well.

A: Fixed by switching branches from beta to master


text:
Q: Clone Object Javascript applying to all and I trying to clone an object with Object assing.

const defaults = {
   a: [],
   b: [],
   c: [],
   d: [],
   e: [],
   f: [],
   g: []
};

this.rowSetSlug = Object.assign({},defaults);
this.rowSetObject = Object.assign({},defaults);
this.rowSetModified = Object.assign({},defaults);

But when I fill one object like

this.rowSetObject.push(object);

And do a console.log()
console.log(this.rowSetObject);
console.log(this.rowSetModified);
console.log(this.rowSetSlug);

All same have the rowSetObject items, and if i fill another they replicate.
Thanks


text:
Q: Generate a range of records depending on from-to dates I have a table of records like this:

Item
From
To

A
2018-01-03
2018-03-16

B
2021-05-25
2021-11-10

The output of select should look like:

Item
Month
Year

A
01
2018

A
02
2018

A
03
2018

B
05
2021

B
06
2021

B
07
2021

B
08
2021

Also the range should not exceed the current month. In example above we are asuming current day is 2021-08-01.
I am trying to do something similar to THIS with CONNECT BY LEVEL but as soon as I also select my table next to dual and try to order the records the selection never completes. I also have to join few other tables to the selection but I don't think that would make a difference.
I would very much appreciate your help.

A: Row generator it is, but not as you did it; most probably you're missing lines #11 - 16 in my query (or their alternative).
SQL> with test (item, date_from, date_to) as
  2    -- sample data
  3    (select 'A', date '2018-01-03', date '2018-03-16' from dual union all
  4     select 'B', date '2021-05-25', date '2021-11-10' from dual
  5    )
  6  -- query that returns desired result
  7  select item,
  8         extract(month from (add_months(date_from, column_value - 1))) month,
  9         extract(year  from (add_months(date_from, column_value - 1))) year
 10  from test cross join
 11    table(cast(multiset
 12      (select level
 13       from dual
 14       connect by level <=
 15         months_between(trunc(least(sysdate, date_to), 'mm'), trunc(date_from, 'mm')) + 1
 16      ) as sys.odcinumberlist))
 17  order by item, year, month;

ITEM       MONTH       YEAR
----- ---------- ----------
A              1       2018
A              2       2018
A              3       2018
B              5       2021
B              6       2021
B              7       2021
B              8       2021

7 rows selected.

SQL>

A: Recursive CTEs are the standard SQL approach to this type of problem.  In Oracle, this looks like:
with cte(item, fromd, tod) as (
      select item, fromd, tod
      from t
      union all
      select item, add_months(fromd, 1), tod
      from cte
      where add_months(fromd, 1) < last_day(tod)
     )
select item, extract(year from fromd) as year, extract(month from fromd) as month
from cte
order by item, fromd;

Here is a db<>fiddle.


text: Q: Can a star emits laser? I know if I pump enough energy to a bunch of electrons so that they are all in their excited states, then I can introduce some photons to start off a chain reaction resulting in simulated emission. Can a star do so too?


text:
Q: Run Spark executors as specified Linux user I have a spark standalone cluster having 5 nodes. All nodes have mounted the same volume via nfs. Files within these mount have certain linux file permission.
When I Spark-submit my Job as user x (who is available on all nodes and has on all nodes the same uid) then I want that the spark executors also run as user x so that the job can only access files user x has permissions to.
I don't have Kerberos and I don't have HDFS.
Is this possible in this setup?
Would it help to use YARN?

A: As someone who as been playing a lot with Spark Standalone, Yarn, HDFS and so on.
Here's what my experience told me:

*

*Spark Standalone has absolutly no form of access control or regulation possible.

*Yarn without HDFS is possible but your job will always run as Yarn, if you write files to something else than HDFS the files will be owned by yarn user.

*Kerberos is not a solution to that kind of usage, HDFS/yarn works hand in hand and if you run a job as spark with kerberos and write in HDFS the files will belong to spark.  If you do the same with NFS or any other distributed file system files will belong to the system user used to run Yarn.

*Finally you might be able to mitigate some issues with Ranger or Livy but files written outside of HDFS will belong to the system user that write them.

My conclusion to such a problem is that HDFS is the centre piece of all the Hadoop ecosystem and not using it is problematic.
It kinda s**** somehow as HDFS is really complex to maintain compared to NFS.


text:
Q: How to connecth VM with Host while using VPN on host machine I'm trying to connect Virtual Machine with Host (I use VMWARE) while using VPN in host machine.
When the VPN is off, I can ping my network adapters, it works fine. As soon as I turn VPN ON  I can't ping adapters and other devices from one system to another. I use cisco VPN which gives me access to my company network which I need on VM, but I can't have the VPN on VM(company is blocking :<).
I use NAT type of network.
Is it even possible to run VPN on host, have the VPN network on VM, and still have a connection HOST - VM so I can share data between network devices?


text:
Q: Why the TypeError: Cannot read property '0' of undefined? I am pulling data from woocommerce.
Which I have defined as so in my render():
const product2 = this.state.products2;
Now I want to target a particular value in this returned object as such:
const defaultLace = product2.default_attributes[0].option
However, the above renders a Type Error but const defaultLace = product.default_attributes; does not render an error and in the console I can see the data similar in this way;
      default_attributes: [
        {
          id: 0,
          name: "Lace",
          option: "Closure"
        }
      ]

What is happening here that this const defaultLace = product2.default_attributes[0].option renders an error?
Any help?
---EDIT----
broken code replication: XXXX

A: This code is OK.
But when you retrive data from remote server you must check that data exist and are in your structure.
When you use
const defaultLace = product2.default_attributes[0].option

you must check data as:
if(product2 && product2.default_attributes && Array.isArray(product2.default_attributes) && product2.default_attributes.length > 0) {
    const defaultLace = product2.default_attributes[0].option
} else {
   throw new Error('Bad data');
}

A: products2 is initially an empty array before the request has finished, so accessing products2.default_attributes will give undefined, and trying to access [0] on that will give rise to your error.
You could wait with the rendering until the products2 array has been filled with data.
Example
render() {
  const product2 = this.state.products2;

  if (product2.length === 0) {
    return null;
  }

  const productSize = product2[0].default_attributes[0].option;

  return (

{productSize}

  );
}


text:
Q: Movilizer - Eclipse doesn't find class 'OutlineLabelProvider' I installed the movilizer plug-in, but whenever I try to make a movelet, I get the same error:
Could not initialize class
com.movilizer.eclipse.editor.outline.OutlineLabelProvider
Thread=Thread[ModalContext,6,main]
at com.movilitas.jaxbframework.dataaccess.jaxb.AbstractJaxbDAL.parseXML(AbstractJaxbDAL.java:162)
at com.movilizer.eclipse.editor.actions.MovilizerRequestEditorActionExecuteDelegate$1.run(MovilizerRequestEditorActionExecuteDelegate.java:169)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)
Caused by: org.jibx.runtime.JiBXException: No unmarshaller for element "{http://movilitas.com/movilizer/v15}MovilizerRequest" (line 3, col 71)
at org.jibx.runtime.impl.UnmarshallingContext.unmarshalElement(UnmarshallingContext.java:2754)
at org.jibx.runtime.impl.UnmarshallingContext.unmarshalDocument(UnmarshallingContext.java:2914)
at com.movilitas.jaxbframework.dataaccess.jaxb.AbstractJaxbDAL.parseXML(AbstractJaxbDAL.java:157)
... 2 more

A: For Eclipse Neon, use the https://devtools.movilizer.com/eclipseUpdateSite46 update site.
For older Eclipse versions, use the https://devtools.movilizer.com/eclipseUpdateSiteDev update site.
If installation from the correctly corresponding update site does not solve the problem, you work around the problem by closing the Outline view in Eclipse.
https://help.eclipse.org/neon/index.jsp?topic=%2Forg.eclipse.platform.doc.user%2Fconcepts%2Fcoutline.htm


text:
Q: Are these definitions of a continuous random variable equivalent? In a textbook I'm reading:

A random variable $X$ is continuous if there exists a function $f_X$ such that $f_X(x) \ge 0$ for all $x$, $\int_\infty^\infty f_X(x) dx = 1$ and for every $a \le b$,
$$
\mathbb{P}(a < X < b) = \int_a^b f_X(x)dx.
$$

This is different than the definition provided for on Wikipedia, which seems to define a continuous random variable $X$ as any random variable with an uncountably infinite range.

*

*Are these two definitions equivalent?

*Does it matter if the left-side of the equition above uses $\le$ instead of $<$? That is do we have the following:

$$
\mathbb{P}(a < X < b) = \int_a^b f_X(x)dx = \mathbb{P}(a \le X \le b)?
$$
Edit: Wikipedia link on random variables. Here is the quote:

If the image is uncountably infinite then $X$  is called a continuous random variable.

A: First, some references would prefer the term "absolutely continuous" for what you are calling continuous. They would instead use the word "continuous" to refer to r.v.s whose CDF is continuous; the Cantor distribution is "continuous" in this sense but not in your sense.
At any rate, there are r.v.s with uncountably infinite range that are not even continuous in this weaker sense. For instance you can have $X=B U + 1-B$, where $B$ is Bernoulli(1/2), $U$ is uniform on $(0,1)$, and the two are independent. Then $X$ can take on any value between $0$ and $1$ but its CDF is not continuous at $1$.
As for your second question, $<$ vs. $\leq$ does not matter because in this situation single points have probability zero.

A: *

*These two definitions are equivalent.

*It doesn't matter whether $<$ or $\leq$ is used in a continuous distribution, because continuous distributions have no mass on any one point. (e.g. $Pr(x=k)=0$ in a continuous case)


text:
Q: Tag Manager to two ga properties I have implemented Google enhanced Ecommerce Via GTM for GA Property (New), keeping the old classic analytics code in the webiste, Now I removed the old classic code and pushing the events data from the same GTM account to (old) GA property (Replicated the Tags with different GA Property, Reference url : http://www.kristaseiden.com/step-by-step-adding-a-second-ga-property-via-google-tag-manager/).
The first GA property transactions are used to track properly, But after adding another GA property the transactions and all other events are not tracking accurately. In both the accounts Transactions are dropped to 50 percent.
Could someone help me. Thanks in advance.

A: You can create a custom JS variable:
function() {
  var newTrackingId = 'UA-XXXXXX-XX'; // Replace here
  var globalSendTaskName = '_' + newTrackingId + '_originalSendTask';
  return function(customModel) {
    window[globalSendTaskName] = window[globalSendTaskName] || customModel.get('sendHitTask');
    customModel.set('sendHitTask', function(sendModel) {
      var hitPayload = sendModel.get('hitPayload');
      var trackingId = new RegExp(sendModel.get('trackingId'), 'gi');
      window[globalSendTaskName](sendModel);
      sendModel.set('hitPayload', hitPayload.replace(trackingId, newTrackingId), true);
      window[globalSendTaskName](sendModel);
    });
  };
}

And then add this as a custom task on fields to set:

Hope it helps!
PS: Here is a more detail post from Simo Ahava.


text:
Q: Drag
* between two
* JS (without jQuery) I am trying to build two ul in JS and HTML and drag li between them. (task to it without using jQuery)  I pretty sure that I do something wrong in
function handleDrop(e)  OR I need to rewrite all.

Hope for your help
this is a code that I have.
HTML

A

B

C

D

E

Ad

Bd

Cd

Dd

Ed

AND JS

A: You should remove the dragged element from its parent. And not from the elemet that triggered the drop event. Below is the code. Have a look and let me know if this is what you wanted.

var dragSrcEl = null;

function handleDragStart(e) {
  // Target (this) element is the source node.
  dragSrcEl = this;

  e.dataTransfer.effectAllowed = 'move';
  e.dataTransfer.setData('text/html', this.outerHTML);

  this.classList.add('dragElem');
}
function handleDragOver(e) {
  if (e.preventDefault) {
    e.preventDefault(); // Necessary. Allows us to drop.
  }
  this.classList.add('over');

  e.dataTransfer.dropEffect = 'move';  // See the section on the DataTransfer object.

  return false;
}

function handleDragEnter(e) {
     //console.log('handleDragEnter');
        e.preventDefault();

  // this / e.target is the current hover target.
}

function handleDragLeave(e) {
  this.classList.remove('over');  // this / e.target is previous target element.
}

function handleDrop(e) {
  // this/e.target is current target element.
  if (e.stopPropagation) {
    e.stopPropagation(); // Stops some browsers from redirecting.
  }

  // Don't do anything if dropping the same column we're dragging.
  if (dragSrcEl != this) {
    // Set the source column's HTML to the HTML of the column we dropped on.
    //alert(this.outerHTML);
    //dragSrcEl.innerHTML = this.innerHTML;
    //this.innerHTML = e.dataTransfer.getData('text/html');
    dragSrcEl.parentNode.removeChild(dragSrcEl);
    var dropHTML = e.dataTransfer.getData('text/html');
    this.insertAdjacentHTML('beforebegin',dropHTML);
    var dropElem = this.previousSibling;
    addDnDHandlers(dropElem);

  }
  this.classList.remove('over');
  return false;
}

function handleDragEnd(e) {
  // this/e.target is the source node.
  this.classList.remove('over');

  /*[].forEach.call(cols, function (col) {
    col.classList.remove('over');
  });*/
}

function addDnDHandlers(elem) {
  elem.addEventListener('dragstart', handleDragStart, false);
  elem.addEventListener('dragenter', handleDragEnter, false)
  elem.addEventListener('dragover', handleDragOver, false);
  elem.addEventListener('dragleave', handleDragLeave, false);
  elem.addEventListener('drop', handleDrop, false);
  elem.addEventListener('dragend', handleDragEnd, false);

}

var cols = document.querySelectorAll('#columns .column');
[].forEach.call(cols, addDnDHandlers);

var cols_1 = document.querySelectorAll('#columns_1 .column');
[].forEach.call(cols_1, addDnDHandlers);

A

B

C

D

E

Ad

Bd

Cd

Dd

Ed

Hope this helps :)


text:
Q: How was the structure of DNA deduced using X-ray crystallography The determination of DNA's double helix structure by Watson, Crick, and co-workers using X-ray crystallography is a well-known milestone in the development of biology. My question is, what was the mathematical model employed by them to deduce the value of the relevant parameters, including r (radius of the helix, 1nm), d (length of each pitch, 3.4nm), and n (number of base pairs in each helix, 10)?
I heard one (toy) model which treated the two strands of the DNA as two parallel diffraction gratings, but, interesting though it was, this model was at best qualitative.


text:
Q: How to link with binary using mingw32 in wine I have made this minimal project to reproduce my link problem using mingw32 in wine32:
CMakeLists.txt
cmake_minimum_required(VERSION 3.13)
set(CMAKE_CXX_STANDARD_REQUIRED ON)

project("tst" VERSION 1.1.0)

add_executable("tst" "main.cpp")

add_library("resource" "text.o")
set_target_properties("resource" PROPERTIES LINKER_LANGUAGE CXX)
add_custom_command(OUTPUT "text.o"
    MAIN_DEPENDENCY "text"
    COMMAND ${CMAKE_COMMAND} -E copy "${CMAKE_CURRENT_SOURCE_DIR}/text" "text"
    COMMAND ${CMAKE_LINKER} -r -b binary "text" -o "text.o"
)
set_source_files_properties("text" PROPERTIES GENERATED true EXTERNAL_OBJECT true)

target_link_libraries("tst" "resource")

main.cpp
#include <iostream>
#include <string>

extern char _binary_text_start[];
extern char _binary_text_end[];

int main()
{
    std::string text{ _binary_text_start, _binary_text_end };
    std::cout << text << std::endl;
}

text
Hello, World!

This project builds and runs using mingw-w64 on Linux; however, when I try to build the project in wine32, I got this output:
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -SZ:\var\cache\deploy\cpp -BZ:\var\cache\deploy\cpp\build\windows --check-build-system CMakeFiles\Makefile.cmake 0
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E cmake_progress_start Z:\var\cache\deploy\cpp\build\windows\CMakeFiles Z:\var\cache\deploy\cpp\build\windows\\CMakeFiles\progress.marks
mingw32-make  -f CMakeFiles\Makefile2 all
mingw32-make[1]: Entering directory `Z:/var/cache/deploy/cpp/build/windows'
mingw32-make  -f CMakeFiles\resource.dir\build.make CMakeFiles/resource.dir/depend
mingw32-make[2]: Entering directory `Z:/var/cache/deploy/cpp/build/windows'
[ 25%] Generating text.o
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E copy Z:/var/cache/deploy/cpp/text text
Z:\mingw32\bin\ld.exe -r -b binary text -o text.o
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E cmake_depends "MinGW Makefiles" Z:\var\cache\deploy\cpp Z:\var\cache\deploy\cpp Z:\var\cache\deploy\cpp\build\windows Z:\var\cache\deploy\cpp\build\windows Z:\var\cache\deploy\cpp\build\windows\CMakeFiles\resource.dir\DependInfo.cmake --color=
mingw32-make[2]: Leaving directory `Z:/var/cache/deploy/cpp/build/windows'
mingw32-make  -f CMakeFiles\resource.dir\build.make CMakeFiles/resource.dir/build
mingw32-make[2]: Entering directory `Z:/var/cache/deploy/cpp/build/windows'
[ 50%] Linking CXX static library libresource.a
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -P CMakeFiles\resource.dir\cmake_clean_target.cmake
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E cmake_link_script CMakeFiles\resource.dir\link.txt --verbose=1
Z:\mingw32\bin\ar.exe qc libresource.a text.o
Z:\mingw32\bin\ranlib.exe libresource.a
mingw32-make[2]: Leaving directory `Z:/var/cache/deploy/cpp/build/windows'
[ 50%] Built target resource
mingw32-make  -f CMakeFiles\tst.dir\build.make CMakeFiles/tst.dir/depend
mingw32-make[2]: Entering directory `Z:/var/cache/deploy/cpp/build/windows'
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E cmake_depends "MinGW Makefiles" Z:\var\cache\deploy\cpp Z:\var\cache\deploy\cpp Z:\var\cache\deploy\cpp\build\windows Z:\var\cache\deploy\cpp\build\windows Z:\var\cache\deploy\cpp\build\windows\CMakeFiles\tst.dir\DependInfo.cmake --color=
mingw32-make[2]: Leaving directory `Z:/var/cache/deploy/cpp/build/windows'
mingw32-make  -f CMakeFiles\tst.dir\build.make CMakeFiles/tst.dir/build
mingw32-make[2]: Entering directory `Z:/var/cache/deploy/cpp/build/windows'
[ 75%] Building CXX object CMakeFiles/tst.dir/main.cpp.obj
Z:\mingw32\bin\g++.exe   -O3 -DNDEBUG -o CMakeFiles\tst.dir\main.cpp.obj -c Z:\var\cache\deploy\cpp\main.cpp
[100%] Linking CXX executable tst.exe
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E cmake_link_script CMakeFiles\tst.dir\link.txt --verbose=1
Z:\cmake-3.19.1-win32-x86\bin\cmake.exe -E rm -f CMakeFiles\tst.dir/objects.a
Z:\mingw32\bin\ar.exe cr CMakeFiles\tst.dir/objects.a @CMakeFiles\tst.dir\objects1.rsp
Z:\mingw32\bin\g++.exe -O3 -DNDEBUG -Wl,--whole-archive CMakeFiles\tst.dir/objects.a -Wl,--no-whole-archive -o tst.exe -Wl,--out-implib,libtst.dll.a -Wl,--major-image-version,0,--minor-image-version,0 @CMakeFiles\tst.dir\linklibs.rsp
z:/mingw32/bin/../lib/gcc/i686-w64-mingw32/10.2.0/../../../../i686-w64-mingw32/bin/ld.exe: CMakeFiles\tst.dir/objects.a(main.cpp.obj):main.cpp:(.text.startup+0x43): undefined reference to `_binary_text_end'
z:/mingw32/bin/../lib/gcc/i686-w64-mingw32/10.2.0/../../../../i686-w64-mingw32/bin/ld.exe: CMakeFiles\tst.dir/objects.a(main.cpp.obj):main.cpp:(.text.startup+0x48): undefined reference to `_binary_text_start'
z:/mingw32/bin/../lib/gcc/i686-w64-mingw32/10.2.0/../../../../i686-w64-mingw32/bin/ld.exe: CMakeFiles\tst.dir/objects.a(main.cpp.obj):main.cpp:(.text.startup+0x68): undefined reference to `_binary_text_start'
z:/mingw32/bin/../lib/gcc/i686-w64-mingw32/10.2.0/../../../../i686-w64-mingw32/bin/ld.exe: CMakeFiles\tst.dir/objects.a(main.cpp.obj):main.cpp:(.text.startup+0x16f): undefined reference to `_binary_text_start'
collect2.exe: error: ld returned 1 exit status
mingw32-make[2]: *** [tst.exe] Error 1
mingw32-make[2]: Leaving directory `Z:/var/cache/deploy/cpp/build/windows'
mingw32-make[1]: *** [CMakeFiles/tst.dir/all] Error 2
mingw32-make[1]: Leaving directory `Z:/var/cache/deploy/cpp/build/windows'
mingw32-make: *** [all] Error 2

nm libresource.a
text.o:
0000000d D _binary_text_end
0000000d A _binary_text_size
00000000 D _binary_text_start

objdump -f libresource.a
In archive libresource.a:

text.o:     file format pe-i386
architecture: i386, flags 0x00000038:
HAS_DEBUG, HAS_SYMS, HAS_LOCALS
start address 0x00000000

cmake: https://github.com/Kitware/CMake/releases/download/v3.19.1/cmake-3.19.1-win32-x86.zip
mingw: https://pilotfiber.dl.sourceforge.net/project/mingw-w64/Toolchains%20targetting%20Win32/Personal%20Builds/ray_linn/GCC-10.x-with-ada/mingw32-10.2.0-crt-8.0.0-with-ada.7z
mingw-make: https://phoenixnap.dl.sourceforge.net/project/mingw/MinGW/Extension/make/mingw32-make-3.80-3/mingw32-make-3.80.0-3.tar.gz


text:
Q: Show Username on Windows Form I have an MSI package which gets launched from a website. This MSI package is a winform application acting like a WebAPI which receives Ajax request from the website.
I want to show the Username of the user logged in the website, as the title bar of the launched winform application (say e.g. in Visual Studio, where the logged in user name is shown above the top right corner).
I have come to know that this can be achieved via ADFS etc., but I am new to that.
So any recommended approaches/examples or ways to achieve the above?.
Thanks In Advance!!!..

A: If you want to authenticate via ADFS, you need to setup an ADFS claims rule to pass "Display Name" as a claim in the token.
When you receive the token, extract the value of this claim and display it.


text:
Q: jQuery hover first and hover second When I hover on the first, then it will show Second.
If I then hover to Second, Second shall remain show, else hide Second.
My problem is in between hover first and hover Second it get too fast hiding the Second.
How do I delay the $(".second").hide("slow" ); before I hover to second?
  $(".first").hover(
    function(){
      $(".second").show();
    },
    function(){
      $(".second").hide("slow" );
    }
  );

 $(".second").hover(
   function(){
     $(".second").show();
   },
   function(){
    $(".second").hide("slow" );
   }
 );

A: The solution is to use a timer using setTimeout()
var $second = $(".second");
$(".first").hover(function () {
    clearTimeout($second.data('timer'));
    $second.stop(true, true).show();
}, function () {
    var timer = setTimeout(function () {
        $second.stop(true, true).hide("slow");
    }, 200);
    $second.data('timer', timer);
});

$(".second").hover(function () {
    clearTimeout($second.data('timer'))
    $second.stop(true, true).show();
}, function () {
    $second.stop(true, true).hide("slow");
});

Demo: Fiddle

A: $( "#clickme" ).click(function() {
$( "#book" ).hide( "slow", function() {
alert( "Animation complete." );
});
});


text:
Q: how hide loading image when load jquery done i have this jquery code
else if ($(this).val() === "5") {
        var codefaqs = $(this).val();
        $('#imgloadfaqs').show();
        $("#faqsmain").attr("disabled", "disabled");
        $('#faqsanswer').load('http://royta.org/somefolder/get.php',{codedgive:codefaqs},function(applycode){
            $('#faqsanswer').html(applycode);
            $('#imgloadfaqs').hide(2000);
            $("#faqsmain").removeAttr("disabled");
        });
    }

and show loading image and disable select box
i want when get.php do its work and done to send resault
loading image gone
but with this code its gone very soon before php show resault
can anyone help me with this?

A: move hide method inside function where you are getting result from php file as :
...,codedgive:codefaqs},function(applycode){
            $('#faqsanswer').html(applycode);
            $("#faqsmain").removeAttr("disabled");
            $('#imgloadfaqs').hide(500);
        });

A: try putting the code that hides the image inside the done function. I believe this would be the right approach:
$('#faqsanswer').load('http://royta.org/module/faqs/get.php',{codedgive:codefaqs},function(applycode){
        $('#faqsanswer').html(applycode);
        $("#faqsmain").removeAttr("disabled");
        $('#imgloadfaqs').hide(500);
    });

A: Use following code snippet to show and hide.
    $(document).ready(function() {

// Setup the ajax indicator

$('body').append('

');

$('#ajaxBusy').css({

display:"none",

margin:"0px",

paddingLeft:"0px",

paddingRight:"0px",

paddingTop:"0px",

paddingBottom:"0px",

position:"absolute",

right:"3px",

top:"3px",

width:"auto"

});

});

// Ajax activity indicator bound to ajax start/stop document events

$(document).ajaxStart(function(){

$('#ajaxBusy').show();

}).ajaxStop(function(){

$('#ajaxBusy').hide();

});

To read more about the same follow http://skfox.com/2008/04/28/jquery-example-ajax-activity-indicator/
if you use this approach on all ajax request you will get spinning image, so you do not need to code for all request and it will lead to save extra efforts.
For working example follow jsfiddle link http://jsfiddle.net/re57j/


text:
Q: Not able to find Windows.IdentityModel for windows 10 store app development Is this dll not compatible with windows store app, Or is there any other way to achieve the same.
I tried adding it from nuget package also but not happening, I am getting this error:
"Severity   Code    Description Project File    Line    Suppression State
Error       Package restore failed. Rolling back package changes for 'Solution'."

A: As far as I'm concerned, you need to intall the Windows Identity Foundation as well as the WIF SDK and then restart the application for the effect to work.
For Windows 10 device, Windows Identity foundation is not an istall but a Windows feature need to be enabled.

*

*Enter Control Panel from Start menu

*Click program and features

*Choose turn Windows feature on or off

*Choose Winodws Identity Framework, click OK

*Restart your machine

A similar question here that could be helpful to you. As Moory said in the comment, he fixed this issue by adding the reference below to the csproj file:: ( .
Please also try it. Thank you.


text:
Q: Multiple Intermittent Errors with Seemingly Simply Graphics Method C# I have a simple method that analyzes a sample image in a pictureBox and increases the value of the Red channel.  Similar other methods analyze other color channels.  The user is given the option of choosing the sample image containing the desired color changes and applying it to their original image.
Everything was working fine until I added a trackBar to enable the user to change how much Red, Green, or Blue they'd like to add to or subtract from their sample image.  Now, everything sometimes works fine on the first run. I was getting a "Cross-thread operation not valid" error, but I seem to have resolved that.  After first run, pictureBox1 often dissapears at random and is replaced by the dreaded red X.  Other times, pictureBox1 has its color changes applied at full power, regardless of the trackBar setting.  Other times, I get an error stating "Object is currently in use elsewhere."  I have, to the best of my understanding of the concept, tried locking the code that errors out, but this has had no effect. I have very thoroughly researched these problems both here and elsewhere, but found no solutions (other than those I have already implemented). Code follows:
EDIT: FWIW, I just got a rare "Object is not set to an instance of an object" error, in regard to int y. I was unable to recreate it. Also, I'm curious, when I'm running multiple methods such as red(), green(), and blue(), is there a preferred way to run them (other than running them from, for example, a pictureBox click)?
My primary problems continue to be the intermittent red X in pictureBox1, and the intermittent but frequent "Object is currently in use elsewhere." error. Thank you very much.
    private object lockObject = new object();

    private void red()
    {
            // declare initial variables
            int xRed = 64;

            // Work around for "Cross-thread operation not valid" error.  This may be a VS issue, not an actual coding error.
            if (trkColor.InvokeRequired)
                trkColor.Invoke(new MethodInvoker(delegate { xRed = trkColor.Value; }));
            else
                xRed = trkColor.Value;

            // Get bitmap from picturebox
            Bitmap bmp = (Bitmap)pictureBox1.Image;

            lock (lockObject)
            {

            // search through each pixel via x, y coordinates, examine and make changes. Dont let values exceed 255 or fall under 0.
            for (int y = 0; y < bmp.Height; y++)
                for (int x = 0; x < bmp.Width; x++)
                {
                    Color c = bmp.GetPixel(x, y);
                    int myRed = c.R, myGreen = c.G, myBlue = c.B;
                    myRed += xRed;
                    if (myRed > 255)
                        myRed = 255;
                    bmp.SetPixel(x, y, Color.FromArgb(255, myRed, myGreen, myBlue));
                }

            // assign the new bitmap to the picturebox
            pictureBox1.Image = (Bitmap)bmp;
            }
    }


text:
Q: Getting process ID created by ProcessBuilder I created a Process with ProcessBuilder class in Java. In ProcessBuilder,
in process builder i opened cmd.exe,in task manager a process is opened with cmd.exe and javw.exe for running java application, i want get process id for cmd exe which was started by java ...

A: The JRE's ProcessBuilder does not provide that functionality, you could try jnr-process instead.


text:
Q: Expression #29 of SELECT list is not in GROUP BY clause and contains nonaggregated column I am using a GoDaddy VPS server, after the server setup I can see that they have provided MySql version 5.7. I am getting the below error in MySql query, but this query is running perfectly in MySql 5.6
I have root access.
Error -> Expression #29 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'sephecom_ecom.v2.secondary_colors' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by

A: It is not a version problem, it is a configuration problem
The problem is that you have the only_full_group_by activated. That means that all your select columns must be either on the GROUP BY or must use an aggregation function (like sum, avg, count, etc). If you want to avoid it you can change it doing
SET GLOBAL sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

If you modify your group by condition, you may get strange results in your query


text:
Q: Twitter API: reconnection for TCP/IP level network errors I'm working on a backoff strategy for a robot that connects through the Twitter Streaming API.  The API documentation states:

Back off linearly for TCP/IP level network errors. These problems are generally temporary and tend to clear quickly. Increase the delay in reconnects by 250ms each attempt, up to 16 seconds.

I understand this errors to be when – for whatever reason – the client cannot communicate with the server (ie: no Internet service).  However, I'm not sure if HTTP status codes equal or greater than 500 should be treated as TCP/IP level network errors too (ie: 503 service unavailable), because, in order to receive this error codes, a successful connection between client and server should have happened already.
Could someone please help me understand this?
Thanks.

A: Since this post earned me a "Tumbleweed" badge :-), I decided to post the reply I received at Twitter Developers:

@kurrik
I think your intuition is correct in that a HTTP status code is not a TCP/IP error and you should use the exponential backoff. The slower backoff for these kinds of errors is so that your connection does not get rate limited. A 5XX error is a bit unusual, as it indicates an error which may have happened before or after the connection attempt was logged by the rate limiter. To be safe, I'd say use exponential backoff for this case (although most 503 issues should be cleared after the first reconnect attempt).

I ended up using this strategy:

*

*Disconnections and 500 errors: linear backoff starting at 0.25s and adding 0.25s each time, up to 16s.

*All errors greater than 500: exponential backoff starting at 5s and doubling the amount each time, up to 5 minutes.

*Rate limited (420 / 429): exponential backoff starting at 1m and doubling the amount each time.

*No reconnection:  all 4XX errors different from the rate limit errors.


text:
Q: echo -e "$(git status)" loses colors I'm trying to store a=$(git status) to send it's content to a script and then print the result to the terminal. The problem is that the git colors are not gone. All the result is now without colors.
Any solution to this problem?

A: The following should do the trick.
a="$(git -c color.status=always status)"
echo "$a"


text:
Q: Manually refresh or re-render component onClick in React Is there a way in React to just refresh a component not the window but the component itself? This is so I can re-trigger a react-query. I know I can use useEffect() but what would be the way to do it?
So I know I could do, something like:
useEffect(() => {
     setFetchData(result);
}, [result]);

This would trigger the component to re-render when result changes. But how can you have a button that would manually refresh the component or re-render it.

A: If you are trying to refresh the component just to re-trigger a query from react-query, you'd better use refetch function provided by useQuery hook.
const { data, refetch, ... } = useQuery(...);

return (
  <>
    {(data?.yourQuery?.results || []).map(result => ...)}
    <button onClick={refetch}>Refetch!</button>
  </>
)

If there are some changes of data after calling refetch, the component will be automatically rerendered.

A: You can do it like this:
const [reload, setReload] = useState()
useEffect(() => {
     // Add your code here
}, [reload]);

return (
 <button onClick={() => setReload(!reload)} >Reload</button>
);

And anytime you click the button it will execute the code inside the useEffect and update the component.


text:
Q: Cant see 'incomplete applications' on Goolge Dataproc history server When I am running a spark job I can't see it on the history server under the 'incomplete applications' tab and it does not show up until the job is finished. Is there some setting that I need to set to enable jobs to show up there?

A: Ah it seems the setting was:
'spark:spark.history.fs.gs.outputstream.type' which needs to be set to 'FLUSHABLE_COMPOSITE'
Otherwise it will only write updates when the job is done.


text:
Q: Generating classes for Kentico objects Kentico is installed in Azure. And I'm working with a MVC website.
I'm trying to follow the this Kentico docs article to generate classes for my custom content-only page type. According to the article, after clicking Save, by default the generated classes should be created in ~/App_Code/CMSClasses folder. But I don't see them.

A: Click show all files in Visual Studio :

Or add existing item.
P.S. Connect with FTP or use kudu tools , they will let you browse directory structure and files on-line

A: I've just run through most of the scenario that you describe in an instance of Kentico 11 in an Azure App Service.  I used Kudo to look at the file system and the files are definitely created as described in the documentation.  Rather than connecting through Visual Studio, try using a standard FTP client to see if the files are where you need them to be.
As I said in the comment, if your solution uses a web application rather than a website project, then you'll need to manually add the existing files into the project as @shof says in his answer.


text:
Q: use ug with soplex to solve LP problems I think the ug use scip to solve ILP problems. But I want to solve LP problems with ug and can not find the parameters to configure ug to solve with soplex.
Is it possible to do so, or the LP solver is scalable enough and does not the trouble?

A: UG is a framework for parallelizing the tree search. While there are some tricks to speed up the root as well (racing stage), it's best suited for MIP instances that require a lot of branch and bound nodes.
If you want to solve an LP in parallel, I suggest you try an interior point, aka barrier solver, as is implemented in CPLEX, Gurobi or Xpress. SoPex is a sequential simplex solver.


text:
Q: .bashrc overwritten but still sourced -- how can it be recovered? Usually when I find a command I want to alias, I echo it to my .bashrc like so:
[up button pressed to last command, then line edited so that it reads]
$echo "command-i-just-did" >> ~/.bashrc

There may be a better way to do this. But anyway, just now I overwrote the entire .rc file by using a single chevron. However, since the .bashrc is still current, it's still accepting my old aliases (for now of course). So is there a way to recover it?

A: *

*alias without parameter outputs the definitions of currently defined aliases.

*declare -f outputs the definitions of currently defined functions.

*export -p outputs the definitions of currently defined variables.

All those commands output definitions ready to be reused, you can redirect their outputs directly to a new ~/.bashrc.
All lists will contain a lot of elements defined elsewhere, for example /etc/profile and /etc/bash_completion. So you will have to clean up the list manually.

A: typeset -f > .bashrc
should do it, providing all you had were aliases.


text:
Q: Swift, Spritekit Rotating sprites swift 3 I am trying to rotate a sprite using swift, IOS 10 and the touchesmoved function, the code I have works in the fact it moves the sprite but in not the right way, the wrong directions etc.
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
   super.touchesMoved(touches, with: event)
   guard let touch=touches.first{
         return
   }
   let touchLocation = touch.location(in: self)
   self.zRotation=CGFloat(atan2(Double(touchLocation.y), Double(touchLocation.x)))
}

does anyone know the correct way to rotate a sprite using zRotation and touchesMoved?
Thank you

A: I think you've probably overlooked the wonderful power of constraints in SpriteKit. Easy enough to do, Apple does a terrible job of promoting, presenting and educating those considering using SpriteKit.
Constraints allow you to say "go here", or "look at this".
In your case, the "look at this" is ideal, from the docs:
Orientation Constraints

A common use for orientation constraints is to make a look-at
  constraint. For example, you may create a look-at constraint to make a
  pair of eyes follow a moving object or to have a rocket point in the
  direction of its target.

More specifically, you can use these in your touchesMoved:
https://developer.apple.com/reference/spritekit/skconstraint/1519627-orient

A: thanks for all the suggestions. Yes my explanation of the problem was not too great. so will add the full code here and it seems to be working apart from occasionally moving by 90 degrees on its own when i stop dragging and start dragging again
What I was trying to do was rotate a sprite around another sprite for example a cannon barrel around its wheel... When the wheel is loaded from the scene it calls this class and adds a child node (the barrel) which should be able to be moved around its wheel
import SpriteKit
class WheelNode: SKSpriteNode, CustomNodeEvent{
  private var tubeNode=SKSpriteNode(imageNamed: "cannon-barrel")
  var previousPoint:CGPoint!
  var touchLocation:CGPoint!
  func didMoveToScene() {
    guard let scene=scene else{
        return
    }
    isUserInteractionEnabled=true
    tubeNode.anchorPoint=CGPoint(x:0, y:0)
    tubeNode.position=position
    self.addChild(tubeNode)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        if let touch=touches.first{
            previousPoint=touch.location(in: scene!)
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        super.touchesMoved(touches, with: event)
        if let touch=touches.first{
            touchLocation=touch.location(in: scene!)
            var angle=atan2(touchLocation.y-previousPoint.y, touchLocation.x-previousPoint.x)
            self.zRotation=angle
        }
    }
}


text:
Q: Row Number with a mySQL Join I have the following Query that works correctly:
SELECT  @row_num :=  IF(@prev_value=concat(o.CITY, o.keyword_text)  ,@row_num+1, 1) AS     POSITION
   ,o.idBUSINESS
   ,o.KEYWORD_TEXT
   ,o.CITY
 , o.BID_AMOUNT
  ,@prev_value := concat(o.CITY, o.keyword_text)
FROM   (SELECT @row_num := 1) x,
  (SELECT @prev_value := '') y,
  (SELECT @prev_value1 := '') z,
elevated_business_queue o
ORDER BY o.CITY , o.KEYWORD_TEXT, o.BID_AMOUNT DESC

This query returns:
# POSITION, idBUSINESS, KEYWORD_TEXT, CITY, BID_AMOUNT, @prev_value := concat(o.CITY, o.keyword_text)
'1', '7', '2', 'New Jersey', '3.50', 'New Jersey2'
'2', '5', '2', 'New Jersey', '2.50', 'New Jersey2'
'3', '1', '2', 'New Jersey', '2.50', 'New Jersey2'
'1', '5', '1', 'New York', '2.50', 'New York1'
'2', '7', '1', 'New York', '2.30', 'New York1'
'3', '1', '1', 'New York', '1.50', 'New York1'
'1', '9', '2', 'New York', '7.50', 'New York2'
'2', '1', '2', 'New York', '4.50', 'New York2'
'3', '5', '2', 'New York', '3.50', 'New York2'
'4', '7', '2', 'New York', '2.50', 'New York2'

This data is correct. Now, I want to join the elevated_business_queue with another table. I am doing it as follows:
SELECT  @row_num :=  IF(@prev_value=concat(o.CITY, o.keyword_text)  ,@row_num+1, 1) AS POSITION
   ,o.idBUSINESS
   ,o.KEYWORD_TEXT
   ,o.CITY
 , o.BID_AMOUNT
   ,@prev_value := concat(o.CITY, o.keyword_text)
    FROM   (SELECT @row_num := 1) x,
  (SELECT @prev_value := '') y,
  (SELECT @prev_value1 := '') z,
elevated_business_queue o
INNER JOIN funds_balance fb ON fb.idBUSINESS = o.idBUSINESS
 WHERE fb.PREMIUM_POSITIONS_CREDIT >= (o.BID_AMOUNT + ROUND((12.36/100)*o.BID_AMOUNT, 2))
ORDER BY o.CITY , o.KEYWORD_TEXT, o.BID_AMOUNT DESC

However, when I join, my POSITION gets messed up. I am now getting:
# POSITION, idBUSINESS, KEYWORD_TEXT, CITY, BID_AMOUNT, @prev_value := concat(o.CITY, o.keyword_text)
'2', '7', '2', 'New Jersey', '3.50', 'New Jersey2'
'1', '1', '2', 'New Jersey', '2.50', 'New Jersey2'
'1', '5', '2', 'New Jersey', '2.50', 'New Jersey2'
'2', '5', '1', 'New York', '2.50', 'New York1'
'3', '7', '1', 'New York', '2.30', 'New York1'
'1', '1', '1', 'New York', '1.50', 'New York1'
'1', '1', '2', 'New York', '4.50', 'New York2'
'2', '5', '2', 'New York', '3.50', 'New York2'
'1', '7', '2', 'New York', '2.50', 'New York2'

Can someone please help.
--------------UPDATE----------------------
I tried with the following query but the POSITION is still off:
SELECT T1.*,fb.* FROM
(SELECT  @row_num :=  IF(@prev_value=concat(o.CITY, o.keyword_text)  ,@row_num+1, 1) AS       POSITION
,o.idBUSINESS
,o.KEYWORD_TEXT
,o.CITY
,o.BID_AMOUNT
,@prev_value := concat(o.CITY, o.keyword_text)
FROM   (SELECT @row_num := 1) x,
 (SELECT @prev_value := '') y,
 (SELECT @prev_value1 := '') z,
elevated_business_queue o
ORDER BY o.CITY , o.KEYWORD_TEXT, o.BID_AMOUNT DESC)T1
INNER JOIN funds_balance fb ON fb.idBUSINESS = T1.idBUSINESS
WHERE fb.PREMIUM_POSITIONS_CREDIT >= (T1.BID_AMOUNT + ROUND((12.36/100)*T1.BID_AMOUNT,    2))
ORDER BY T1.CITY ,T1.KEYWORD_TEXT, T1.BID_AMOUNT DESC;

I now get the following result-set:
# POSITION, idBUSINESS, KEYWORD_TEXT, CITY, BID_AMOUNT, @prev_value := concat(o.CITY, o.keyword_text), idBUSINESS, PREMIUM_POSITIONS_CREDIT
'1', '7', '2', 'New Jersey', '3.50', 'New Jersey2', '7', '17.30'
'3', '1', '2', 'New Jersey', '2.50', 'New Jersey2', '1', '12.31'
'2', '5', '2', 'New Jersey', '2.50', 'New Jersey2', '5', '15.19'
'1', '5', '1', 'New York', '2.50', 'New York1', '5', '15.19'
'2', '7', '1', 'New York', '2.30', 'New York1', '7', '17.30'
'3', '1', '1', 'New York', '1.50', 'New York1', '1', '12.31'
'2', '1', '2', 'New York', '4.50', 'New York2', '1', '12.31'
'3', '5', '2', 'New York', '3.50', 'New York2', '5', '15.19'
'4', '7', '2', 'New York', '2.50', 'New York2', '7', '17.30'

There is no POSITION=1 for KEYWORD_TEXT=2 in New York. The following row should have a position of 1:
'2', '1', '2', 'New York', '4.50', 'New York2', '1', '12.31'

A: Perhaps you could replace your row_num calculation with a window function like this:
row_number() over(partition by o.CITY , o.KEYWORD_TEXT order by o.BID_AMOUNT DESC)

A: Here you're misplacing the order by columns. If you require ordering by KEYWORD_TEXT  then by  BID_AMOUNT  and CITY (if yes then)
Change order by as:
 ORDER BY KEYWORD_TEXT, BID_AMOUNT  CITY


text:
Q: Centrar horizontalmente botón Queria consultarles como hago para alinear mi botón al centro o si se puede establecer coordenadas precisas para alinearlo.Les dejo una parte de mi codigo :
Html:
Soy un botón

css:
 .boton_personalizado{
    text-decoration: none;
    padding: 10px;
    font-weight: 600;
    font-size: 20px;
    color: #ffffff;
    background-color: transparent;
    border-radius: 0px;
    border: 2px solid #EDD8D8;

  }
  .boton_personalizado:hover{
    color: #EDD8D8;
    background-color: transparent;
  }

A: Tomemos en cuenta lo siguiente:

*

*Lo que tratas de centrar horizontalmente es un elemento en línea

*La propiedad que pudiera auxiliarnos es text-align con un valor de center

*El problema es que esta propiedad trabaja para la distribución horizontal de los elementos de tipo en bloque como puedes leer en el enlace provisto mas arriba

Dados los puntos anteriores, la opción mas simple es meter dentro de un elemento en bloque como un p a tu etiqueta a y que el centrado se aplique al primero mencionado y en concencuencia afecte a su contenido o etiqueta interna.

      Ir a ningún lugar

Lectura altamente recomendada

*

*Alineación y justificación

A: te recomiendo usar un codigo más sencillo, puedes hacerlo agregando en el "" dos lineas de código que hacen referencia a los archivos de CSS y JS de Bootrap, con el fin que lo hagas de una forma mas sencilla con clases de Bootstrap.
Te recomiendo hacerlo de esta forma, ya los estilos se los puede aplicar en el CSS como tu gustes.
<!DOCTYPE html>

        <title>Titulo web</title>

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">

            Soy un botón

En teoría lo que hice fue, a la etiqueta  le aplique las clases "btn btn-primary", luego encerré esa etiqueta  dentro de un  que lleva un ID el cual podrás usar en el CSS para aplicar los estilos personalizados que desees, al  le puse unas clases de Bootstrap "d-flex justify-content-center" y de esta manera el botón ya está centrado Horizontalmente.
Espero te sea de ayuda.

A: Aplica flexbox a la etiqueta padre en la que vayas a poner a tu enlace
html:

   Soy un botón

css:
div{
  border:1px solid;
  display:flex;
  justify-content:center;
  align-items:center;
}

De esta manera quedará centrado horizontal y verticalmente, pero ojo porque aplicará para todos los elementos dentro del div y el centro se calculará en base al tamaño del mismo.


text:
Q: CheckBox's onCheckedChanged not called after programatically changing checked state? In my code I setOnCheckedChangeListener prior to setting initial value to CheckBox but the listener method not called after setting the initial value :
final CheckBox check_box = convertView.findViewById(R.id.check_box);

check_box.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

// Some logic
}
}

After above line, I set the initial value to CheckBox as follows,
if (isConditionTrue) {
            check_box.setChecked(true);
        } else {
            check_box.setChecked(false);
        }
}

But the listener method onCheckedChanged never called when programmatically changed the check value using method setChecked(), but when the user changes it via display it is called. Is this normal behavior or I have implemented it wrongly?

A: setOnCheckedChangeListener() is called when the checked state of this button changes. However looking at your code, it looks like state of the checkbox might not be changing.
if (isConditionTrue) {
            check_box.setChecked(true);
        } else {
            check_box.;
        }
}

If isConditionTrue is false and check_box is already un-checked, then setChecked(false) won't result in invocation of setOnCheckedChangeListener won't be called. Same applies for check_box already checked and you try to setChecked(true);

A: Yeah its normal behavior. Because the listener is attached  to the checkbox, When you change it on the application ui it will call. But if you change it programmatically, it will not execute.


text:
Q: How do I label the axis of a sinus using pi? I am plotting a sinus function using a pgfplot and would like that the tick of the x axis was labeled using multiplers of pi (pi/4, pi/2, 2*pi...), for they are the "important" x values to visualize when studying the sinus function.
\documentclass{standalone}
\usepackage{tikz}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}
\begin{document}

\begin{tikzpicture}

\begin{axis}[domain=0:2*pi, ymax=1.2, samples=100, grid=major,
  xlabel=$\alpha$, ylabel=$sin(\alpha)$,
  xtick = {0,1,...,6}, ytick = {-1,-0.5,...,1}] %I assume this the part that I need to change?
    \addplot [blue](\x, {sin(\x r)});
\end{axis}

\end{tikzpicture}
\end{document}

I've tried giving regular values of pi in the braces near the % in the code above, but neither using "pi" nor "\pi" has proven useful. Am I missing something? The plot looks like this using the code above:

A: an (simple) alternative:

*

*drawing sin(x) (in degrees)

*label tick with 0, \frac{\pi}{4}, ....
\documentclass[margin=3mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.14}

\begin{document}
    \begin{tikzpicture}
\begin{axis}[
       grid,
       ymax = 1.2,
     xlabel = $\alpha$, ylabel=$\sin(\alpha)$,
      xtick = {0,45,...,360},
xticklabels = {\mathstrut 0,
                $\frac{ \pi}{4}$,$\frac{ \pi}{2}$,$\frac{3\pi}{4}$,$\mathstrut \pi$,
                $\frac{5\pi}{4}$,$\frac{3\pi}{2}$,$\frac{7\pi}{4}$,$\mathstrut2\pi$},
     domain = 0:360,
    samples = 73,
    no marks
                ]
    \addplot +[very thick] {sin(x)};
\end{axis}
    \end{tikzpicture}
\end{document}

A: Welcome to TeX.SE! Here is a possibility. Notice that there exists a number format frac, but I was unable to make this work in this case.
\documentclass[tikz,border=3.14mm]{standalone}
\usepackage{pgfplots}
\pgfplotsset{compat=1.16}
\begin{document}
% based on https://tex.stackexchange.com/a/34958/121799
\foreach \X [count=\Y] in {0,...,8}
{\pgfmathsetmacro{\myx}{\X*pi/4}
\ifnum\Y=1
\xdef\LstX{\myx}
\else
\xdef\LstX{\LstX,\myx}
\fi
}
\begin{tikzpicture}
\begin{axis}[domain=0:2*pi, ymax=1.2, samples=100, grid=major,
  xlabel=$\alpha$, ylabel=$\sin(\alpha)$,
  xtick=\LstX,
      xticklabel={\pgfmathtruncatemacro{\tmp}{round(4*\tick/pi)}
      \pgfmathsetmacro{\mygcd}{gcd(\tmp,4)}%
      \pgfmathtruncatemacro{\mynumerator}{\tmp/\mygcd}%
      \pgfmathtruncatemacro{\mydenominator}{4/\mygcd}%
      \ifnum\mynumerator=0
       $\mathstrut\pgfmathprintnumber{0}$
      \else
       \ifnum\mynumerator=1
         \ifnum\mydenominator=1
          $\mathstrut\pi$
         \else
          $\frac{\pi}{\pgfmathprintnumber{\mydenominator}}$
         \fi
       \else
         \ifnum\mydenominator=1
          $\mathstrut\mynumerator\pi$
         \else
          $\frac{\mynumerator\pi}{\pgfmathprintnumber{\mydenominator}}$
         \fi
       \fi
      \fi}, % https://tex.stackexchange.com/a/304032/121799
     ytick = {-1,-0.5,...,1}] %I assume this the part that I need to change?
    \addplot [blue](\x, {sin(deg(\x))});
\end{axis}
\end{tikzpicture}
\end{document}


text:
Q: boton que envia a otra pagina en html estoy creando un formulario de registro y tengo un pequeño problema.
tengo un boton y cuando doy clic no hace nada ni me lleva a ninguna pagina

Bienvenidos

  <form class="login-form">
    <input type="email" placeholder="Ingresa tu correo electronico"/>
    <input type="number" placeholder="Número de celular"/>
    <input type="text" placeholder="Nombre completo"/>
    <input type="text" placeholder="Apellidos"/>
    <input type="password" placeholder="Contraseña"/>
    <input type="password" placeholder="confirmar contraseña"/>
    <button onclick="location.href=index.html" >Registrarse </button>

Ya tienes una cuenta? Inicia sesión

  </form>

A: en verdad te estas planteando mal el formulario,y como envias datos desde un form,
deberias colocar esto
 <form class="login-form"  action="miurl" method="post">

y luego cambiar el button por esto
 <button type="submit" >Registrarse </button>

asi es la forma tipica de enviar datos que estan dentro de un "form" en html
El "button" hace referencia a un botón genérico, y los "submit" són un tipo de botones preparados para enviar información de formularios, es decir, permiten recoger la información de los "input" que haya dento del "form", empaquetarlos y luego enviar estos datos a la url que hayas colocado en el "action" de la etiqueta "form"


text:
Q: SP2013 Export-SPWeb and Import-SPWeb preserve meta data I want to move a list / library from one site collection to another. I tried to use Export-SPWeb and Import-SPWeb PowerShell commands, however the imported list items doesn't not preserve metadata like Created, Created by, Modified by.
I already used -IncludeVersions All -IncludeUserSecurity
Is it not supported by design?
UPDATED:
After trying the Content and Migration tool. I found that if the ModifiedBy and CreatedBy user of the original item not exist in current AD, the copied/moved items will change the ModifiedBy and CreatedBy to the user who run the operation.

A: It is the limitation of the export and import command. But there are couple of things you can try

*

*use 3rd party tools, which preserve the metadata while moving the contents.i.e sharegate or metalogix

*if it is with in same site then use content structure option to move the list

*i am not sure but garylapoint has custom powershell commands for export n import.http://www.falchionconsulting.com/PowerShellViewer/Default.aspx