text:
Q: Getting last N segments of URL in C++ I need to write a function to return the last N segments of a given URL, i.e. given /foo/bar/zoo and N=2, I expect to get back /bar/zoo. Boundary conditions should be handled appropriately. I have no problem doing it in C, but the best C++ version I could come up is this:
string getLastNSegments(const string& url, int N)
{
    basic_string<char>::size_type found = 0, start = path.length()+1;

    int segments = 2;
    while (start && segments && (start = path.find_last_of('/', start-1)) != string::npos) {
        found = start;
        segments--;
    }

return url.substr(found);
}

cout << "result: " << getLastNSegments("/foo/bar/zoo", 2) << endl;

Is there a more idiomatic (STL+algorithms) way of doing this?

A: Use std::string and rfind().
You call rfind successively N times feeding the last index as parameter. You now have the start index of the string you're looking for and use substr to extract the substring.
std::string x("http:/example.org/a/b/abc/bcd");
int N = 3;
int idx = x.length();
while ( idx >= 0 && --N > 0 )
{
   idx = x.rfind('/',idx) - 1;
}
std::string final = x.substr(idx);

A: Nothing wrong with just using a loop..  Don't know of any STL string functions that will do what you want in a single call.
By the way, what happens when You ask for the last 3 segments of http://www.google.com/?
Call me old-school, but personally I would not use any STL searches here...  What's the matter with this:
if( N <= 0 || url.length() == 0 ) return "";

const char *str = url.c_str();
const char *start = str + url.length();
int remain = N;

while( --start != str )
{
    if( *start == '/' && --remain == 0 ) break;
}

return string(start);

A: Last but not least, a simple boost split solution
string getLastNSegments(const string& url, int n)
{
    string selected;
    vector<string> elements;
    boost::algorithm::split(elements, url, boost::is_any_of("/"));

    for (int i = 0; i < min(n, int(elements.size())); i++)
        selected = "/" + elements.at(elements.size()-1-i) + selected;

    return selected;
}


text:
Q: watir-webdriver not working when called I have a PHP script that calls a Ruby script (system('ruby /lib/program.rb')) that requires watir-webdriver. The system it's on has ruby version
ruby 2.0.0p648 (2015-12-16 revision 53162) [x86_64-linux]

and when I check the error logs I have this message
/usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require': cannot load such file -- watir-webdriver (LoadError)
    from /usr/lib/ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from /lib/program.rb:4:in `<main>'

Requiring rubygems above does nothing. How can I fix?
See here for output when I run "by hand" and not via PHP's system function:
https://gist.github.com/anonymous/ad7befc4ca188e7b3989d6d023bcf100

A: require_relative may solve requiring package. Try this:
require_relative 'watir-webdriver'

A: Try doing system('rvm use 2.0') before executing the ruby script. That should ensure that the shell is using the correct version for the Ruby execution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Fresh installed Ubuntu16.04.1 stucks at reboot screen My screen stays at this  for so long after I installed Ubuntu16.04.1 on Dell XPS15 and tried to reboot.
What should I press to exit this state? Force shutdown by long pressing the power button would be my last resort.


text:
Q: Excel function to present total event occurrences based on month and year of event In my excel file, we are tracking items in for repairs with their corresponding dates of arrival.  The dates start in A3 and continue to A23.  I need a function to output how many items arrived each month based on their date of arrival in C45 (July), D45 (August), ect.  Is this  even possible?
There are no values corresponding to these dates.  That is why my previous attempts at using the LOOKUP function have failed.  Thanks.
Arrival Date
7/10/2012
9/10/2012
9/18/2012
9/18/2012
9/19/2012

Total Failures      July '12    August '12  September '12
Historical         1                0                4

A: Put =SUMPRODUCT(--(MONTH($A$3:$A$23)= 7)) in C45
Put =SUMPRODUCT(--(MONTH($A$3:$A$23)= 8)) in D45
courtesy: www.chandoo.org


text:
Q: UIScrollView not scrolling with UITableView I am trying to implement a scrollView that contains a text field, button, and table view. I am completely lost trying to get the thing to scroll, I've tried changing the height of UITableView but that has not worked, I've tried adjusting the height of the content View and scrollView, but that has not worked either. How can I get the scrollview to scroll and adjust the size when another tableViewCell is added to the tableView?
override func viewDidLayoutSubviews() {

        tableView.frame = CGRect(x: tableView.frame.origin.x, y: tableView.frame.origin.y, width: tableView.frame.size.width, height: CGFloat(tableView.numberOfRows(inSection: 0) * 120))
        tableView.reloadData()

    }

@IBAction func addExercisePressed(_ sender: Any) {
    test.append("nice")
    tableView.reloadData()

    tableView.frame = CGRect(x: tableView.frame.origin.x,y: tableView.frame.origin.y ,width: self.view.frame.size.width, height: CGFloat(test.count * 120))
    scrollView.frame.size = CGSize(width: self.view.frame.size.width, height: tableView.frame.size.height)

}

A: Please dont use tableView inside a scrollView, tableView is subclass of scrollView and that's mean tableView already have scroll function
your answer to set
tableHeight.constant = tableView.contentSize.height

It will make recycle/dequeue cell function useless because tableView will show all the cell immediately, tableview will call cellForRowAt for all indexes that showed in tableview viewport
UITableview inside Scrollview call cellforrow too many times
Here why we use dequeueReusableCellWithIdentifier
From what I see you want something like this right

you can check this repo how I only use a tableview to achieved that
please note that tableHeaderView is scrollable, sectionHeaderView is sticky

A: All I needed was to set a height constraint for the TableView and connect that via IBOutlet, then this line of code wherever reloading table data is needed
tableHeight.constant = tableView.contentSize.height


text:
Q: How to set log level for apache beam pipeline running on Direct Runner When running an Apache Beam pipeline locally using Direct Runner the log level seems to be set to DEBUG.
Is there a way to set the log to say INFO instead?
Note: --workerLogLevelOverrides can be used when using Cloud Dataflow Runner, but does not seem to apply on Direct Runner

A: It appears that per standard configuration, the logging is done with slf4j using a JUL(java.util.logging) backend. You can check in your pom.xml for slf4j-api which corresponds to slf4j and slf4j-jdk14 for its backend.
You need to configure JUL at runtime. One way is to pass as a parameter to the VM something like
-Djava.util.logging.config.file=logging.properties
Then you create a logging.properties in the directory where you run your application. In my case it is the root directory for the app(the one that contains src directory). If it doesn't seem to work, you can just specify an absolute path in as the filename.
Regarding the configuration, here you have an example:
handlers=java.util.logging.ConsoleHandler
.level=INFO
java.util.logging.ConsoleHandler.level=ALL
org.apache.beam.sdk.io.gcp.pubsub.PubsubUnboundedSource.level=ALL

This sets the level for the package org.apache.beam.sdk.io.gcp.pubsub.PubsubUnboundedSource. Depending on the situation you can play with it's configuration. Make sure that the level is properly set to all the components involved in JUL log output.


text:
Q: testing a webapplication using jUnit or some other api? I am wondering if its possible to create a testing suite for testing a web application using junit API?
or we have to add other APIs, or is there any other better option?
Will this support ajax, jquery, javascript?
I mean will I be able to test the web application that uses javascript, ajax, jquery?

A: These are the possible solutions for you ( http://java-source.net/open-source/web-testing-tools)


text:
Q: Notify admin via email when order is placed in magento Is there a way to Notify admin via email when order is placed in magento? I feel like this is a silly question but I'm placing test orders currently and I'm not getting any email notification.
Will the order also get an email notification by default or does the admin have to click the "invoice button" each time an order comes in?

A: In the magento backend goto
System > Configuration

Left Naviagation > Sales > Sales Emails  this option will let you configure mail sending settings where you can ask magento to send you mail whenever an order is placed.
Alternatively, you can create a plugin with an observer which listens to the event of the order being placed and you can write your mail sending code in the observer.

A: Once configured...
Are you sure that email is being sent?
<?php
 $to = "recipient@example.com";
 $subject = "Hi!";
 $body = "Hi,\n\nHow are you?";
 if (mail($to, $subject, $body)) {
   echo("sent!");
  } else {
   echo("failed");
  }
?>

also check your /var/log/maillog for messages.

A: Go to System -> Configuration -> Select Store email addresses and change the Sales representative's email address.
Then go to Left Naviagation > Sales > Sales Emails and ensure that it is set for Sales representative.
Also just check that you've done this on the main site.


text:
Q: Spring security without password
We have a scenario where the admin user should be able to launch the
  application by just entering the username of any user without entering the
  password. This is required for testing purpose and in real production
  environment we will use SSO pre authentication.

Can this be achieved with following stack?

*

*Spring - 3.2.17.RELEASE

*Spring Security - 3.2.9.RELEASE

A: Spring security store the references for current user in a SecurityContext object. Spring Security magic ensures (through thread local storage) that a thread correctly accesses its one.
You can allow a special action in your web app to dynamically change the Authentication in the SecurityContext through the static methods of the SecurityContextHolder.


text:
Q: MySQL request from two tables interacting with each other Tables i have
Table1 user_id, date
Table2 user_id, status
I need something like
UPDATE Table2
   SET status = 2
   WHERE user_id in ( {SELECT user_id FROM Table1 WHERE date > 0} )

In other words i need to see if date in table1 is more than 0000-00-00 then grab user_id of people who match this criteria and use them in table2 to set their status to 2.
Problem is that i need to do it for more than one user so request inside request does not work for me, it only works when there's one row in result.

A: I think what you've written should work, but what's with the curly braces? Just remove them to make it like this:
UPDATE Table2
   SET status = 2
   WHERE user_id in (SELECT user_id FROM Table1 WHERE date > 0)

According to the MySQL documentation, IN should work with a subquery.

The ANY keyword, which must follow a comparison operator, means "return TRUE if the comparison is TRUE for ANY of the values in the column that the subquery returns."
When used with a subquery, the word IN is an alias for = ANY.

A: Are you using PHP or some other language to make SQL calls? If so, it might easier to just,

*

*firstly: select user ids from table 1

*secondly: loop through each row

*thirdly: execute the update

Regards,
Mark


text:
Q: ObjC: Duplicate NSLog() output in the console when reading in char's with scanf() And here I thought I was getting competent at ObjC, and this little C-type problem is giving me fits.  :)  This program is intended to read in a character from user input and print an expression that gives the character's decimal value.  This program is generating duplicate NSLog() statements and I can't figure out why:
#import <Foundation/Foundation.h>

int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

char a;

for (int i = 1; i <= 10; i++)
{
    NSLog(@"Type in an ASCII character or type 'command-.' to exit.");
    scanf("%c", &a);
    NSLog(@"%c = %d", a, a);
}

[pool drain];
return 0;
}

Here's the output:
Type in an ASCII character or  type 'command-.' to exit.
a
a = 97
Type in an ASCII character or type 'command-.' to exit.
 = 10
Type in an ASCII character or type 'command-.' to exit.

When I change the read-in variable from a char to an int and make the according format specifier modification in the scanf(), the program runs in the console as intended.  (Prompting the user for a character, printing out the value, and prompting again.)  As soon as I go back to a char though, it does this.  What am I doing wrong?  Also, regardless of what type of char I enter, there's always the "= 10" output.  What's the deal with that?  Thanks in advance, guys.

A: "= 10" is the ascii code for the enter key.
So change your code into:
scanf("\n%c", &a);


text:
Q: Can I preserve files input at Meteor hot code push? Background: I'm working on file uploading in Meteor.js, when I do a hot code push the client refresh their pages, but if they are during a file upload this stops.
My question: "Is the Meteor hot code push a total refresh of the app?"

*

*If so then I'm out of luck, since the file input cannot survive in a session/cookie.
but:

*If not then how can I recieve hot code push event? (is there a Meteor.addListener for this?)
(no, I dont have any code since this is a general Meteor.js question)

A: The way hot code push works is it serializes your application state and refreshes the page, then restores the state. Unfortunately, file uploads are a little complicated. I imagine you're not actually storing the file upload progress in your app state, which means that if the page refreshes, it won't start up again all by itself and continue.
To fix this, you could first store the uploading file locally in a database and upload it from there. Keep track of how much has been uploaded, and then when the app refreshes, tell the app to continue from where it left off.
Obviously this is a non-trivial problem. Personally I would probably consider this an edge case and ask the user to re-upload the file rather than investing all the time needed into engineering a solution. Unless your app use case consists entirely of uploading files, at which point you have a challenge on your hands :-)


text:
Q: How to customize styles of listBoxItem in UWP? My Xaml:
    <ListBox x:Name="ListBox" Style="{StaticResource ListBoxStyle1}" Width="200" Height="200">

    </ListBox>

I have a custom ItemTemplete for ListBox.
    <Style x:Key="ListBoxStyle1" TargetType="ListBox">
        <Setter Property="Foreground" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="Background" Value="{ThemeResource SystemControlBackgroundChromeMediumLowBrush}"/>
        <Setter Property="BorderBrush" Value="{ThemeResource SystemControlForegroundBaseHighBrush}"/>
        <Setter Property="BorderThickness" Value="{ThemeResource ListBoxBorderThemeThickness}"/>
        <Setter Property="ScrollViewer.HorizontalScrollBarVisibility" Value="Disabled"/>
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Auto"/>
        <Setter Property="ScrollViewer.HorizontalScrollMode" Value="Disabled"/>
        <Setter Property="ScrollViewer.IsHorizontalRailEnabled" Value="True"/>
        <Setter Property="ScrollViewer.VerticalScrollMode" Value="Enabled"/>
        <Setter Property="ScrollViewer.IsVerticalRailEnabled" Value="True"/>
        <Setter Property="ScrollViewer.ZoomMode" Value="Disabled"/>
        <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False"/>
        <Setter Property="ScrollViewer.BringIntoViewOnFocusChange" Value="True"/>
        <Setter Property="IsTabStop" Value="False"/>
        <Setter Property="TabNavigation" Value="Once"/>
        <Setter Property="FontFamily" Value="{ThemeResource ContentControlThemeFontFamily}"/>
        <Setter Property="FontSize" Value="{ThemeResource ControlContentThemeFontSize}"/>
        <Setter Property="UseSystemFocusVisuals" Value="{StaticResource UseSystemFocusVisuals}"/>
        <Setter Property="ItemTemplate">
            <Setter.Value>
                <DataTemplate>
                    <RelativePanel x:Name="Holder">
                        <FontIcon x:Name="ToogleIcon" FontFamily="Segoe MDL2 Assets" Width="18" Height="12" Glyph=""/>
                        <TextBlock x:Name="ItemNameBlock" Margin="23 0 0 0" Text="{Binding Name}"/>
                    </RelativePanel>
                </DataTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="ItemsPanel">
            <Setter.Value>
                <ItemsPanelTemplate>
                    <VirtualizingStackPanel/>
                </ItemsPanelTemplate>
            </Setter.Value>
        </Setter>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="ListBox">
                    <Border x:Name="LayoutRoot" Background="{TemplateBinding Background}" BorderThickness="{TemplateBinding BorderThickness}" BorderBrush="{TemplateBinding BorderBrush}">
                        <ScrollViewer x:Name="ScrollViewer" AutomationProperties.AccessibilityView="Raw" BringIntoViewOnFocusChange="{TemplateBinding ScrollViewer.BringIntoViewOnFocusChange}" HorizontalScrollBarVisibility="{TemplateBinding ScrollViewer.HorizontalScrollBarVisibility}" HorizontalScrollMode="{TemplateBinding ScrollViewer.HorizontalScrollMode}" IsDeferredScrollingEnabled="{TemplateBinding ScrollViewer.IsDeferredScrollingEnabled}" IsHorizontalRailEnabled="{TemplateBinding ScrollViewer.IsHorizontalRailEnabled}" IsVerticalRailEnabled="{TemplateBinding ScrollViewer.IsVerticalRailEnabled}" Padding="{TemplateBinding Padding}" TabNavigation="{TemplateBinding TabNavigation}" VerticalScrollMode="{TemplateBinding ScrollViewer.VerticalScrollMode}" VerticalScrollBarVisibility="{TemplateBinding ScrollViewer.VerticalScrollBarVisibility}" ZoomMode="{TemplateBinding ScrollViewer.ZoomMode}">
                            <ItemsPresenter/>
                        </ScrollViewer>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

And i have bind the DataTemplete element, TextBlock (ItemNameBlock) using Model in .cs.
class Model
{
    public Model(string name)
    {
        this.Name = name;
    }
    public string Name { get; set; }
}

 Class Load
 {
    publc void LoadData()
    {
       Model model = new Model("Hai");
        Model model1 = new Model("Hello");
        ObservableCollection<Model> observable = new ObservableCollection<Model>();
        observable.Add(model);
        observable.Add(model1);
        ListBox.ItemsSource = observable;
     }
  }

Upto binding the Name, works fine.
I have ToggleIcon inside the DataTemplete , that toggleIcon must be visible only for the selectedItem.How to do that?
At the same time,I need to change the ListBoxItem style like PointerOver,PointerPressed,SelectedPointerOver using visualState!.How to do this also?

A:
I have ToggleIcon inside the DataTemplete , that toggleIcon must be visible only for the selectedItem.How to do that?

You could define bool Visible property for the Model class to handle ToggleIcon visible.
For example
public class Model : INotifyPropertyChanged
{
    public Model(string name)
    {
        this.Name = name;
    }
    public string Name { get; set; }
    private bool _visible;
    public bool Visible
    {

        get => _visible;
        set
        {
            _visible = value;
            NotifyPropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            // PropertyChanged is always null.
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

ListBox contains SelectedItem property, you could use it to get selected item, and update model Visible property, and record previous selected item. so that hide the ToggleIcon of previous item when select the next one.
public sealed partial class MainPage : INotifyPropertyChanged
{
    public MainPage()
    {
        this.InitializeComponent();
        this.DataContext = this;
    }

    public void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            // PropertyChanged is always null.
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    private Model _selectItem;
    private Model _privousItem;
    public Model SelectItem
    {
        get => _selectItem;
        set
        {
            if (_privousItem != null)
            {
                _privousItem.Visible = false;
            }

            _selectItem = value;

            NotifyPropertyChanged();
            _selectItem.Visible = true;
            _privousItem = _selectItem;
        }
    }

    protected override void OnNavigatedTo(NavigationEventArgs e)
    {
        base.OnNavigatedTo(e);
        MyList.ItemsSource = new ObservableCollection<Model> {
        new Model("hello"),
          new Model("hello1"),
            new Model("hello2"),
              new Model("hello3"),
                new Model("hello4"),
                  new Model("hello5"),
                    new Model("hello6"),
        };
    }

}

Xaml code
<ListBox x:Name="MyList" SelectedItem="{Binding SelectItem, Mode=TwoWay}">

    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <TextBlock Text="{Binding Name}" />
                <SymbolIcon
                    x:Name="MySbl"
                    HorizontalAlignment="Right"
                    Symbol="Accept"
                    Visibility="{Binding Visible}" />
            </StackPanel>

        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

At the same time,I need to change the ListBoxItem style like PointerOver,PointerPressed,SelectedPointerOver using visualState!.How to do this also?

For doing this you need edit the default ListBoxItem style. you could get the default  ListBoxItem in the generic.xaml file.


text:
Q: merge in sqlserver - incorrect syntax I try to execute this transaction:
GO
BEGIN TRAN;
MERGE A AS t
USING B AS tmp
ON (t.domain = tmp.domain and t.link=tmp.link)
WHEN NOT MATCHED BY A
    THEN INSERT(ipVal, domain, dateStart, dateUpdate, dateFinish, link) VALUES(tmp.ipVal, tmp.domain, tmp.dateStart, tmp.dateUpdate, tmp.dateFinish, tmp.link)
WHEN MATCHED
    THEN UPDATE SET t.dateupdate = tmp.dateupdate
WHEN NOT MATCHED BY B
    THEN UPDATE SET t.datefinish="a"
ROLLBACK TRAN;
GO

I took this code from here, But when I tried to execute this I got an error:
Incorrect syntax near 'A'

What can be the problem?

A: According to MSDN the simplified syntax for WHEN NOT MATCHED branches is
   [ WHEN NOT MATCHED [ BY TARGET ] [...]
        THEN <merge_not_matched> ]
    [ WHEN NOT MATCHED BY SOURCE [...]
        THEN <merge_matched> ] [ ...n ]

The solution is to replace WHEN NOT MATCHED BY A with WHEN NOT MATCHED BY TARGET and WHEN NOT MATCHED BY B with WHEN NOT MATCHED BY SOURCE.
TARGET and SOURCE are T-SQL keywords not placeholders.

A: One I just began to use MERGE I use this syntax to understand it right:
MERGE A AS target
USING B AS source
ON (target.domain = source.domain and target.link=source.link)
WHEN NOT MATCHED BY TARGET
    THEN INSERT(ipVal, domain, dateStart, dateUpdate, dateFinish, link)
    VALUES(source.ipVal, source.domain, source.dateStart, source.dateUpdate, source.dateFinish, source.link)
WHEN MATCHED
    THEN UPDATE SET target.dateupdate = source.dateupdate
WHEN NOT MATCHED BY SOURCE
    THEN UPDATE SET target.datefinish="a"

I know it is a bad practice but when started - helps a lot.
As @BogdanSahlean points TARGET and SOURCE are keywords and there are required when you determine matched/not matched statements.

A: Looks like you are trying to update the date or datetime type column with char or varchar type data which is not convertible to date or datetime type. 'a' is not convertible to date or datetime. Look at the First and the second Merge I have below.If you don't mention when matched or when not matched  by source or target, by default it considers Target.
--DROP TABLE #A;
--DROP TABLE #B;

CREATE TABLE #A
    (
        ipval VARCHAR(50)
    , domain CHAR(5)
    , dateStart DATE
    , dateUpdate DATE
    , dateFinish DATE
    , link VARCHAR(50)
    );

CREATE TABLE #B
    (
        ipval VARCHAR(50)
    , domain CHAR(5)
    , dateStart DATE
    , dateUpdate DATE
    , dateFinish DATE
    , link VARCHAR(50)
    );
INSERT  INTO #B
        ( ipval, domain, dateStart, dateUpdate, dateFinish, link )
VALUES  ( '42.130.239.56'  -- ipval - varchar(50)
            , '.com'  -- domain - char(5)
            , GETDATE()  -- dateStart - date
            , DATEADD(DAY, 1, GETDATE())  -- dateUpdate - date
            , DATEADD(DAY, 5, GETDATE())  -- dateFinish - date
            , 'www.stackoverflow'  -- link - varchar(50)
            ),
        ( '78.188.136.74'  -- ipval - varchar(50)
            , '.com'  -- domain - char(5)
            , GETDATE()  -- dateStart - date
            , DATEADD(DAY, 2, GETDATE())  -- dateUpdate - date
            , DATEADD(DAY, 10, GETDATE())  -- dateFinish - date
            , 'www.msdn'  -- link - varchar(50)
            );

INSERT  INTO #A
        ( ipval, domain, dateStart, dateUpdate, dateFinish, link )
VALUES  ( '30.48.111.20'  -- ipval - varchar(50)
            , '.com'  -- domain - char(5)
            , GETDATE()  -- dateStart - date
            , DATEADD(DAY, 5, GETDATE())  -- dateUpdate - date
            , DATEADD(DAY, 10, GETDATE())  -- dateFinish - date
            , 'www.msdn'  -- link - varchar(50)
            ),
        ( '30.48.111.20'  -- ipval - varchar(50)
            , '.com'  -- domain - char(5)
            , GETDATE()  -- dateStart - date
            , DATEADD(DAY, 5, GETDATE())  -- dateUpdate - date
            , DATEADD(DAY, 10, GETDATE())  -- dateFinish - date
            , 'www.gmail'  -- link - varchar(50)
            );
--First Merge
BEGIN TRAN;
MERGE #A AS T
USING #B AS tmp
ON T.domain = tmp.domain
    AND T.link = tmp.link
WHEN NOT MATCHED BY TARGET THEN
    INSERT ( ipval
            , domain
            , dateStart
            , dateUpdate
            , dateFinish
            , link
            )
    VALUES ( tmp.ipval
            , tmp.domain
            , tmp.dateStart
            , tmp.dateUpdate
            , tmp.dateFinish
            , tmp.link
            )
WHEN MATCHED THEN
    UPDATE SET T.dateUpdate = tmp.dateUpdate
WHEN NOT MATCHED BY SOURCE THEN
    UPDATE SET T.dateFinish =''a'';
COMMIT TRAN;
GO

SELECT  *
FROM    #A;
SELECT  *
FROM    #B;
--Second Merge
BEGIN TRAN;
MERGE #A AS T
USING #B AS tmp
ON T.domain = tmp.domain
    AND T.link = tmp.link
WHEN NOT MATCHED BY TARGET THEN
    INSERT ( ipval
           , domain
           , dateStart
           , dateUpdate
           , dateFinish
           , link
           )
    VALUES ( tmp.ipval
           , tmp.domain
           , tmp.dateStart
           , tmp.dateUpdate
           , tmp.dateFinish
           , tmp.link
           )
WHEN MATCHED THEN
    UPDATE SET T.dateUpdate = tmp.dateUpdate
WHEN NOT MATCHED BY SOURCE THEN
    UPDATE SET T.dateFinish = CAST(GETDATE() AS DATE);
COMMIT TRAN;
GO

SELECT  *
FROM    #A;
SELECT  *
FROM    #B;


text:
Q: Compiling with ASLR(-pie) causes the executable to be seen as shared library I am trying to add security flags to an executable but it seem that when compiling with -pie (as linker flags), the file tool sees it as a shared library, although I can run it without problems.
Is this normal? Can this be fixed?
I am using add_link_options(-pie) (so all CMake executables can benefit)
untitled3: ELF 64-bit LSB shared object, x86-64, version 1 (GNU/Linux), dynamically linked, interpreter /lib64/l, for GNU/Linux 3.2.0, BuildID[sha1]=f33e240db8bf52c2566b2cad14b4be67fdb6b35a, with debug_info, not stripped
LE: it seems it was a bug in file tool, fixed here:

A: Executables compiled with -pie are shared objects. file now has special support to deal with these. The answers to this question go into this in more detail.


text:
Q: Getting "FBSDKErrorDeveloperMessageKey=(#324) Requires upload file" when trying to post image I'm currently in charge of implementing several new features to a social network app, one of them is whenever the user posts an image it automatically gets posted on the user's facebook as well (exactly the same way Instagram does). So far I came up with this:
FBSDKAccessToken *token = [FBSDKAccessToken currentAccessToken];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
NSDictionary *parameters = @{
                             @"message" : @"some text",
                             @"picture" : @"http://fanaru.com/doge/image/18353-doge-os-x-doge.jpg",
                             };

FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:@"me/photos" parameters:parameters tokenString:token.tokenString version:@"v2.3" HTTPMethod:@"POST"];
[connection addRequest:request completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
    if(error)
        NSLog(@"%@", error);
    else
        NSLog(@"Success");
}];

[connection start];

but every time I run it I get this error:

Error Domain=com.facebook.sdk.core Code=8 "The operation couldn't be completed. (com.facebook.sdk.core error 8.)" UserInfo=0x166a64d0 {com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=324, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
          body =     {
              error =         {
              code = 324;
              message = "(#324) Requires upload file";
              type = OAuthException;
          };
      };
      code = 400;
  }, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400,   com.facebook.sdk:FBSDKErrorDeveloperMessageKey=(#324) Requires upload file,   com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0}

I understand I need to upload the image to the facebook servers but I simply have no idea on how to do this. Already read tons of pages from the Facebook SDK documentation and still haven't got any solution. Ideally I will also need to create a new photo album specifically for this app but solving the problem above is my main concern right now.
Thanks in advance.
EDIT: Just so you know, if I change the graphpath to "me/feed" it works just fine, put the picture is posted as a link, so still not really what I'm looking for.

A: The error it's giving you is right. It doesn't want a URL it asked you for a file and that file wasn't included. You need to download your image first if you don't already have it and include the image data in the parameters.
UIImage *image = (some picture I downloaded);
NSDictionary *parameters = @{
                               @"message" : @"some text",
                               @"picture" : UIImagePNGRepresentation(image),
                            };


text:
Q: Typeorm: Check if a property is either value 1, 2, 3 or n I want to get all tasks that have a certain role. I have an array of strings for which I want to get the tasks.
Query:
return this.createQueryBuilder('task')
    .select(this.baseSelect)
    .where('task.role = :role', { role }) // What here?
    .getMany();

This code of course only gets the tasks for which the role is that one value.
How can I check multiple values?

A: For searching in multiple roles you can use the IN operator:
OLD VERSION of TypeORM
return this.createQueryBuilder('task')
    .select(this.baseSelect)
    .where('task.role IN(:roles)', {roles: [role1, role2, role3]});
    .getMany();

NEW VERSION of TypeORM
As mentioned by user Christophe Geers, In the new version, you will have to use the spread syntax.
return this.createQueryBuilder('task')
    .select(this.baseSelect)
    .where('task.role IN(:...roles)', {roles: [role1, role2, role3]});
    .getMany();


text:
Q: Azure Web App - Is it possible to put custom domain to virtual application I have deployed 2 web application on a single azure web app using the virtual application, please refer screenshot below,
Now I want to point custom domain URL as,
main.mydomain.com to app1
and
api.mydomain.com  to app2
is it possible? if yes how to achieve that? please help.
Otherwise, I will end up creating no of WebApps for each application? Then is that the only approach?

A: According to your description, you want visit main.mydomain.com and redirect to yourwebapp.azurewebsites.net/app1 and same with app2.
If so, you could use the following rule in web.config:
<rewrite>
    <rules>
        <rule name="RedirectTovirtualDirectory" stopProcessing="true">
            <match url="(.*)" />
            <conditions logicalGrouping="MatchAny">
                <add input="{HTTP_HOST}" pattern="^main.mydomain.com$" />
            </conditions>
            <action type="Redirect" url="https://yourwebapp.azurewebsites.net/app1/{R:1}" redirectType="Permanent" />
       </rule>
    </rules>
</rewrite>


text:
Q: NSURLConnection(download large files more than 500M) I want to download a large file (> 500MB) to my application from the server. I used NSURLConnection, that works well if the network is  very good. but sometimes I tried to download 500MB file, but 200MB or 100MB only downloaded if the network is not very good.That means I got the connectionDidFinishLoading  method when the task was not completed.Someone says set a timeout second to avoid this situation,but i set  timeout  second 30s,it did not work.Should I set 60s or more? Does someone have better idea,please help me.

A: in connectionDidFinishLoading method every time check the length of data to download and the downloaded data.
length of the data to be download is gain by this [response expectedContentLength]; in didReceiveResponse method

A: You should download such big file in parts. Specify the Content-Range field in the header of your HTTP request and ask only for a small portion of the file at once. When you get all portions, you can assemble the file together.
You can set HTTP headers with NSMutableURLRequest setValue:@"0-1023/*" forHTTPHeaderField:@"Content-Range"];, this example downloads only the first kbyte of the file. See also Content-Range in http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html


text:
Q: Group rows based on flag, with a single row as output I have a table like below in oracle 10g.
**Pat_no   pat_id   doc    doc_flag**
A1         123      ABD     Y
A1         123      ABC     Y
A1         123      ABE     Y
A1         123      ABF     Y

I want a single row output when all the different docs have the flag 'Y'.
**Pat_no    pat_id  doc_flag**
A1          123     Y

If any one has a doc_flag as 'N' then the output should be 'N'.
**Pat_no    pat_id  doc_flag**
A1          123     N

How can I do this?

A: I think you're looking for
select pat_no, pat_id, min(doc_flag) doc_flag
  from t
 group by pat_no, pat_id

A: Is this what you want:
select pat_no, pat_id, 'Y'
from t
group by pat_no, pat_id
having min(doc_flag) = max(doc_flag) and min(doc_flag) = 'Y';

A: You can use the COUNT aggregation function with CASE:
SELECT pat_no,
       pat_id,
       CASE
         WHEN COUNT( CASE doc_flag WHEN 'N' THEN 1 END ) > 0
         THEN 'N'
         ELSE 'Y'
       END AS doc_flag
FROM   your_table
GROUP BY
       pat_no,
       pat_id


text:
Q: Strange error trying to query against an excel datasource in ssrs I am writing a report in SSRS that uses an excel spreadsheet as a datasource.  There is a column in the spreadsheet I want to do counts on named F2.  I want to use this SQL to perform the counts:
Select Sum(Case When F2 = 'I' then 1 end) as IncidentCount,
       Sum(Case When F2 = 'R' then 1 end) as RequestCount,
       Sum(Case When F2 = 'P' then 1 end) as ProblemCount
From [Ticket Detail$]

When I hit OK to exit the query designer, I get this error:
ERROR [42000] [Microsoft][ODBC Excel Driver] Syntax error (missing operator) in query expression 'Sum(Case When F2 = 'I' then 1 end)'.

Can I not run this type of SQL against an excel datasource?  How can I get the counts I want?

A: You should be able to handle this fairly easily in SSRS itself through expressions. If you select * from the dataset, you would used an expression like this in your tablix:
=sum(iif(Dataset1!Type.Value="I", 1, 0))

And for a textbox it would look like:
=sum(iif(Fields!Type.Value="I", 1, 0), "Dataset1")


text:
Q: Does the cross over the projection graphic indicate the origin of the projection? [QGIS] I am using a projection that I have defined from a WKT format, and not included in QGIS' default roster of projections. See below in the image. The origin of my projection is 40N and 100W. Why is the cross hair centring where it is? Or is this just a generic default that occurs when you define your own custom projection in Q?

A: The cross simply indicates where your map canvas is centered right now and the violet box shows you the current extent of the map canvas. Normally, there should be a second, light red box that shows the extent the selected CRS is valid for.
Screenshot: zoomed to Europe, the small violet box shows the extent of the map canvas (=red outlined frame), including the point the canvas is centered on, somewhere in eastern Poland/western Ukraine. The red box covers the whole world, because I selected EPSG:3857 (Web Mercator) in the CRS dialog window.


text:
Q: Delphi Component displayed wrong when running I'm using Delhi XE2 to create a custom progressbar Component. I thought I had it working, but if I run an application with the progressbar, the complete layout changes.
The red, yellow and black panels disappear and only the (main) green one is visible.
Here is my code:
unit CustomProgressBar;

interface

uses
System.SysUtils, System.Classes, Vcl.Controls, Vcl.ExtCtrls;

type
  TCustomProgresBar = class(TPanel)
  private
    { Private declarations }
    LeftRedPanel: TPanel;
    LeftYellowPanel: TPanel;
    RightRedPanel: TPanel;
    RightYellowPanel: TPanel;
    BlackPanel: TPanel;
    function GetLeftRedPanelWidth: Integer;
    procedure SetLeftRedPanelWidth(const NewWidth: Integer);
    function GetLeftYellowPanelWidth: Integer;
    procedure SetLeftYellowPanelWidth(const NewWidth: Integer);
    function GetRightRedPanelWidth: Integer;
    procedure SetRightRedPanelWidth(const NewWidth: Integer);
    function GetRightYellowPanelWidth: Integer;
    procedure SetRightYellowPanelWidth(const NewWidth: Integer);
    function GetPosition: Integer;
    procedure SetPosition(const NewPosition: Integer);
  protected
    { Protected declarations }
    procedure Paint; override;
  public
    { Public declarations }
    constructor Create(AOwner: TComponent); override;
  published
    { Published declarations }
    property LeftRedPanelWidth: integer read GetLeftRedPanelWidth write SetLeftRedPanelWidth;
    property LeftYellowPanelWidth: integer read GetLeftYellowPanelWidth write SetLeftYellowPanelWidth;
    property RightRedPanelWidth: integer read GetRightRedPanelWidth write SetRightRedPanelWidth;
property RightYellowPanelWidth: integer read GetRightYellowPanelWidth write SetRightYellowPanelWidth;
    property Position: integer read GetPosition write SetPosition;
  end;

procedure Register;

implementation

procedure TCustomProgresBar.Paint;
begin
  inherited;
  BlackPanel.Height:=Height;
end;

function TCustomProgresBar.GetLeftRedPanelWidth: Integer;
begin
  Result := LeftRedPanel.Width;
end;

procedure TCustomProgresBar.SetLeftRedPanelWidth(const NewWidth: Integer);
begin
  if NewWidth <> LeftRedPanel.Width then
  begin
    LeftRedPanel.Width := NewWidth;
    Invalidate; // redraws the component
  end;
end;

function TCustomProgresBar.GetLeftYellowPanelWidth: Integer;
begin
  Result := LeftYellowPanel.Width;
end;

procedure TCustomProgresBar.SetLeftYellowPanelWidth(const NewWidth: Integer);
begin
  if NewWidth <> LeftYellowPanel.Width then
  begin
    LeftYellowPanel.Width := NewWidth;
    Invalidate; // redraws the component
  end;
end;

function TCustomProgresBar.GetRightRedPanelWidth: Integer;
begin
  Result := RightRedPanel.Width;
end;

procedure TCustomProgresBar.SetRightRedPanelWidth(const NewWidth: Integer);
begin
  if NewWidth <> RightRedPanel.Width then
  begin
    RightRedPanel.Width := NewWidth;
    Invalidate; // redraws the component
  end;
end;

function TCustomProgresBar.GetRightYellowPanelWidth: Integer;
begin
  Result := RightYellowPanel.Width;
end;

procedure TCustomProgresBar.SetRightYellowPanelWidth(const NewWidth: Integer);
begin
  if NewWidth <> RightYellowPanel.Width then
  begin
    RightYellowPanel.Width := NewWidth;
    Invalidate; // redraws the component
  end;
end;

function TCustomProgresBar.GetPosition: Integer;
begin
  Result := BlackPanel.Left;
end;

procedure TCustomProgresBar.SetPosition(const NewPosition: Integer);
begin
  if NewPosition <> BlackPanel.Left then
  begin
    BlackPanel.Left := NewPosition;
    Invalidate; // redraws the component
  end;
end;

procedure Register;
begin
  RegisterComponents('MarcelS', [TCustomProgresBar]);

end;

constructor TCustomProgresBar.Create(AOwner: TComponent);
begin
  inherited create(Aowner);
  Color:=65280;  //Green
  Width:=200;
  Height:=25;
  BevelOuter:=bvNone;

  LeftRedPanel:=TPanel.Create(Self);
  with LeftRedPanel do
  begin
    Parent := Self;
    Align:=alLeft;
    Color:=255;    //Red
    Width:=25;
    Caption:='';
    BevelOuter:=bvNone;
  end;

  LeftYellowPanel:=TPanel.Create(Self);
  with LeftYellowPanel do
  begin
    Parent := Self;
    Align:=alLeft;
    Color:=65535;   //Yellow
    Width:=25;
    Caption:='';
    BevelOuter:=bvNone;
  end;

  RightYellowPanel:=TPanel.Create(Self);
  with RightYellowPanel do
  begin
    Parent := Self;
    Align:=alRight;
    Color:=65535;   //Yellow
    Width:=25;
    Caption:='';
    BevelOuter:=bvNone;
  end;

  RightRedPanel:=TPanel.Create(Self);
  with RightRedPanel do
  begin
    Parent := Self;
    Align:=alRight;
    Color:=255;   //Red
    Width:=25;
    Caption:='';
    BevelOuter:=bvNone;
  end;

  BlackPanel:=TPanel.Create(Self);
  with BlackPanel do
  begin
    Parent := Self;
    Align:=alNone;
    Color:=0;   //Red
    Width:=5;
    Left:=35;
    Caption:='';

    Top:=0;
    BevelOuter:=bvNone;
  end;

  BlackPanel.Height:=Height;
  Caption:='';
end;

end.


text:
Q: Передать количество повторений в наследуемый шаблон Blade У меня есть вот такая реализация наследуемых шаблонов (упрощенная разметка):
chunks/incl.blade.php
@for ($i = 2; $i <= $count; $i++)

@endfor

layouts/parent.blade.php

@yield('guest-count')
@include('chunks.incl', ['count' => $guest_count])

child.blade.php
@extends('layouts.parent')
@section('guest-count')
@php
$guest_count = 20;
@endphp
@endsection

@section('room-guests',20)

Все работает как надо, но мне не нравится реализация!
Видимо что-то я не доучил, что-то не дочитал ...
Вопрос
Как еще можно (более красиво) из шаблона child.blade.php передать количество повторений во включаемый шаблон incl.blade.php?


text:
Q: Add overlay image on top of other image Suppose that I have an RGB image RGB and a binary image binary that contains the result of segmentation of image RGB. How to draw the image binary on top of image 'RGB` and show the segmentation as a red transparent area? I tried the following but I got an error. Please help me to figure out the best way in MATLAB
I=imread('RGB.png');
[M,N,C] = size(I);
h=imshow(I);
alpha= imread('binary.png');
alpha = cat(3,alpha,zeros(M,N), zeros(M,N));
set(h, 'AlphaData', alpha);

Here are the input images:

A: You simply use your binary alpha (one layer only) as AlphaData.

A: Here is a method to add red overlays in select regions of the mask. Modifications to these scripts can be made to fill in the remaining regions with the colours white or black. The regions of interest on the mask are selected using a logical array.
Overlay Red Over White Region of Mask

Overlay_Opacity = 0.5;

Image =imread('RGB.png');
imshow(Image);

Red_Channel = imread('binary.png');
White_Mask_Region = Overlay_Opacity*(Red_Channel ~= 0);

Overlay_Image(:,:,1) = White_Mask_Region;
Overlay_Image(:,:,2) = 0;
Overlay_Image(:,:,3) = 0;

hold on
Overlay = image(Overlay_Image);
Overlay.AlphaData = White_Mask_Region;
saveas(gcf,'Overlay_1.png');

Overlay Red Over Black Region of Mask

Overlay_Opacity = 0.5;

Image =imread('RGB.png');
imshow(Image);

Red_Channel = imread('binary.png');
Black_Mask_Region = Overlay_Opacity*(Red_Channel == 0);

Overlay_Image(:,:,1) = Black_Mask_Region;
Overlay_Image(:,:,2) = 0;
Overlay_Image(:,:,3) = 0;

hold on
Overlay = image(Overlay_Image);
Overlay.AlphaData = Black_Mask_Region;
saveas(gcf,'Overlay_2.png');

A: If you have the Image Processing Toolbox, this function will do what you want:
https://www.mathworks.com/help/images/ref/labeloverlay.html


text:
Q: Delete/clear all contents of a neptune named graph using sparql I am trying to delete/clear data from a named graph using python. Used approach
import requests
url = "neptune_endpoint:8182/sparql"
query = "CLEAR GRAPH IRIref."
PARAMS = {"query" :query}
r = requests.get(url, params= PARAMS)

getting error malformed query. Thanxs in advance for help.

A: The following code should work for you.
import requests
url = "neptune_url:8182/sparql"
query = "CLEAR GRAPH IRIref"
headers = {"content-type": "application/sparql-update"}
r = requests.post(url, data=query, headers=headers)

Note that the specification requires this to be a POST and have specific content type headers set.  Neptune is fully SPARQL 1.1 compliant, so the relevant areas in the specification here are https://www.w3.org/TR/sparql11-protocol/#update-operation and https://www.w3.org/TR/sparql11-update/#clear.


text:
Q: is it possible to find class name given class variable class A:
    var = 'hello'

type(A.var)               # returns: <class 'str'>
A.var.__class__.__name__  # returns: 'str'
vars(A)                   # returns: mappingproxy({'__module__': '__main__', 'var': 'hello', '__dict__': <attribute ' __dict__' of 'A' objects>, '__weakref__': <attribute '__weakref__' of 'A' objects>, '__doc__': None, '__getattribute__': <slot wrapper '__getattribute__' of 'object' objects>})

given A.var is it possible to find class A, or just var is related to class A, may be something similar to 'qualname' for methods.
Edited
reason I wanted to find the class name is I am implementing micro ORM, similar to SQLAlchemy using declarative mapping.
As you can see in this example.
import sqlalchemy as sa
import sqlalchemy.ext.declarative

meta = sa.MetaData()
DeclarativeBase = sa.ext.declarative.declarative_base(metadata=meta)

class User(DeclartiveBase):
    __tablename__ = 'user'

    id            = sa.Column(Integer, primary_key=True)
    name          = sa.Column(String)
    fullname      = sa.Column(String)

as you can see class is used as the abstraction for the real table, intresting thing is you can still access all the column using vars(Users) and filter column using isinstance(<var>, sa.Column).
while doing query some how query is able to know which table the row is from, which is similar to the question I asked above, may its something to do with sa.Column.
Session = sa.orm.sessionmaker(bind=engine)
session = Session()

rows = session.query(
    User.id,
    User.name,
).all()

Sample
This is sample of the implemenation, which is able to do basic table creating, insertion and update.
class Col(str):
    pass

class Base:
    @classmethod
    def childs(cls):
        subclasses = set()
        work = [cls]
        while work:
            parent = work.pop()
            for child in parent.__subclasses__():
                if child not in subclasses:
                    subclasses.add(child)
                    work.append(child)
        return subclasses

    @classmethod
    def create(cls, cursor):
        query = 'CREATE TABLE IF NOT EXISTS {} ({})'.format(
            cls.__tablename__,
            ', '.join(
                k + ' ' + v
                for k, v in vars(cls).items()
                if isinstance(v, Col)
            )
        )
        cursor.execute(query)

    @staticmethod
    def create_all_tables(cursor):
        for cls in __class__.childs():
            cls.create(cursor)

    @classmethod
    def drop(cls, cursor):
        query = 'DROP TABLE IF EXISTS {}'.format(
            cls.__tablename__,
        )
        cursor.execute(query)

    @classmethod
    def insert(cls, cursor, kvRow):
        query = 'INSERT INTO {} ({}) VALUES(:{})'.format(
            cls.__tablename__,
            ', '.join(kvRow.keys()),
            ', :'.join(kvRow.keys())
        )
        cursor.execute(query, kvRow)

using it
class User(Base):
    __tablename__ = 'user'

    id            = Col('INTEGER PRIMARY KEY')
    name          = Col('VARCHAR')
    fullname      = Col('VARCHAR')

now creating table is similar to sqlalchemy meta.create_all(bind=engine, checkfirst=True)
import sqlite3

conn   = sqlite3.connect('./sqlite.db')
cursor = conn.cursor()
Base.create_all_tables(cursor)

Which I don't understand is how sqlchemy session.query is able to understand the table the row is from.

A: If I understand your question correctly, the main problem you deal with is: How to make an object, when it is placed in the definition of a class as its attribute, "know" what class it belongs to?
To achieve that, SQLAlchemy uses metaclasses (an advanced topic...), but there are simpler techniques, especially in modern versions of Python. One of them, which I think can be particularly handy for you, is to make your Col class implement a specific part of the descriptor protocol.
A simple approach - __set_name__-based
Referring to the Python docs, when it comes to your use case, the relevant part of the descriptor protocol is the method:

__set_name__(self, owner, name)
Called at the time the owning class owner is created. The descriptor has been assigned to name.

For example, you can implement this method as follows:
class Col(str):

    owner = None
    name = None

    def __set_name__(self, owner, name):
        self.owner = owner
        self.name = name

Then, if you place in a class definition some instances of Col as attributes of that class, they will be notified about that, by invocation of their __set_name__, just after creation of the class. Thanks to that, each of them will "know" that class and the name obtained as an attribute of that class:
>>> class ArbitraryClass:
...     id            = Col('INTEGER PRIMARY KEY')
...     name          = Col('VARCHAR')
...     fullname      = Col('VARCHAR')
...
>>> ArbitraryClass.id
'INTEGER PRIMARY KEY'
>>> ArbitraryClass.id.owner
<class '__main__.ArbitraryClass'>
>>> ArbitraryClass.id.name
'id'
>>> ArbitraryClass.name.owner
<class '__main__.ArbitraryClass'>
>>> ArbitraryClass.name.name
'name'
>>> ArbitraryClass.fullname.owner
<class '__main__.ArbitraryClass'>
>>> ArbitraryClass.fullname.name
'fullname'

An alternative approach - __init_subclass__-based
# We keep `Col` very simple:
class Col(str):
    owner = None
    name = None

# ...as the responsibility of detecting `Col` attributes
# is taken by the `Base` class:
class Base:
    def __init_subclass__(cls, /, **kwargs):
        super().__init_subclass__(**kwargs)
        for name, obj in vars(cls).items():
            if isinstance(obj, Col):
                obj.owner = cls
                obj.name = name
    # And below the rest of your implementation of `Base`...

See the docs of __init_subclass__.
Example use of the above definitions:
>>> class Table(Base):
...     id            = Col('INTEGER PRIMARY KEY')
...     name          = Col('VARCHAR')
...     fullname      = Col('VARCHAR')
...
>>> Table.id
'INTEGER PRIMARY KEY'
>>> Table.id.owner
<class '__main__.Table'>
>>> Table.id.name
'id'
>>> Table.name.owner
<class '__main__.Table'>
>>> Table.name.name
'name'
>>> Table.fullname.owner
<class '__main__.Table'>
>>> Table.fullname.name
'fullname'

Another alternative approach - metaclass-based
Yet another possibility is to use a metaclass -- in a way which is quite similar to what we have done above with __init_subclass__.
# Again, we keep `Col` very simple:
class Col(str):
    owner = None
    name = None

# ...because a metaclass will do the work:
class BaseMeta(type):
    def __new__(metacls, name, bases, namespace, **kwargs):
        cls = super().__new__(metacls, name, bases, namespace, **kwargs)
        for name, obj in vars(cls).items():
            if isinstance(obj, Col):
                obj.owner = cls
                obj.name = name
        return cls

class Base(metaclass=BaseMeta):
    # Note: ↑ by passing `metaclass=BaseMeta` we say:
    # the class of the `Base` class is `BaseMeta`.
    # That's the essence: *metaclass* == *class of a class*.

    # And below the rest of your implementation of `Base`...

Usage is the same as in the case of the __init_subclass__()-based approach...
Note: metaclasses are a very powerful tool, as you can customize with them various stages of the class creation process. Here, however, I believe engaging them would be overkill. Moreover, using this technique becomes troublesome when you need capabilities provided by more than one metaclass. Composing different existing metaclasses may turn out to be difficult or even impossible.
So I'd rather suggest one of the simpler approaches described earlier.

A: If you want find the model class that a column in the query "belongs" to, you can use the query's column_descriptions attribute:
q = session.query(User.id, User.name)
q.column_descriptions

outputs
[{
     'name': 'id',
     'type': Integer(),
     'aliased': False,
     'expr': <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7fa18b87dcc0>,
     'entity': <class '__main__.User'>
 },
 {
     'name': 'name',
     'type': String(),
     'aliased': False,
     'expr': <sqlalchemy.orm.attributes.InstrumentedAttribute object at 0x7fa18b87dd60>,
     'entity': <class '__main__.User'>
}]

so the model class can be found in the value of the entity key for each column.  This works for both the 1.x session.query syntax and the 2.0 sa.select(User.id, User.name) syntax.

A: Well, it's not possible to associate the class A, to the variable, because you are creating a class A, but instatiating a String that has nothing to do with that class.
If you create the class, and associate an attribute, instead of just creating a raw string inside the class, than you can return the class.
class A:
    def __init__(self, value):
        self.__value = value
    def __str__(self):
        return self.__value
    def __eq__(self, other):
        return self.__value == other
    def retunclass(self):
        return self.__class__.__name__

var = A('hello')             #var = 'hello'
print(var.retunclass())      #>>> 'A'

if var == 'hello':
    print(True)              #>>> True


text:
Q: Can we run DDL scripts using FromSql in EF Core I know this is not what intended for, but just want to know FromSql whether we can use like this
_dbContext.Student.FromSql("ALTER TABLE Student ADD Grade varchar(max)")

I just want to push this once to my Azure SQL Test environment (still I am in development phase and dont have direct access to SQL editor), better i could have run Migrations, but some point i had messed with it, have to rely on something else. This is like a temporary fix.

A: _dbContext.Database.ExecuteSql("ALTER TABLE Student ADD Grade varchar(max)")


text:
Q: How do I stop a build from running when I check in code? In exploring devops I have set up several build pipelines for my Azure repository.
When I push my code the following pipeline runs

However I want to stop this pipeline running and run a different one instead.

Where do I configure this?
[Update]
From the docs
It would appear to be to do with step 9, triggers.

How do I edit the triggers?

A: On the Triggers tab check Override YAML Continuous Integration trigger from here.

Then select Disable continuous integration
Than save


text:
Q: Python - Newspaper Library - Why is it missing sizable portions of articles? I'm using the newspaper library, V. 2.7 found here.
When I download, parse, and print the text, it gives me a much smaller portion of the article than exists in reality. Why is this? Is there any way to fix this?
Here is my code:
from newspaper import Article

url = "http://www.nytimes.com/2010/10/07/us/politics/07manchin.html"

article_object = Article(url, language = 'en')
article_object.download()
article_object.parse()
article_object.text

If you look at what it prints out, and compares with the actual article online, one finds that the article.text skips over the first 7-8 paragraphs of the actual article. Any way to make sure the "full" article is captured?
Here's the output of article_object.text:

u'The national Republican Party has smelled blood and is spending
  millions on television ads here as part of its drive to retake the
  Senate. One new ad shows men in baseball caps predicting that Mr.
  Manchin will transform into \u201cWashington Joe,\u201d declaring,
  \u201cWe\u2019ve got to stop Obama.\u201d\n\nPhoto\n\nMr. Manchin
  thought he had punched all the right buttons in this state with a
  Democratic majority but conservative values. He won his second term as
  governor in 2008 with 70 percent of the vote and has garnered praise
  for fiscal responsibility; even Mr. Raese calls him a good governor.
  He has been endorsed by the Chamber of Commerce, the National Rifle
  Association and both the coal industry and the mine workers.\n\nMr.
  Manchin is highlighting his conservative credentials and record of
  independence and he has accused his opponent of waging a campaign of
  \u201cfear and smear.\u201d But the anti-Obama message appears to be
  resonating with some residents \u2014 perhaps the same voters who gave
  the state to Senator John McCain and President Bush in the last three
  presidential elections.\n\n\u201cManchin has been a great governor,
  but I\u2019m going to vote for Raese,\u201d said Jeff Whittington, 41,
  a tire distributor in Charleston. \u201cI think Manchin will get to
  the Senate and be a rubber stamp for Obama,\u201d he said, repeating
  Mr. Raese\u2019s message almost word for word.\n\nIn a state where
  coal is seen as the fount of prosperity, Mr. Raese has seized on what
  he calls ambiguous statements by Mr. Manchin on proposals for a
  cap-and-trade system to reduce greenhouse gases. Mr. Manchin now
  speaks clearly on the issue: he is firmly against cap-and-trade and a
  carbon tax, he emphasized in the interview.\n\nOn Wednesday, Mr.
  Manchin had an opportunity to underscore his support for coal and to
  distance himself from the president. With the head of the coal
  producers\u2019 association at his side in the state Capitol, he
  announced that the state was suing two federal agencies, seeking to
  reverse the stricter controls on mountain-top coal mining adopted in
  2009 by the Obama administration.\n\nAdvertisement Continue reading
  the main story\n\nDiscussing the suit against the Environmental
  Protection Agency and the Army Corps of Engineers, Mr. Manchin said
  that the more stringent procedures were unlawful and had harmed the
  state by slowing new mining projects to a trickle, and he accused the
  Obama administration of trying \u201cto destroy our coal industry and
  way of life.\u201d\n\nThe E.P.A. responded that its actions were
  legally and scientifically sound.\n\nMr. Manchin, independent experts
  and even the West Virginia Coal Association have taken exception to a
  Raese ad accusing Mr. Manchin of passing a state law that
  \u201celiminates 25 percent of coal usage in our power
  plants.\u201d\n\nIn fact, the law calls for progress in new energy
  technologies that include cleaner coal, and it had the support of the
  industry.\n\nMr. Raese has also lambasted the governor for past
  statements welcoming the Obama health plan; Mr. Manchin says that some
  core elements of the plan, like protecting children\u2019s coverage,
  are good but that others should be repealed. Mr. Raese calls the
  health plan \u201cpure, unadulterated socialism\u201d that should be
  discarded entirely, a message that appeals to many small-business
  owners.\n\nPhoto\n\nMr. Raese is a brawny and self-confident man who
  has run unsuccessfully for the Senate and for governor before and now
  feels currents flowing his way. \u201cHow do you put together a
  business plan when you have Obamacare facing you, when you\u2019ve got
  cap-and-trade facing you?\u201d he asked in an interview at the
  Republican office in Morgantown, his home base.\n\nMr. Raese runs
  limestone mines and a steel-fabrication company and is part owner of a
  radio network and a newspaper. He has at least three homes around the
  country, and his wife lives in their home in Palm Beach, Fla., while
  he has kept his residence in West Virginia.\n\nWhile Mr. Raese\u2019s
  anti-Washington message has wide appeal, his unequivocal support for
  Nafta and free trade and his opposition to unions may not help him in
  a state with a blue-collar heritage. Mr. Manchin\u2019s campaign has
  run ads featuring Mr. Raese boasting about his inherited wealth and
  highlighting his opposition to minimum wages and other worker
  protections.\n\nIn interviews across the state, some residents said
  that while Mr. Raese can seem arrogant, they admired his record of
  creating jobs and were ready to send a new face to Washington rather
  than elect a man they see as a career politician.\n\nAdvertisement
  Continue reading the main story\n\nThe only polls published so far
  were automated \u2014 done without personal interviews \u2014 and are
  not widely accepted as reliable. But private polling by both camps
  indicates an unexpectedly close race.\n\nFord Frances, 53, a lawyer in
  Charleston, said he likes Mr. Manchin as governor \u2014 Mr. Manchin
  will retain his job if he loses the Senate race \u2014 but that he is
  leaning toward voting for Mr. Raese because he worries about a
  skyrocketing federal deficit and thinks government has too big a role
  in the economy.\n\nOthers, including Cheryl Bonner, 64, of Fairmont,
  said they thought it was unfair to paint Mr. Manchin with the excesses
  of Washington. \u201cHe\u2019s been for West Virginia, and I\u2019m
  leaning toward voting for him,\u201d said Ms. Bonner, who had to start
  working again, as a store clerk, because her and her husband\u2019s
  Social Security and pension checks did not cover the bills. She hopes
  that retirees will be protected, whoever wins, she said.\n\nSome
  residents said Mr. Manchin was just unlucky to be running for national
  office this year. \u201cProbably at any other time he\u2019d have
  gotten my vote,\u201d said a 51-year-old credit analyst in Charleston,
  an economic conservative who voted for Mr. Manchin in 2008 but is
  troubled by the administration\u2019s economic
  policies.\n\n\u201cPutting him in that Senate seat would enhance the
  Democrats\u2019 position,\u201d said the man, who declined to give his
  name because his company has dealings with the governor\u2019s office.
  \u201cWe\u2019d rather keep him here as governor.\u201d'


text:
Q: Replaying the sound as many times as button is clicked I have the following code:
    if (someId.matches("A") || someId.matches("a")) {
        tvLetCap.setText("A");
        tvLetLow.setText("a");
        ivLetterIcon.setImageResource(R.drawable.apple);
        btnDisplayWord.setText("A is for APPLE");
        mpSound = MediaPlayer.create(this, R.raw.sound);
        mpSound.setLooping(false);
        btnPlay.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                /*try {
                    Uri uri = Uri.parse("android.resource://com.mypack.testing/" + R.raw.sound);
                    mpSound.setDataSource(getApplicationContext(),uri);
                    mpSound.prepare();
                    */
                    mpSound.start();
                    btnPlay.setVisibility(View.GONE);
                    btnStop.setVisibility(View.VISIBLE);
                    btnStop.setOnClickListener(stopSound);
                /*}
                catch (IOException e){
                    Log.e("REPLAYING", "prepare() failed");
                }*/
            }
        });
        mpSound.setOnCompletionListener(new OnCompletionListener() {
            public void onCompletion(MediaPlayer mp) {
                mpSound.release();
                btnPlay.setVisibility(View.VISIBLE);
                btnStop.setVisibility(View.GONE);
            }
        });
    }

It plays fine with the codes commented out but whenever I try to replay the file my app FC. The sound file is located in res/raw/sound.mp3
How can I modify the code so it plays as many times as the btnPlay is pressed.

A: You've released the media player.  If you want to reuse it, don't do that.

A: There are some methods for mediaplayer...
http://developer.android.com/reference/android/media/MediaPlayer.html
Maybe you need to use mpSound.reset() in onClick method for button (some time ago i had such mistake :p)? :)


text:
Q: C# Convert Char to KeyValue I have a char, for example 'A'.
How I can get KeyValue after which will write this character ('A')?
Thanks for reading,
Greetings.
PS:
How to obtain the function SendInput large / small letters?

A: [DllImport("user32.dll")]
static extern short VkKeyScan(char ch);

static public Key ResolveKey(char charToResolve)
{
    return KeyInterop.KeyFromVirtualKey(VkKeyScan(charToResolve));
}


text:
Q: ASP.NET LocalResources same filename I have a small question and I think this is asked before but I can't seem to find it...
I have 2 pages:

/Default.aspx
/Profile/Default.aspx

The resource file for the /Default.aspx is in /App_LocalResources/Default.aspx.resx but where do I place the Default.aspx.resx for the /Profile/Default.aspx?
When I place it in /App_LocalResources/Profile/Default.aspx.resx it keeps telling me the resource isn't found...
I access the resources like this: <%$ Resources:lblHeader.Text %>

A: try
    /Profile/App_LocalResources/Default.aspx.resx


text:
Q: Error connecting to a PostgreSQL Azure database using libpq I am trying to connect to a PostgreSQL Azure database using libpq on Windows 10. The syntax is as below --
PQinitSSL(1);
PGconn* pConn = PQconnectdb("host=nameofhost.postgres.database.azure.com port=5432 dbname={your_database} user=postgres@nameofhost password={your_password} sslmode=require");
ConnStatusType ist = PQstatus(pConn);

The connection status is CONNECTION_BAD, and the error message is "SSL SYSCALL error: Connection reset by peer (0x00002746/10054)".
Note that I set up the windows firewall rules correctly. And on the same machine, pgAdmin is able to connect to this PostgreSQL Azure database successfully.
Your help/suggestion is greatly appreciated.


text:
Q: How to protect users' credentials stored unencrypted in ~/.docker/config.json by 'docker login'? I have a Docker registry deployed on a server, where multiple persons can login as root. This local registry is used to pull and push Docker images in a remote registry hosted in an Artifactory instance. However, whenever a person makes a docker login to an Artifactory repository with its credentials, Docker stores his/her credentials unencrypted in a base64 encoding in ~/.docker/config.json. Since the host of the local Docker registry is accessible from multiple persons, it puts his/her credentials at risk from others.
I searched and found alternatives to resolve this problem. According to docker login documentation, the Docker Engine can keep user credentials in an external credentials store using an external helper program. From the list of currently available credentials helpers, I chose pass one. I followed the instructions followed by other users here, and I successfully created a directory  under ~/, where every credential could be stored encrypted:
[root@hostname ~]# ls -a .password-store/
.  ..  .gpg-id
[root@hostname ~]# pass
Password Store

It didn't take me long to realise that this didn't actually solve my problem. Let me explain. By running docker login for the first time after the above setup, the following directories were created:
[root@hostname ~]# docker login repository-name.artifactory-url
Username: myUserName
Password:
[root@hostname ~]# pass
Password Store
└── docker-credential-helpers
    └── cmVwb3NpdG9yeS1uYW1lLmFydGlmYWN0b3J5LXVybA==
        └── myUserName

The password is now encrypted in myUserName.gpg file under ~/.password-store/docker-credential-helpers/cmVwb3NpdG9yeS1uYW1lLmFydGlmYWN0b3J5LXVybA==/ directory, using the private key which corresponds to gpg-id included in ~/.password-store/.gpg-id file.
If a second person executes docker login as above, his/her credentials will be encrypted with the same private key as before. And then of course decrypted with the same public key. This is because docker automatically saves every new password under the same directory, ~/.password-store/docker-credential-helpers/, using always ~/.password-store/.gpg-id file. If every person had his/her credentials stored under a different path, then an alternative .gpg-id file would be used for him/her, and thus a different private-public key pair.
Has anyone an idea how to overcome either the problem with the unencrypted credentials in ~/.docker/config.json, or the problem with pass utility I described?
My OS is a CentOS Linux release 7.9.2009.


text:
Q: What is the AUX_IN and CD_IN connection on old Soundblaster sound cards? What is the AUX_IN and CD_IN 4-pin connection on old Soundblaster sound cards? The card's model is CT4170. Here is an example

I think its some sort of input. Is there any schematic which tells me which pin is what? There was also a connector on one of those inputs with three wires. Here is how it was connected

A: Those are analog inputs for a CD drive and whatever auxiliary device such as another CD drive.
The pinout is Left Ground Ground Right.

A: Those are audio inputs.  The sound card can record them or mix them into the speaket output, or record and mix to output at the same time.
"AUX" is "auxilliary."  Any line level signal you'd like to connect.
"CD_IN" is for connecting the audio output of the CD drive.  It is just a line level input, but the mixer will show it as CD so that you know which one it is.
AUX and CD are wired differently.
AUX:
Look closely at the markings beside the connectors, and you'll see "L" and "R."  That's "left" and "right."  The signal goes to the outer pins.
Connect the left and right signals from a line level source (or headphone cable from your phone) to the appropriate L and R pins.
Connect the ground to the middle pins.  Either one, or both.  It doesn't matter.
The connections are "LGGR."
CD:
There are several ways these were wired.  Later boards used the same scheme as AUX.
Yours appears to be "LOGR." That's "left," "open," "ground," and "right."  "Open" means there's no connection.
This page has descriptions of many common PC audio connections.


text:
Q: INSERT violating unique key constraint on primary key on a table with primary key 'id' with default value nextval(), inserting a row throws the error
Query 1 ERROR: ERROR:  duplicate key value violates unique constraint "table_pkey"
DETAIL:  Key (id)=(6) already exists.

except this table has 200 rows. why isn't Postgres setting the new row id as 201?

A: You inserted rows manually into the table providing explicit values for the id column, which means the sequence was not advanced as no default value was used. Now your sequence is out of sync with the actual values in the table.
You need to sync the sequence using setval() with your actual values if you do that:
select setval( pg_get_serial_sequence('the_table', 'id'),
               (select max(id) from the_table)
             );

If you want to prevent this kind of problem in the future, you can re-define the column as an identity column which will reject passing explicit values for it, so that you get an error if you try to bypass the default value.


text:
Q: JAXB annotation for repeating block of elements I have the following example XML I would like to unmarshal using jaxb annotations:
<root>
    <AAA>
        stuff
        1
        <c>8</c>
        <BBB>
            more stuff
            2
            <c>10</c>
            <CCC>
                other stuff
                2
                <c>10</c>
            </CCC>
        </BBB>
    </AAA>
</root>

I would like to factor out the repeating elements in to a class, like:
@XmlAccessorType(XmlAccessType.FIELD)
public class SomeName {
    private String a;
    private String b;
    private String c;
}

Is there a way to annotate this, without having to repeat the properties in each class AAA, BBB, CCC?
@XmlAccessorType(XmlAccessType.FIELD)
public class AAA {
    **@WhatToUseHere?**
    private SomeName someName;

    private BBB bbb;
}

A: You were already on the right track.
Your class SomeName is fine.
But then you need to define the other classes AAA, BBB and CCC
by extending SomeName.
(If you are still new to Java, then you may want to read more about Inheritance first.)
By doing so these 3 classes contain all the members (a, b, c)
from their superclass SomeName.
JAXB works well together with Java inheritance.
And therefore the 3 XML elements <AAA>, <BBB> and <CCC>
automatically contain all the sub-elements ,  and <c>.
@XmlAccessorType(XmlAccessType.FIELD)
public class AAA extends SomeName {

    @XmlElement(name="BBB")
    private BBB bbb;
}

@XmlAccessorType(XmlAccessType.FIELD)
public class BBB extends SomeName {

    @XmlElement(name="CCC")
    private CCC ccc;
}

@XmlAccessorType(XmlAccessType.FIELD)
public class CCC extends SomeName {

}

and finally the root element:
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class Root {

    @XmlElement(name = "AAA")
    private AAA aaa;
}

Notice also:
Some Java members are annotated with @XmlElement(name="something")
to explicitly set the name of the according XML element.
If you would not do that, then the Java member would be mapped to an XML element
with the same name.
For example: the Java member private AAA aaa would be mapped
to the XML element <aaa> (not <AAA>).


text:
Q: Reporting non-significant regression analysis?
As a result of attached regression analysis I found non-significant results and I was wondering how to interpret and report this. I am a self-learner and checked Google but unfortunately almost all of the examples are about significant regression results.
Hypothesis 7 predicted that receiving more likes on a content will predict a higher score of self-objectification. To test this hypothesis a simple linear regression was conducted to predict self-objectification based on number of likes.

A: The interpretation is similar to analysis with a significant outcome. Your B coefficient indicate how much one changes in likes (or one unit of changes likes) affect the self-objectification. I see it is a very small number, to easier interpret the result, it might be interesting use a scale of 10 of 100 likes instead?
As with significant results you should report the confidence interval, and discuss if the upper or lower limit has a relevant effect on your outcome based on you subject knowledge. The p-value is in itself less interesting, but is often reported anyway.
The standard coefficient can be given if one want to compare with other variables with other units. But is most important if you do not have the subject knowledge to understand the units of the variables.
You can get help here:
I hope this helps you


text:
Q: Asserting Element Not Present Using ExpectedConditions Class I'm trying to get into the practice of utilizing the ExpectedConditions class to do my Selenium related assertions, but I'm having trouble finding the de facto best practice for asserting a given element is not present.  I'm trying to use something like this ...
Assert.assertFalse(ExpectedConditions.presenceOfElementLocated(By.xpath(myXpath)).apply(driver1));

But this won't compile of course because presenceOfElementLocated returns a WebElement instead of a boolean, which I'm finding frustrating.  What do you recommend as the best practice for accomplishing what I'm going for?
EDIT: The accepted answer to the question converted to Java ...
public static boolean elementXpathPresent(WebDriver driver,String elementXpath) {
    try {
        WebDriverWait wait = new WebDriverWait(driver,10);
        wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(elementXpath)));
    } catch (TimeoutException e) {
        return false;
    }
    return true;
}

A: Well, using ExpectedConditions will eventually throw NoSuchElementException if there is no element matching the selector present. In that case you probably want to use try catch with ExpectedConditions or simply use findElements() and size() to see if it finds any elements at all. See my answer here
Here is another option for you. Written in C# but will be fairly easy to convert
/// <summary>
///
/// </summary>
/// <returns></returns>
public bool Test()
{
    try
    {
        new WebDriverWait(Driver, TimeSpan.FromSeconds(10)).Until(
            ExpectedConditions.ElementExists(By.XPath("MyXpath")));
    }
    catch (NoSuchElementException)
    {
        return false;
    }

    return true;

}

/// <summary>
///
/// </summary>
public void Assertion()
{
    Assert.IsTrue(Test());
}

A: The easiest way to check that an element is not present is to use the plural form of the findElement function (i.e. findElements) and check the length of the returned list of element. If the element is not present, then the list will be of size 0.
Assert.assertTrue(driver.findElements(By.xpath(myXpath)).size() == 0);

Whether or not it makes sense to use an explicit wait for this test really depends on your application. Most of the time when I am checking for the absence of an element, I have an earlier tests that uses an explicit wait. For instance, if I want to check that a change to a search table empties the table, I first check that the table has finished refreshing and then check that it is empty. The former check needs an explicit wait, the latter check does not.

A: The accepted answer is a good way to do this (and it's the way I prefer to make assertions with Selenium). But you could also use ExpectedConditions.not() with Assert.true() to assert that elements aren't present:
Assert.assertTrue(
    ExpectedConditions.not(ExpectedConditions.presenceOfAllElementsLocatedBy(By.xpath(myXpath))).apply(driver1));


text:
Q: Weird content-assist behavior in Eclipse with Android I have encountered very weird behavior on Eclipse's (both Helios and Juno) content-assist when I was programming for Android. Following capture shows everything smooth when I was still inside that inner class (OnSeekBarChangeListener())

Then once I move further on (just one line forward, declaring an int after the Listener instead of inside, as shown below, content-assist has stopped working!

Then commenting out the whole listener makes things work again...

I tried deleting the whole block of code and hand type them again yet the behavior remains. I have tried cleaning out Eclipse's cahche (-clean), double-checked my content-assist setting (seems to be correct otherwise case #1 & 3 wouldn't have worked)
Strange thing is that I had another inner listener earlier in the file and things were working without any problem.
What can be the problem? (it's almost impossible to write code without content-assist :p)
Thanks in advance for your assistances.
Michael


text:
Q: Spring Inject PersistenceContext Trying to implement a DDD architecture with aspect oriented tests that access a database and check if user exists, using AspectJ LTW...
Currently I am faces with two issues, I don't know if this class is being injected in a Spring context. I have tried to add the
//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath*:EntityTest-context.xml"})

With no sucess. Here is the test that I am trying to run. If you notice I am creating the EntityManager on the @Before I don't know if this is a proper usage, because when I try to find the object that is created I get returned null.
package ienterprise.common.aspects;

import ienterprise.common.model.CompanyPosition;
import ienterprise.common.model.InternalUser;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceContext;

import static org.junit.Assert.assertEquals;
import org.springframework.test.context.ContextConfiguration;

//@RunWith(SpringJUnit4ClassRunner.class)
//@ContextConfiguration(locations = {"classpath*:EntityTest-context.xml"})
public class EntityTest {

    private static final Logger logger = LoggerFactory.getLogger(EntityTest.class);

//    @PersistenceContext(unitName="mysql") // FIXME inject this in unit tests
    private static EntityManager manager;

    @Before
    public void setUp(){
        EntityManagerFactory mngFactory = Persistence.createEntityManagerFactory("mysql");
        manager = mngFactory.createEntityManager();
    }

    @Test
    public void createUser(){

        InternalUser someGuy = new InternalUser();

        someGuy.setName("Adam");
        someGuy.setUser("Engineer");

        someGuy.create();

        logger.debug("created user: {}", someGuy);
        //FIXME: Can't find the user in the database.
        InternalUser foundUser = manager.find(InternalUser.class, 1L);

        logger.debug("fetched user: {}",foundUser);

        assertEquals( someGuy, foundUser);
    }
}

Our context xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:load-time-weaver/>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
        <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property>
    </bean>
</beans>

How can I remove the @Before and inject a PersistenceContext?
How can I make sure that my class has a Spring Context?
This is all new stuff for me, and I would appreciate some links to github repositories if there are any with this kind of Spring+Hibernate+AspectJ+JUnit setup.
Let me know if something is not clear or additional detail is necessary.


text:
Q: Using alternation and grouping constructs Originally I wanted a regex parsing month numbers. At first I came up with the following regex:
^([1-9]{1})|(1[012])$

and it matched any positive number, saying that it matched the high-order digit of the number, i.e.:
1 => 1
2 => 2
...
9 => 9
10=> 1
...
19=> 1
20=> 2
...

Why is that so? I thought that the alternation construct will make Regex choose either the left one or the right, while having ^ and & makes it match the whole string. What am I missing?
P.S.: I do have a working regex now (one that matches numbers from 1 to 12 only); it's:
^([1-9]{1}|1[012])$

And I can't catch why it works so....
This is the code I used to test:
Regex r = new Regex(@"^([1-9]{1})|(1[012])$");//^([1-9]{1}|1[012])$
for (int i = -5; i < 35; i++)
{
    Console.Write(i);
    Console.Write("\t");
    Match m = r.Match(i.ToString());
    if (m.Success)
        Console.WriteLine(m.Groups[0].Value);
    else
        Console.WriteLine("false");
}

A: Read the first regular expression like this:
^([1-9]{1})      # match this
|                # ...OR...
(1[012])$        # match this

Either match a digit 1-9 at the beginning of the string and store that in group #1, or match 10-12 at the end of the string and store that in group #2.
The first successful match is used, so when you match against 10 the ^([1-9]{1}) part of the regex matches. You can see why 20 is a match with this broken regex.
Also, you print out only group #1's contents and ignore group #2's. So if the second set of parentheses had happened to match, you wouldn't see that in your printout.
if (m.Success)
    Console.WriteLine(m.Groups[0].Value);

Your second regex fixes the problem by surrounding the two | alternatives with parentheses, leaving the ^ and $ anchors on the outside, and leaving only one set of parentheses so the result is always in group #1.
And for what it's worth, the {1} is unnecessary. You could write:
^([1-9]|1[012])$

A: The alternation operator has the lowest precedence of all regex operators.
The difference between the two regular expressions, interpreted literally, is this:
( [BEGIN]([1-9]) )    OR    ( (1[012])[END] )

vs
[BEGIN] ( [1-9]    OR    1[012] ) [END]


text:
Q: Filter azure cli output based on nested array values with jmespath I'm trying to filter the output from the following Azure CLI command based on the artifacts[].alias value.
Command
az pipelines release definition list --artifact-type build

Output (simplified)
[
    {
        "artifacts": [
            {
                "alias": "alias_with_suffix",
                "definitionReference": {
                    "IsMultiDefinitionType": {
                        "id": "False",
                        "name": "False"
                    }
                },
                "type": "Build"
            }
        ],
        "createdOn": "2021-06-16T15:15:07.620000+00:00",
        "id": 88,
        "isDeleted": false,
        "modifiedOn": "2021-09-15T10:39:14.257000+00:00",
        "revision": 5
    },
    {
        "artifacts": [
            {
                "alias": "alias",
                "definitionReference": {
                    "IsMultiDefinitionType": {
                        "id": "False",
                        "name": "False"
                    }
                },
                "type": "Build"
            }
        ],
        "createdOn": "2021-06-16T15:15:07.620000+00:00",
        "id": 88,
        "isDeleted": false,
        "modifiedOn": "2021-09-15T10:39:14.257000+00:00",
        "revision": 5
    },
    {
        "artifacts": null,
        "createdOn": "2021-06-16T15:15:07.620000+00:00",
        "id": 88,
        "isDeleted": false,
        "modifiedOn": "2021-09-15T10:39:14.257000+00:00",
        "revision": 5
    }
]

Expected Output
[
    {
        "artifacts": [
            {
                "alias": "alias_with_suffix",
                "definitionReference": {
                    "IsMultiDefinitionType": {
                        "id": "False",
                        "name": "False"
                    }
                },
                "type": "Build"
            }
        ],
        "createdOn": "2021-06-16T15:15:07.620000+00:00",
        "id": 88,
        "isDeleted": false,
        "modifiedOn": "2021-09-15T10:39:14.257000+00:00",
        "revision": 5
    }
]

So far i have tried the following:

*

*
az pipelines release definition list --artifact-type build --query "[artifacts[?ends_with(alias, '_suffix')]]"

*
az pipelines release definition list --artifact-type build --query "[].[artifacts[?ends_with(alias, '_suffix')]]"

*
az pipelines release definition list --artifact-type build --query "[].artifacts[?ends_with(alias, '_suffix')]"

I've also tried to use something like [*]..... or pipe results between commands like [] | []..... (with or without the *) but I always get something like [null] or some output with a list of null mixed with valid values.

A: For this, you will have to have a "nested" filter expression, because you are interested in the "parent" object based on the fact that a condition in the array of key artifacts is true.
So, given the query:
[?artifacts[?ends_with(alias, '_suffix')]]

You end up, with the JSON you provided as input, with this resulting JSON:
[
  {
    "artifacts": [
      {
        "alias": "alias_with_suffix",
        "definitionReference": {
          "IsMultiDefinitionType": {
            "id": "False",
            "name": "False"
          }
        },
        "type": "Build"
      }
    ],
    "createdOn": "2021-06-16T15:15:07.620000+00:00",
    "id": 88,
    "isDeleted": false,
    "modifiedOn": "2021-09-15T10:39:14.257000+00:00",
    "revision": 5
  }
]


text:
Q: Intersection between $\mathbb{R}P^2$ and $\mathbb{C}P^1$ I would like to compute the number of points in the intersection of $\mathbb{R}P^2$ and $\mathbb{C}P^1$ in $\mathbb{C}P^2$.
I choose $$\mathbb{R}P^2=\{ [x_0:y_0:z_0]\mid x_i\in\mathbb{R}\}$$
and $$\mathbb{C}P^2=\{[z_0:z_1:z_2]\mid  a_0 z_0+a_1z_1+a_2z_2=0\} $$
where $a_i\in\mathbb{C}$. So I need to compute the number of points satisying
$a_0 x_0+a_1x_1 a_2x_2=0$  where $a_i\in\mathbb{C}$ and $x_i\in\mathbb{R}$, but I don't know how to proceed. Any help would be appreciated.

A: They intersect in a circle = $\mathbb{RP}^{1}$. Just choose the line $\mathbb{CP}^{1}  \subset \mathbb{CP}^{2}$, given by the equation  $\{z_{2}=0\}$ (corresponding to the choice $a_{0}=a_{1}=0, a_{2}=1$), then the real points satisfying this equation are of the form $[x_{0}:x_{1}:0]$, where $x_{1},x_{2} \in \mathbb{R}$ (not both zero).
This is a copy of 1-dimensional real projective space, which is diffeomorphic to a circle.


text:
Q: use a capture between multiple RewriteCond given this url http://sub.domain.org/sub/other_string i need to have it rewritten to: http://newdomain/sub/...
i'm trying this rewrite, but i think i miss something in the RewriteCond.
in the second Cond can i use the capture of the first Cond?
    RewriteCond %{HTTP_HOST} ^(.*)\.domain\.org$
    RewriteCond %{REQUEST_URI} ^/%1/.*$ [NC]
    RewriteRule (.*) /%1/$1 [nosubreq,QSA,L]


text:
Q: Arduino Not Receiving Serial Data When Shield Attached I have nexus duino 3WD and tried to do serial comm to move the robot. I have to remove shield to upload sketch code. This is my sketch:
#include <fuzzy_table.h>
#include <PID_Beta6.h>

#include <PinChangeInt.h>
#include <PinChangeIntConfig.h>

#include <MotorWheel.h>
#include <Omni3WD.h>

#include <EEPROM.h>

#define _NAMIKI_MOTOR    //for Namiki 22CL-103501PG80:1

/*******************************************/

int incoming = 0;

int speed = 100;

// Motors

irqISR(irq1,isr1);
MotorWheel wheel1(9,8,6,7,&irq1);        // Pin9:PWM, Pin8:DIR, Pin6:PhaseA, Pin7:PhaseB

irqISR(irq2,isr2);
MotorWheel wheel2(10,11,14,15,&irq2);    // Pin10:PWM, Pin11:DIR, Pin14:PhaseA, Pin15:PhaseB

irqISR(irq3,isr3);
MotorWheel wheel3(3,2,4,5,&irq3);        // Pin3:PWM, Pin2:DIR, Pin4:PhaseA, Pin5:PhaseB

Omni3WD Omni(&wheel1,&wheel2,&wheel3);

/******************************************/

void setup() {
  Serial.begin(38400);
  Serial.println("setup");

  TCCR1B=TCCR1B&0xf8|0x01;    // Pin9,Pin10 PWM 31250Hz
  TCCR2B=TCCR2B&0xf8|0x01;    // Pin3,Pin11 PWM 31250Hz

  Omni.PIDEnable(0.26,0.02,0,10);
}

/****************************************/
void loop() {
  if(Serial.available() > 0) {
    incoming = Serial.read();
    Serial.print(incoming);
    if(incoming==0) {
      Omni.setCarStop();
    } else if(incoming==1) {
      Omni.setCarAdvance(speed);
    } else if(incoming==2) {
      Omni.setCarRotateLeft(speed);
    } else if(incoming==3) {
      Omni.setCarRotateRight(speed);
    }
  }
  Omni.PIDRegulate();
}

I tried to send data both from Serial Monitor and also PC app with USB cable. When shield is not attached I can send data and receive feedback from arduino. But when shield is attached it seem arduino not receiving data, the RX led flash but not the TX led, got 'setup' text output so arduino can send data to PC. Other thing is I can only use 38400 baud rate, otherwise the output will be garbagish.
I'm not sure if I do wrong in the code? Probably device power issues?

A: If you change the jumpers from RS-485 to Bluetooth like what it says here http://www.dfrobot.com/wiki/index.php/Arduino_I/O_Expansion_Shield_(SKU:_DFR0014)
then everything will work fine. uploading to the board without removing the shield might still be an issue, and sonars probably will not work, but at least you'll be able to read serial through the board.


text:
Q: drop down select value is show default I have select option value drop down looks like

    <select id="ddlCompare1" class="dropdown" onChange="javascript:CompareLoantype(true);" >
            <option value="jumbo">Conv</option>
            <option value="fha" selected >FHA</option>
            <option value="va">VA</option>
            <option value="usda">USDA</option>
    </select>

all four option value have single interest rate
<input name="Compare_interest_rate" id="Compare_interest_rate" class="txt"   type="text" size="6" maxlength="6" style="width:75%" />%

four  option value  have four default value
FHA value- <?php echo $interest_FHA_default; ?>
VA value-<?php echo $interest_VA_default;?>
USDA value- <?php echo $interest_USDA_default;?>
CONV  value- <?php echo $interest_CONV_default;?>
how to show four value depends on drop down select ?  if user select FHA  value need FHA  value .. please any one give me idea ?

A: In your onChange function do this:
function CompareLoantype() {
    var dd = document.getElementById('ddlCompare1');
    var selectedText = dd.options[dd.selectedIndex].text; // or .value if you want to show value
    document.getElementById('Compare_interest_rate').value = selectedText;
}


text:
Q: Assign the launchPad hotkey to another Application I'd like to set the launchPad key :

to the Application windows (See all) function but I can't manage to do it. Any clue ?

A: This isn't an ideal answer, but might be good enough:

*

*Go to System Preferences > Keyboard > Keyboard

*Check "Use all F1, F2, etc. keys as standard function keys"

*Go to System Preferences > Keyboard > Shortcuts

*Set F3 to "display application windows"

*Set the other functions on the f-keys to their default (e.g. whichever f-key your keyboard has for play/pause, mine is F8 will be set to iTunes Play/Pause)

This will let you set the F keys to the functions you want and you won't have to press fn to access them.


text:
Q: Is it possible to compile and run sample projects from the Apple developer library without using a GUI? I want to compile and run this application without using the Xcode GUI. Is this possible? I have so far only been successful with this baby step:
clang -framework AppKit main.m; ./a.out

But I need to compile and run the whole app, not just main.m.

A: Running xcodebuild will build the first Xcode project found in the current directory, using default settings. (If this isn't quite what you want, xcodebuild --help for more options.)


text:
Q: Bash — check if variable is different from any of many options If I have the code
if [[ this != that && this != another ]]

Is there a way to make it sorter? Something like
if [[ this !=that && != another ]]

Naturally that won't work, but something like that, that can shorten the conditions.

A: With bash, you can use regular expressions inside [[:
if [[ ! this =~ ^(that|another|this\ one)$ ]]; then
   # do something
fi

The precedence of the ! (not) operator might be confusing if you're used to any other programming language. Also, beware: do not put the regular expression in quotes. If you do, it is no longer a regular expression.


text:
Q: Mail for Access Request to O365 site not received if a Distribution Group's Mail-id is specified I have the Access Request feature enabled in my O365 SharePoint site. This functionality is working fine for a single site collection admin user's Email-ID and he is receiving the mail in his Outlook with an option to Approve/Deny the request. But when I specify the Email-ID of a Distribution Group (which consists of all the site collection admins), the mail is not sent to their respective inboxes although the corresponding request is listed under the Pending Requests in the Access Requests list in Site Settings. Why is this happening?
Also I would want to know what is the minimum permission level required to Approve/Deny these Access requests? Does the user needs to be a Site Collection Admin?

A: Site Owner can access the Site Access Request Page. So minimum permission is Site Owner.