text:
Q: How to extract JSX from class render method? I want to write something like SCSS for React Native: it'll parse your component jsx and the special SCSS-like styles and return a usual RN component with reworked styles and jsx.
Lets say we have this react code:
class MyClass extends Component {
  render() {
    return (
      <View style={styles.container}>
        <Text>I remember syrup sandwiches</Text>
      </View>
    );
  }
}

Also I have SCSS-ish styles where every Text component inside the parent with a container "class" will have the same props that we provided.
const styles = StyleSheet.create(
  toRNStyles({
    container: {
      Text: { color: 'red' },
    },
  })
);

In the end we need the output of something like this:
...
<View style={styles.container}>
  <Text style={styles._Text_container}>
    I remember syrup sandwiches
  </Text>
</View>
...

So how can I get the jsx that's returning from the render method from outside the class?

A: You might write a plugin for babel, as react-native uses it to transform JSX to plain javascript.
Have a look to the these packages:

*

*babel-helper-builder-react-jsx

*babel-plugin-syntax-jsx

*babel-plugin-transform-react-jsx

*babel-plugin-transform-react-jsx-source

*jsx-ast-utils

A: There doesn't seem to be a standard way of doing this. However, you could import ReactDOMServer and use its renderToStaticMarkup function.
Like this:

class MyApp extends React.Component {
  render() {
    var myTestComponent = <Test>bar</Test>;
    console.dir(ReactDOMServer.renderToStaticMarkup(myTestComponent));

    return myTestComponent;
  }
}

const Test = (props) => {
  return (

foo

      {props.children}

  );
}

ReactDOM.render(<MyApp />, document.getElementById("myApp"));

A: I think parsing the returned element is the wrong approach. One challenge will be that the value of style will be an object (styles.container === a hash of style key/values) whereas you need a key which can be mapped to the object.
I think the most reusable approach is to leverage React context (which I'm assuming RN supports!) to build a styleName which can be augmented as you got down the component tree.
Here's an initial approach which makes a few assumptions (e.g. that every component will have styleName provided as a prop; you might want to provide that at design-time rather than run-time). In short, you wrap every component you want to participate with this HOC and the provide styleName as a prop to each component. Those styleName values are concatenated to produce contextualized names which are mapped to styles.
This example produces:

Some Text

const CascadingStyle = (styles, Wrapped) => class extends React.Component {
  static displayName = 'CascadingStyle';

  static contextTypes = {
    styleName: React.PropTypes.string
  }

  static childContextTypes = {
    styleName: React.PropTypes.string
  }

  // pass the current styleName down the component tree
  // to other instances of CascadingStyle
  getChildContext () {
    return {
      styleName: this.getStyleName()
    };
  }

  // generate the current style name by either using the
  // value from context, joining the context value with
  // the current value, or using the current value (in
  // that order).
  getStyleName () {
    const {styleName: contextStyleName} = this.context;
    const {styleName: propsStyleName} = this.props;
    let styleName = contextStyleName;

    if (propsStyleName && contextStyleName) {
      styleName = `${contextStyleName}_${propsStyleName}`;
    } else if (propsStyleName) {
      styleName = propsStyleName;
    }

    return styleName;
  }

  // if the component has styleName, find that style object and merge it with other run-time styles
  getStyle () {
    if (this.props.styleName) {
        return Object.assign({}, styles[this.getStyleName()], this.props.styles);
    }

    return this.props.styles;
  }

  render () {
    return (
      <Wrapped {...this.props} style={this.getStyle()} />
    );
  }
};

const myStyles = {
  container: {backgroundColor: 'green', color: 'red'},
  container_text: {color: 'blue'}
};

const Container = CascadingStyle(myStyles, (props) => {
  return (

  );
});

const Text = CascadingStyle(myStyles, (props) => {
  return (

  );
});

const Component = () => {
  return (
    <Container styleName="container">
      <Text styleName="text">Some Text</Text>
    </Container>
  );
};


text:
Q: Unihan characters in comments This question asked in July explains why it is not possible for the time being to submit content in posts or comments that contains Unihan characters. It's a spammer thing, fair enough.
As snailboat's answer makes clear, the workaround for posts is to convert your Unihan text to HTML entities: these are parsed and appear correctly.
However, HTML entities are still HTML and as such are not parsed at all in comments, as this answer by AstroCB confirms. In other words, since Unihan glyphs are banned from both posts and comments and HTML entities are not parsed in comments, it seems to be completely impossible to post text containing Unihan glyphs in comments at all, except on sites where the ban has been manually removed, like Japanese.SE.
This seems like a rather substantial limitation. And in any case, the blanket ban on Unihan is unduly heavy-handed and inflexible (not to mention perplexing to the user, when the only feedback you get is "Body/comments cannot contain that content").
In this comment, tchrist suggested that the ability to post Unihan glyphs could be made a rep-based privilege; that is, a certain amount of reputation is required to include these glyphs, otherwise it fails. A requirement of, say, 125 rep points would presumably cut off at least 99.99% of spammers, and it would have the added benefit of being able to maintain—and broaden—the restriction indefinitely to mitigate spam, while still allowing legitimate users to post relevant content.
(The feedback message would have to be improved as well, though; something like, "Due to large volumes of spam written in certain non-Latin scripts, you need at least 125 reputation points to be able to include non-Latin text in your post" or words to that effect.)
Can this be implemented?
Alternatively, as pointed out in Normal Human's reply, since comments already require a certain amount of rep meant to deter absolute newcomers (and, by extension, also spammers), can the ban just be removed from comments and applied only to posts?
(Editing this just to bump it on the front page, to hopefully have some kind of discussion or feedback on the matter.)

A: The solution should be to simply drop the check for comments. They already require nontrivial reputation (even here on Meta), making other filters redundant.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Removing certain files on startup How do you, on startup, remove certain files from the computer. I guess you use stdlib but I can't find any functions for deleting files.
So. How do you delete files when the computer boots up ?


text:
Q: Ruby on Rails collection output in collection_select I've got this code:
    <%= collection_select :channel, @channelList, :id, :channelname, {prompt: (t "channel.add.prompt")}, class: "form-control"%>

And got this error:

Its a normal active relation

Whats my mistake in this case?
thanks

A: http://edgeapi.rubyonrails.org/classes/ActionView/Helpers/FormOptionsHelper.html#method-i-collection_select
You have to specify: object, method, collection, value_method, text_method, you probably forgot to set the object param.
Which would make this:
<%= collection_select :object, :channel, @channelList, :id, :channelname, {prompt: (t "channel.add.prompt")}, class: "form-control"%>

(replace :object with your object you want to save the channel to)


text:
Q: No unit test success value reported to sonar I am using Jenkins with Sonar to perform a build of my Java EE application through an ANT script.
The build works fine and the unit test case run fine as well.
I am currently getting a unit test coverage % but the "Unit test sucess" shows as zero. When I click on the "0 tests" which is available to me as a link on the Sonar dashboard, I get to see the different modules of my Java EE application which Sonar ran through as defined in the build.xml used by Jenkins.
After some research online and reading through a similar Stackoverflow question at this link - Unit test success reported as zero by Sonar
I added the following property tags in my build.xml (used by Jenkins) located in my Java EE application root folder and in the sonar.xml files residing in every sub folder which is defined as a module in the build.xml file:
<property name="sonar.java.coveragePlugin" value="jacoco" />
<property name="sonar.junit.reportsPath" value="ABCD/testreport/" />
<property name="sonar.jacoco.reportPath" value="ABCD/build/classes/jacoco.exec" />

where "ABCD" is the directory which I use to house my Junit test case JAVA files.
The ANT script xml file does contain a junit task which compiles executes my unit test cases in the Jenkins build before giving the hanndle to Sonar. Since I know I am getting a unit test coverage, I know these unit tests are being seen to a degree but what additional steps do I need to take to make the unit test success show up with a value greater than zero?
Please advise.
Thanks in advance.
Subbu


text:
Q: Rotating Image script not keeping preset classes Im using a script to rotate through various images stored in an un-ordered list. The script is working, but seems to remove preset classes applied to a specific Li. I want the script to work exactly as it is currently, but not remove a class that I set on an Li. Can someone offer some suggestions or modifications? Thank you. See the example fiddle here:
http://jsfiddle.net/trobbins26/5U4Cr/5/

Or script below:
function theRotator() {
        //Set the opacity of all images to 0
        $('div.rotator ul li').css({opacity: 0.0});

        //Get the first image and display it (gets set to full opacity)
        $('div.rotator ul li:first').css({opacity: 1.0});

        //Call the rotator function to run the slideshow, 6000 = change to next image after 6 seconds

        setInterval('rotate()',4000);

        }

        function rotate() {
        //Get the first image
        var current = ($('div.rotator ul li.show')?  $('div.rotator ul li.show') : $('div.rotator ul li:first'));

        if ( current.length == 0 ) current = $('div.rotator ul li:first');

        //Get next image, when it reaches the end, rotate it back to the first image
        var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div.rotator ul li:first') :current.next()) : $('div.rotator ul li:first'));

        //Un-comment the 3 lines below to get the images in random order

        //var sibs = current.siblings();
        //var rndNum = Math.floor(Math.random() * sibs.length );
        //var next = $( sibs[ rndNum ] );

        //Set the fade in effect for the next image, the show class has higher z-index
        next.css({opacity: 0.0})
        .addClass('show')
        .animate({opacity: 1.0}, 500);

        //Hide the current image
        current.animate({opacity: 0.0}, 1000)
        .removeClass('show');

        };
setTimeout(function(){
        $(document).ready(function() {
            //Load the slideshow
            theRotator();
            $('div.rotator').fadeIn(500);
            $('div.rotator ul li').fadeIn(500); // tweek for IE
        });
        }, 500);

A: This script is not the problem, you must have another script stripping out the classes.  I must mention, however, that you do not currently have any "preset" classes on your list items currently.  The only class being applied is the "show" class which is expected.  This class is properly being removed, also as expected.
I've reproduced your slider with two classes (that offer background colors for emphasis) to demonstrate that this does indeed work.  I did not change any of the jquery.
View the demo here: http://fluidev.com/stack/rotate.html


text:
Q: useContext is not working in my react code App Component:
    import React,{createContext} from "react";
    import "./style.css";
    import A from "./A";

    export const userContext =createContext();

    function App() {
      return (
        <userContext.Provider name={"samuel"}>

        </userContext.Provider>
      );
    }
    export default App;

Component A
    import React from 'react';
    import B from './B';
    function A(){
      return (

Component A

)
    }

    export default A;

Component B:
        import React, { useContext } from "react";
        import {userContext} from "./App";

    function B() {
      const name = useContext(userContext);
      return (

Component B{name}

      );
    }

    export default B;

The context value that I passed at App component is not getting consumed at Component B.
Context is used to pass data directly to an component instead of being passing to each component that comes in the path of the destination component.
So that the component that does not require the data do not get access to it.
I am using useContext hook instead of Context.consumer api at the receiver component.

A: You have to pass a value to the Provider in this case you want to pass a string, whereas you were previously passing an object with the wrong keyword name.
Another issue I found was that you were using B to extract the value from context but you were not placing it under the scope of which components have access to the context:
function App() {
  return (
    <userContext.Provider value="samuel">

    </userContext.Provider>
  );
}
export default App;

This works now and you can check the codesandbox.


text:
Q: Spotify Follow Count Num I added the Spotify Follow Button Embed Code for our wordpress website.
Question: Is there a way to hide the number for followers the user have, the one showing on right after the follow button.

A: Yes, it's possible to hide the follower count. Simply append show-count=0 in the uri attribute.
Read more in the documentation for the Spotify Play Button.


text:
Q: Setting the initial state of a controlled input with a prop value that is initialized asynchronously I have a controlled input that accepts a prop called user. This object is passed to it by its parent component, where it is initialized asynchronously with an observer1.
In the parent component:
onAuthStateChanged() {
  this.unregisterAuthObserver = onAuthStateChanged((user) => {
    this.setState({
      isSignedIn: Boolean(user),
      user,
    });
  });
}

I would like to populate the initial state of the controlled input with user.displayName. Something like the following, which shouldn't be an anti-pattern because the state is only dependent on the prop user on construction.
class ControlledInput extends Component {
  constructor(props) {
    super(props);

    const { user } = props;

    this.state = {
      displayName: user ? user.displayName : '',
    };
  }
}

When I refresh the controlled input, the following problem occurs:

*

*The value of user is undefined because the observer has yet to fire. The component is constructed and displayName is assigned to ''.

*The observer fires, user is assigned a complex object, and React re-renders the component. This does not change the state of the component and displayName is still ''.

I'm stuck on how to utilize the component lifecycle methods to achieve this. Is there a best practice for this scenario? Should I even be dependent on an asynchronous prop, or should I move the observer into the controlled component?
I've considered using componentDidUpdate() to determine when user is assigned, but it feels like a hack.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

1 The observer is part of Firebase Authentication, but I'm not sure that's relevant to the question.

A: There is no need to assign in the constructor. You should use the props provided to the render method, and following the Lifting State Up pattern handle updates to the state in the parent. That will then flow down to the child component.
See the example below. The "increment" button simulates the async call. ControlledInput is a read-only display, while ControlledInput2 allows edits to the input that are reflected in state.

class Parent extends React.Component {
  constructor(props) {
    super(props);

    this.handleClick = this.handleClick.bind(this);
    this.onInputChanged = this.onInputChanged.bind(this);

    this.state = {
      user,
      count: 1
    };
  }

  handleClick(e) {
    const { user, count } = this.state;

    this.setState({
      user: { ...user, displayName: `display ${count + 1}` },
      count: count + 1
    });
  }

  onInputChanged(name) {
    this.setState({
      user: Object.assign(user, { displayName: name })
    });
  }

  render() {
    const { user, count } = this.state;

    return (

        <ControlledInput user={user} />

{user.displayName}

Count: {count}

        <button onClick={this.handleClick}>increment</button>

          <ControlledInput2 onInputChanged={this.onInputChanged} user={user} />

    );
  }
}

const ControlledInput = ({ user }) =>
  <input type="text" value={user.displayName} />;

class ControlledInput2 extends React.Component {
  constructor(props) {
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e) {
    this.props.onInputChanged(e.target.value);
  }

  render() {
    const { user } = this.props;
    return (
      <input
        type="text"
        onChange={this.handleChange}
        value={user.displayName}
      />
    );
  }
}

const user = { displayName: undefined };

const props = { user };
const rootElement = document.getElementById("sample");
ReactDOM.render(<Parent {...props} />, rootElement);


text:
Q: Service Fabric Error: Not authorized to connect I am attempting to run a Service Fabric example found here:
Service Fabric Getting Started Sample
I am loading it into Visual Studio 2017 CE.  I have set the Fabric app as the startup project and it appears to build and deploy just fine.

The Service Fabric dashboard shows everything up and running.

However, when I try to connect using the example WebService project I get the following error:
WebService> Unhandled Exception: System.Fabric.FabricConnectionDeniedException: Not authorized to connect ---> System.Runtime.InteropServices.COMException: Exception from HRESULT: 0x80071C43
WebService>    at System.Fabric.Interop.NativeRuntime.FabricEndGetNodeContext(IFabricAsyncOperationContext context)
WebService>    at System.Fabric.FabricRuntime.NativeFabricRuntimeFactory.GetNodeContextEndWrapper(IFabricAsyncOperationContext context)
WebService>    at System.Fabric.Interop.AsyncCallOutAdapter2`1.Finish(IFabricAsyncOperationContext context, Boolean expectedCompletedSynchronously)
WebService>    --- End of inner exception stack trace ---
WebService>    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
WebService>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
WebService>    at Microsoft.ServiceFabric.Services.Runtime.RuntimeContext.<GetOrCreateAsync>d__14.MoveNext()
WebService> --- End of stack trace from previous location where exception was thrown ---
WebService>    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
WebService>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
WebService>    at Microsoft.ServiceFabric.Services.Runtime.ServiceRuntime.<RegisterServiceAsync>d__0.MoveNext()
WebService> --- End of stack trace from previous location where exception was thrown ---
WebService>    at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
WebService>    at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
WebService>    at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
WebService>    at WebService.Program.Main()

I've seen where people get this because they have changed the startup project to something other than GettingStartedApplication, unfortunately that's not my issue.

A: Set Service Fabric applications(Orange color projects) as the Startup Projects  and not the .Net projects and  then the error should be gone

A: As I dug through the WebService web.config I found the port to use to connect to the example application (port 8081).  I was trying to launch an instance of the WebService in debug mode (not fully understanding how the example worked) and that's why I got the error message.  Hopefully this will help someone else.


text:
Q: How the send a webform by email I have a task in hand that requires me to send a form to a client by email as soon as it is submited.
My question is: Having an aspx(in order to reuse my form) how can I get the generated html to send it by mail?
Thanks in advance
EDIT:
I know how to send emails, what I am looking for is how to get the html that is generated in my webform so i can place it in the email.

A: You should be able to call Render on it and stream it.
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
Page.RenderControl(htmlWriter);
string output = stringWriter.ToString();

A: Using the SmtpMail class in System.Web?


text:
Q: ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list). eventhough the data is numpy I am trying to use BERT model which gives attention, input ids, token type ids.
But when I tried to convert my dataset to TF Dataset, it throws the error below:
ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list).

I tried looking at ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type list) but it didn't solve my issue. Please see the code below.
for fold in range(5):
       train_fold = train[train['kfold'] != fold]
       valid_fold = train[train['kfold'] == fold]

       X_train_dataset = (X_train[0][train_fold.index.to_list()], X_train[1]
          [train_fold.index.to_list()],
          X_train[2][train_fold.index.to_list()])

       train_dataset = (
             tf.data.Dataset
                .from_tensor_slices((X_train_dataset, train_fold['discourse_effectiveness'].values))
              .repeat()
               .shuffle(2048)
              .batch(BATCH_SIZE)
              .prefetch(AUTO)
                )

When I look at the type of dataset as below:
for x in X_train_dataset:
      print(type(x))
type(train_fold['target'].values)

<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
<class 'numpy.ndarray'>
numpy.ndarray

A: I have solved the same using the way I store the input_ids, attention_mask and token type ids.
I tried using np.zeros((df.shape[0], 256)) and then added the data


text:
Q: Insert distinct values into table with IDs Let's say I have the following table:
camp_1, camp_2
0, 048
00, 048
000, 042
000, 043

I now want to insert these values into a new table dim_promotion, which should look like this:
PromotionID, CampaignID, CouponID
1, 1, 1
2, 2, 1,
3, 3, 2,
4, 3, 3

I know how I can fill the tables (dim_campaigns and dim_coupons which stand behind CampaignID and CouponID) by doing this:
    INSERT INTO [REPORTING].dbo.dim_campaigns
SELECT DISTINCT
camp_2  AS CampaignID
FROM [reporting2].[dbo].[reporting_rawdata_v2]

The primary keys for the respective three tables (dim_coupons, dim_campaigns and dim_promotion) are all set to "Identity Specification = YES"
So how do I then fill dim_promotion? What is the natural order? FIrst derive dim_campaigns and dim_coupons and then isnert this into dim_promotion or the other way round?
EDIT: I have the following DB model (only an excerpt) I am only referring to the yellow fields.
RIght now, we have only large table (rawdatatbl) where all data is stored (CampaignCode, CouponCode, Campaign Name, CouponName). This is not really efficient and that's why I want to compeltely restructure the model (see the screenshot). So, as currently the data does not consist of any IDs at all, I do need IDs to fill the new tables dim_campaigns and dim_coupons. This means: To fill dim_campaigns I would run a SELECT DISTINCT campaign_code on my current rawdatatbl and then Insert this into dim_campaigns (CampaignID is automatically filled by using auto_increment and CampaignName is filled with 'Dummy'). The same I could do for dim_coupons. But how can I then use this data to initialize the Dim_promotion table? Or what is the best process to transform my current data from rawdatatbl into IDs?

A: one possible way is :-
---- insert your all distinct Campaign data
Insert Into dim_campaigns(CampaignCode,CampaignName)
Select  Distinct
         cm.CampaignCode
        ,cm.CampaignName
From    rawdatatbl As cm

---- insert your all distinct Coupon data
Insert Into dim_coupons(CouponCode,CouponName)
Select  Distinct
         c.CouponCode
        ,c.CouponName
From    rawdatatbl As c

Declare  @Total             Int
        ,@Inc               Int
        ,@RowId             Int
        ,@CampaignCode      Varchar(100)
        ,@CouponCode        Varchar(100)

        ----Primary keys
        ,@CampaignId        Int
        ,@CouponId          Int
        ,@PromotionID       Int

Select   @CampaignCode = ''
        ,@CouponCode = ''

----loop through one by one and take necessary action
Select   @Total = Count(1)
        ,@Inc = 0
        ,@RowId = 0
From    rawdatatbl As c With (Nolock)

While (@Inc < @Total)
Begin
    Select  Top 1
             @RowId = [TableUniqueId]
            ,@CampaignCode = c.CampaignCode
            ,@CouponCode = c.CouponCode
            ---- others columns
    From    rawdatatbl As c
    Where   [TableUniqueId] > @RowId
    Order By [TableUniqueId] Asc

    Select  @CampaignId = dc.CampaignId
    From    dim_campaigns As dc
    Where   dc.CampaignCode = @CampaignCode

    Select  @CouponId = dc.CouponId
    From    dim_coupons As dc
    Where   dc.CouponCode = @CouponCode

    If (@CampaignId > 0 And @CouponId > 0)
    Begin
        Insert Into dim_promotion(CampaignID,CouponID)
        Select  @CampaignId,@CouponId

        Select  @PromotionID = @@Identity

        ---- other operation insert/update based on @PromotionID you can do here.
    End

    Select   @Inc = @Inc + 1
            ,@CampaignCode = ''
            ,@CouponCode = ''
            ,@CampaignId = 0
            ,@CouponId = 0
End


text:
Q: Writing SAML2 claim aware asp.net application I have a web application (.Net 4.0) that uses WIF and ADFS for SignON. In ADFS my application is configured  as WS-Fed protocol / SAML 1 Token relying party.  Now I have requirement to allow my-application to accept redirect from client application using SAML 2 token.
Based on on-line resources most likely I will have to perform steps
1. Set ADFS trust between both Organizations
2. Switch my-Application Relying party trust from WS-Fed to WS-SSO.
3. Write Assumer Assertion Service (new page in my application) to accept SAML token
Question
1. Are above steps enough? What else I have to do?
2. Is it required to change my application to use WS-SSO?  Can ADFS be configured to receive SAML2 from client but send SAML1 to my application? If so how can this be achieved?
3. Since WIF does not work with SAML-P what how can I make my application accept SAML 2 token?
Will appreciate any sample / reference / solution to above requirement.

A: Don't write your own Assertion Consumer Service for accepting tokens. Use an existing component/library. There are commercial options available, as well as open source. I maintain Kentor.AuthServices which is an SP implementation for ASP.NET (requires .NET 4.5).


text:
Q: qml access to kde's kwallet I'm writing a kde plasmoid using qml. It's a widget, displaying mobile usage for one of largets mobile priveders in our country, using the api provided by the operater. In order to get the data one must do a request using phone number + password and I'd like to use kwallet to store "accounts" in some kwallet's folder for this widget.
The question is, how do I use kwallet in qml/javascript based widget, if it is even possible? I can't find any info on the web. I found this plasmoid using kwallet: http://kde-look.org/content/show.php/gmail-plasmoid?content=101229
but this one is written in python and is importing some python kde libs, so I can't really use that. Any suggestions or even links to some usefull api would be great.

A: Kwallet can be accessed using qdbus on the command-line. And apparently there is a way to make command-line calls in Javascript plasmoids using the extension LaunchApp, like this:
Button {
    onButtonClick: plasmoid.runCommand("qdbus",
        ["<add-missing-parameters-here>"]);
}

For the extension to work, you need to add this line to your desktop file:
X-Plasma-RequiredExtensions=LaunchApp

The exact command-line calls go something like this:

*

*Make a call to open the wallet
qdbus org.kde.kwalletd /modules/kwalletd org.kde.KWallet.open <wallet name> 0 "<your application name>"

*Use the returned ID to acess a password
qdbus org.kde.kwalletd /modules/kwalletd readPasswordList <wallet-id> kmail "<entry name>" "<your application name>"

I haven't tried any of this, but theoretically it could work.
Links:

*

*Example using runCommand: http://server.ericsbinaryworld.com/blog/2012/06/06/developing-my-first-plasmoid-the-qml-code/

*LaunchApp documentation: http://techbase.kde.org/Development/Tutorials/Plasma/JavaScript/API-LaunchApp

*Wallet access using the command-line: http://learnonthejob.blogspot.de/2009/11/accessing-kde-wallet-from-cmdline.html


text:
Q: Visual Studio Code git/source control gutter stopped showing Working with VS Code, the explorer git status gutter indicators stopped showing for one of my repositories.

*

*I tried rebooting VS Code, My PC

*I tried removing the index file and
git reset

Those didn't resolve the issue.
(Git changes are still tracked in the Source Control Manager panel)

A: This started happening to me when opening subdirectories from a monorepo.
I had to to set the "Open Repository In Parent Folders" setting to "always" to make it work.

Or in json:
"git.openRepositoryInParentFolders": "always"

Not sure when this option has appeared or default changed because the git gutter used to work without this setting.

A: It took me a long while to figure this one out. My changes were still being seen by VSCode and Gitlens, but they were not being tracked in the gutters... for SOME files. Uninstalling VSCode and re-installing would allow tracking for a bit, but even with all extensions off, it would eventually stop tracking in the gutter.
My solution:
I had renamed a few folders by changing the case. Git was not set to track case-sensitive, my Mac was viewing them as the same file, and VSCode was just being VSCode... Going back and renaming the files through Git ended up fixing the issue:
git mv navigation tmp
git mv tmp Navigation

successfully updated it. If it isn't working, I also had to updated git global (temporarily) and pushed with:
git config --global core.ignoreCase false

A: Apparently another common reason for this is that you are accessing your git repo through a symlink. See: https://github.com/microsoft/vscode/issues/60010#issuecomment-433424527
This was the case for me and redirecting vscode to open the folder via the full path fixed it.

A: Solution for me has been to delete my folder (after saving/pushing it on the remote) and cloning the repo again.

A: In my case, the gutter doesn't show if the folder path contains a ., like /home/user.focus/folder
Change the path to one without . works for me.

A: I have encountered this issue and found out that deleting my workspace file and then creating it anew has resolved the problem.
I have found out this was only happening in one workspace and not the others. Something in my workspace file must have gotten messed up somehow. When I opened another workspace, the gutter icon highlighting worked fine, but then when I went back to the problematic workspace it was still not showing up.


text:
Q: Autocad startup LISP code broken after network reset I have a network with a few different drives on it with AutoCAD installed on my local.
I have a startup LISP routine for AutoCAD that loads a variety of other .lsp files, which are called by custom commands in AutoCAD, located in various drives across the network.
Up until yesterday it all worked fine, no errors, always loaded all the .lsp files. But after I reset a couple drives on the network the .lsp files located in those drives are no longer being recognized.
Nothing has changed programmatically. I've re-added all the network locations to the "Trusted" and "Support File" paths in AutoCAD's options and made sure the startup LISP is loaded in the APPLOAD menu.
Any ideas?

A: Assuming that you are using the Startup Suite as part of the APPLOAD command dialog to automatically load your 'Startup' LISP program (which then subsequently loads other program files), I would instead  suggest using the acaddoc.lsp file to automatically load your programs, as this is a far more reliable loading method.
To load programs using the acaddoc.lsp, perform the following procedure:

*

*Check whether or not an acaddoc.lsp already exists. To do this, open AutoCAD to a new blank drawing, and type at the AutoCAD command-line:
(findfile "acaddoc.lsp")

*

*If this returns a valid filepath, in the steps that follow, navigate to the filepath and open & modify the existing acaddoc.lsp using Windows Notepad or other plain text editor.

*If the above expression returns nil, open Windows Notepad (or other plain text/code editor), and create a new acaddoc.lsp in a Trusted AutoCAD Support File Search Path.

*On a new line in the acaddoc.lsp, enter the desired load or autoload expressions to load your custom programs, e.g.:
(load "MyProgram.lsp" "MyProgram.lsp failed to load.")

(autoload "MyProgram.lsp" '("MyCommand"))

*Save the new/modified file and open a new drawing in AutoCAD to automatically load it.

Some Background on the acaddoc.lsp File
To provide a little background information on the nature and behaviour of the acaddoc.lsp file in AutoCAD: when opening a drawing, AutoCAD will search the Working Directory (that is, the directory in which the active drawing resides), and all Support File Search Paths (those listed in the Files tab of the Options dialog) for a file with the filename acaddoc.lsp.
In more recent AutoCAD releases in which the SECURELOAD system variable is present, only paths which are also listed as Trusted Paths will be considered by this search1.
When such a file is found, AutoCAD will cease searching and will proceed to load the acaddoc.lsp file into the active drawing namespace.
The act of loading a LISP file simply means that the contents of the file are read and any LISP expressions found therein are evaluated by the LISP interpreter.
In this way, most users will utilise the acaddoc.lsp to automatically load custom programs when a drawing is opened, so that such programs are available during the drawing session. This is a more reliable and migratable method than using the Startup Suite for the same purpose.

Similar Autoloading Files
Aside, note that the acaddoc.lsp is not the only file that is automatically sought and loaded into the active drawing...
When the AutoCAD application is initially opened, a number of files are automatically loaded and others are reloaded again when every drawing is opened thereafter.
Most of these files are part of the application itself and hence should not be modified, others however are reserved for user customisation and can be modified and created if they don't already exist.
Below is the loading order of the various files that are automatically loaded into AutoCAD, with a brief description about each item:

*

*acad.rxThis file loads various ObjectARX applications when AutoCAD is started.

*acad20##.lspThis file loads the acad20##doc.lsp file in versions which do not load such file automatically. This file should not be modified.

*acad.lspThe loading of this file is dependent on the setting of the
ACADLSPASDOC system variable:

*

*ACADLSPASDOC = 0 (default) Loads acad.lsp into just the first drawing opened in an AutoCAD session, and will not load for each subsequently opened drawing.

*ACADLSPASDOC = 1 Loads acad.lsp into every drawing opened.
This file is reserved for user customisation and is intended to be used for application-specific startup routines, as all functions and variables defined in an
acad.lsp file are only available in the first drawing.
If functions are required in all drawings, rather than altering the value of
ACADLSPASDOC, functions & programs should be moved from the acad.lsp file into the acaddoc.lsp file.

*acad20##doc.lspThis file is automatically loaded every time a drawing is opened and loads the autoload function definiton and other utility functions required by AutoCAD. This file should not be modified.

*acaddoc.lspAs described above, if found, this file is automatically loaded into every drawing opened in the AutoCAD session. This file is useful for loading a library of AutoLISP functions to be available every time a drawing is opened.
The acaddoc.lsp file is always loaded with each drawing regardless of the settings of the ACADLSPASDOC system variable.
Since AutoCAD will search the working directory before the Support File Search Paths and will load the first acaddoc.lsp file found, users can have a different acaddoc.lsp file in each drawing directory, which would load specific AutoLISP routines for certain types of drawings or jobs.2

*acad.dvbThis file will automatically load VBA projects for versions in which VBA is enabled.

*Main CUI/CUIX and related filesA CUIx file contains multiple XML based files and image files, each of which contains the data for a user interface element that can be customised. CUIx files replace the CUI, MNU, MNS, and MNC files that were used to define menus in previouse releases.
The Main CUIx file defines the majority of interface elements in AutoCAD.

*Enterprise CUI/CUIX and related filesThe Enterprise CUIx file is typically controlled by a CAD manager and accessed by many users, usually from a shared network location.
This file is read-only to users to prevent the data in the file from being changed. A CAD manager would create an enterprise CUIx file by modifying a Main CUIx file and then saving the file to a shared network location.

*acetmain.mnlThis file loads the Express Tools menugroups.

*Express Tools LISP & MNL filesThe various LISP and Menu files required by the Express Tools programs are loaded here.

*Startup Suite programsPrograms files residing in the Startup Suite are now loaded, in the order they appear in the APPLOAD dialog.
As noted above, the Startup Suite is known to be temperamental in some versions of AutoCAD, so I would recommend using the acaddoc.lsp for loading functions and programs required during the drawing session.

*(S::STARTUP)This post-initialisation function can be utilised to perform operations after the drawing has initialised in the drawing editor.
Since the acad.lsp and acaddoc.lsp files are loaded early in the drawing initialisation procedure, commands issued at run-time from these files may be unsuccessful as the command-line may not be initialised in the drawing.

*acad.exe command-line switch /bThe command-line switch /b can be used to run a Script when the AutoCAD application is launched. Any Script operations called in this way will be executed after drawing initialisation has completed.
Command-line switches can be set from within the properties of the AutoCAD application shortcut icon, within the Target edit box.

Footnotes
1 This was introduced to mitigate against AutoCAD 'viruses' in which a drawing file would be sent to a third-party along with an accompanying malicious acaddoc.lsp file residing in the same folder, such that when the drawing file was opened, AutoCAD would automatically evaluate the malicious acaddoc.lsp file.
2 This is only possible if the SECURELOAD system variable is set to 0.


text:
Q: Facebook Workplace API - How can I get user by username using API? I have tried retrieving a user using the API endpoint scim/v1/Users?filter=userName eq "xxxxxxxxxx@xxxx.com" But this endpoint works properly only when the username and email address of the user are same.
There are two cases:

*

*When username and email address is different, if tried sending the above API with username it returns 0 results and if tried with the email assigned by facebook (xxxxxxxxxx@emailless.facebook.com), it does give correct result. But this email address is not visible on the user profile. So, how can I locate this email on the UI?

*When username and email address is same, it gives the expected result.
Though in the API documentation, it is mentioned that the API works for both username/email address.

Note: I tried the same with v2 APIs but the behavior is same as v1.
enter image description here


text:
Q: Why is my constructed formula giving different results than the same formula as UDF in Excel? Here's a long formula to calculate  distance between two coordinates points on Earth

=ACOS(COS(RADIANS(90-LAT1)) *COS(RADIANS(90-LAT2)) +SIN(RADIANS(90-LAT1)) *SIN(RADIANS(90-LAT2)) *COS(RADIANS(Long1-Long2))) *6371

As it is a bit cumbersome to use inside other formulas, I wrote a user defined function for that.

Function DistXY(Lat1 As Single, Lng1 As Single, Lat2 As Single, Lng2
  As Single) As Single
DistXY = WorksheetFunction.Acos(Cos(WorksheetFunction.Radians(90 -
  Lat1)) * Cos(WorksheetFunction.Radians(90 - Lat2)) +
  Sin(WorksheetFunction.Radians(90 - Lat1)) *
  Sin(WorksheetFunction.Radians(90 - Lat2)) *
  Cos(WorksheetFunction.Radians(Lng1 - Lng2))) * 6371
End function

As you can see, they're exactly the same. As there's no Acos ou Radians functions in VBA, it even uses the "worksheetFunction" method.
Why is that when I apply theses formula to the same pair of XY coordinates, I get different results ?
For example:
From ABC    45.4960674,-73.514446   to  XYZ 43.5369,-71.8592
DistXY() results:    254.313156128
Long formula method: 254.313268914
Going along with the comment of @raystafarian , changing all the types to double improved the precision. But there's still a difference.

Function DistXY(Lat1 As double, Lng1 As double, Lat2 As double, Lng2
  As double) As double ...

New results:
DistXY() :           254.3132689135060 km
Long formula method: 254.3132689135250 km

A: You're using (and returning) a data type of single. This will cause functions to evaluate differently if they take a different data type of default.

*

*Acos - Double

*Cos - Double

*Sin - Double

*Radians - Double

A: Based on Raystafarian's answer:
Public Function DistXY(Lat1 As Double, Lng1 As Double, Lat2 As Double, Lng2 As Double) As Double
   Dim i As Double, f As Double
   Dim wf As WorksheetFunction
   Set wf = Application.WorksheetFunction

   i = 90
   f = 6371

   DistXY = wf.Acos(Cos(wf.Radians(i - Lat1)) * Cos(wf.Radians(i - Lat2)) + Sin(wf.Radians(i - Lat1)) * Sin(wf.Radians(i - Lat2)) * Cos(wf.Radians(Lng1 - Lng2))) * f
End Function


text:
Q: matlab get_param for scope I need to change the variable name of a scope.
How can I do it with code?
Seems get_param does not work for scopes.
get_param('untitled/scope','DialogParameters')

ans =

struct with no fields.

A: To discover (most/many of) the settable/gettable properties for the standard library blocks have a look at the first link returned by
>> docsearch('Block-Specific Parameters')

Specifically, for the variable you are looking for,
>> get_param('untitled/Scope','SaveName')
ans =
ScopeData
>> set_param('untitled/Scope','SaveName','NewName')


text:
Q: Order of the selected rows are not remembered when I refresh a JSF page I have a very strange bug into jsf page which I cannot find. This is the code of the JSF page:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <h:head>
        <ui:insert name="header">
            <ui:include src="header.xhtml"/>
        </ui:insert>
    </h:head>
    <h:body>

 History Center

            <ui:insert name="Navigation">
                <ui:include src="Navigation.xhtml"/>
            </ui:insert>

            <h:graphicImage alt="Dashboard"  style="position:relative; top:-20px; left:9px;"  value="resources/images/logo_sessions.png" />

                    <h:form id="form">

                        <ui:debug />

                        <h:dataTable id="dataTable" value="#{SessionsController.dataList}" binding="#{table}" var="item">

                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Select" />
                                </f:facet>
                                <h:selectBooleanCheckbox onclick="highlight(this)" value="#{SessionsController.selectedIds[item.aSessionID]}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="№" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="№" value="№" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{table.rowIndex + SessionsController.firstRow + 1}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="Account Session ID" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="sortField" value="Account Session ID" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{item.aSessionID}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="User ID" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="sortField" value="User ID" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{item.userID}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="Activity Start Time" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="sortField" value="Activity Start Time" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{item.activityStart}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="Activity End Time" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="sortField" value="Activity End Time" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{item.activityEnd}" />
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:commandLink value="Activity" actionListener="#{SessionsController.sort}">
                                        <f:attribute name="sortField" value="Activity" />
                                    </h:commandLink>
                                </f:facet>
                                <h:outputText value="#{item.activity}" />
                            </h:column>
                        </h:dataTable>

                        <h:commandButton value="first" action="#{SessionsController.pageFirst}"
                                         disabled="#{SessionsController.firstRow == 0}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>

                        <h:commandButton value="prev" action="#{SessionsController.pagePrevious}"
                                         disabled="#{SessionsController.firstRow == 0}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>

                        <h:commandButton value="next" action="#{SessionsController.pageNext}"
                                         disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>

                        <h:commandButton value="last" action="#{SessionsController.pageLast}"
                                         disabled="#{SessionsController.firstRow + SessionsController.rowsPerPage >= SessionsController.totalRows}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>

                        <h:outputText value="Page #{SessionsController.currentPage} / #{SessionsController.totalPages}" />

                        <ui:repeat value="#{SessionsController.pages}" var="page">
                            <h:commandLink value="#{page}" actionListener="#{SessionsController.page}"
                                           rendered="#{page != SessionsController.currentPage}" >
                                <f:ajax render="@form" execute="@form"></f:ajax>
                            </h:commandLink>
                            <h:outputText value="#{page}" escape="false"
                                          rendered="#{page == SessionsController.currentPage}" />
                        </ui:repeat>

                        <h:outputLabel for="rowsPerPage" value="Rows per page" />
                        <h:inputText id="rowsPerPage" value="#{SessionsController.rowsPerPage}" size="3" maxlength="3" />
                        <h:commandButton value="Set" action="#{SessionsController.pageFirst}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>
                        <h:message for="rowsPerPage" errorStyle="color: red;" />

                        <h:commandButton value="Delete" action="#{SessionsController.deleteSelectedIDs}" >
                            <f:ajax render="@form" execute="@form"></f:ajax>
                        </h:commandButton>

                    </h:form>

    </h:body>

This is the managed bean:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/*
 * include SQL Packages
 */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UICommand;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import javax.faces.event.ActionEvent;

import org.glassfish.osgicdi.OSGiService;

@Named("SessionsController")
@ViewScoped
public class Sessions implements Serializable {

    /*
     * Call the Oracle JDBC Connection driver
     */
    @Resource(name = "jdbc/Oracle")
    private DataSource ds;
    // Data.
    private List<ActiveSessionObj> dataList;
    // Rows
    private int totalRows;
    // Paging.
    private static int firstRow;
    private int rowsPerPage;
    private int totalPages;
    private int pageRange;
    private Integer[] pages;
    private int currentPage;
    // Sorting.
    private String sortField;
    private boolean sortAscending;

    /*
     * Constructor
     */
    public Sessions() {
        /*
         * Set default properties
         */
        rowsPerPage = 10; // Default rows per page (max amount of rows to be displayed at once).
        pageRange = 10; // Default page range (max amount of page links to be displayed at once).
        sortField = "ASESSIONID"; // Default sort field.
        sortAscending = true; // Default sort direction.
    }

    public class ActiveSessionObj {

        private String aSessionID;
        private String userID;
        private Date activityStart;
        private Date activityEnd;
        private String activity;
        //private boolean selected;

        public ActiveSessionObj(String aSessionID, String userID, Date activityStart, Date activityEnd, String activity) {
            this.aSessionID = aSessionID;
            this.userID = userID;
            this.activityStart = activityStart;
            this.activityEnd = activityEnd;
            this.activity = activity;
        }

        public int getFirstRow() {
            return firstRow;
        }

        public String getaSessionID() {
            return aSessionID;
        }

        public void setaSessionID(String aSessionID) {
            this.aSessionID = aSessionID;
        }

        public String getactivity() {
            return activity;
        }

        public void setactivity(String activity) {
            this.activity = activity;
        }

        public Date getactivityEnd() {
            return activityEnd;
        }

        public void setactivityEnd(Date activityEnd) {
            this.activityEnd = activityEnd;
        }

        public Date getactivityStart() {
            return activityStart;
        }

        public void setactivityStart(Date activityStart) {
            this.activityStart = activityStart;
        }

        public String getuserID() {
            return userID;
        }

        public void setuserID(String userID) {
            this.userID = userID;
        }

        private ActiveSessionObj() {
            throw new UnsupportedOperationException("Not yet implemented");
        }
    }

    // Paging actions -----------------------------------------------------------------------------
    public void pageFirst() {
        page(0);
    }

    public void pageNext() {
        page(firstRow + rowsPerPage);
    }

    public void pagePrevious() {
        page(firstRow - rowsPerPage);
    }

    public void pageLast() {
        page(totalRows - ((totalRows % rowsPerPage != 0) ? totalRows % rowsPerPage : rowsPerPage));
    }

    public void page(ActionEvent event) {
        page(((Integer) ((UICommand) event.getComponent()).getValue() - 1) * rowsPerPage);
    }

    private void page(int firstRow) {
        this.firstRow = firstRow;
        loadDataList(); // Load requested page.
    }

    // Sorting actions ----------------------------------------------------------------------------
    public void sort(ActionEvent event) {
        String sortFieldAttribute = (String) event.getComponent().getAttributes().get("sortField");

        // If the same field is sorted, then reverse order, else sort the new field ascending.
        if (sortField.equals(sortFieldAttribute)) {
            sortAscending = !sortAscending;
        } else {
            sortField = sortFieldAttribute;
            sortAscending = true;
        }

        pageFirst(); // Go to first page and load requested page.
    }

    // Loaders ------------------------------------------------------------------------------------
    private void loadDataList() {

        // Load list and totalCount.
        try {
            dataList = list(firstRow, rowsPerPage, sortField, sortAscending);
            totalRows = countDBRowNum(); //count the tablerows
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        // Set currentPage, totalPages and pages.
        currentPage = (totalRows / rowsPerPage) - ((totalRows - firstRow) / rowsPerPage) + 1;
        totalPages = (totalRows / rowsPerPage) + ((totalRows % rowsPerPage != 0) ? 1 : 0);
        int pagesLength = Math.min(pageRange, totalPages);
        pages = new Integer[pagesLength];

        // firstPage must be greater than 0 and lesser than totalPages-pageLength.
        int firstPage = Math.min(Math.max(0, currentPage - (pageRange / 2)), totalPages - pagesLength);

        // Create pages (page numbers for page links).
        for (int i = 0; i < pagesLength; i++) {
            pages[i] = ++firstPage;
        }
    }

    // Getters ------------------------------------------------------------------------------------
    public List<ActiveSessionObj> getdataList() {
        if (dataList == null) {
            loadDataList(); // Preload page for the 1st view.
        }
        return dataList;
    }

    public int getTotalRows() {
        return totalRows;
    }

    public int getFirstRow() {
        return firstRow;
    }

    public int getRowsPerPage() {
        return rowsPerPage;
    }

    public Integer[] getPages() {
        return pages;
    }

    public int getCurrentPage() {
        return currentPage;
    }

    public int getTotalPages() {
        return totalPages;
    }

    // Setters ------------------------------------------------------------------------------------
    public void setRowsPerPage(int rowsPerPage) {
        this.rowsPerPage = rowsPerPage;
    }

    // Actions ------------------------------------------------------------------------------------
    /**
     * Returns list of ActiveSessionObj items starting at the given first index
     * with the given row count, sorted by the given sort field and sort order.
     *
     * @param firstRow First index of rows to be returned.
     * @param rowCount Amount of rows to be returned.
     * @param sortField Field to sort the data on.
     * @param sortAscending Whether to sort data ascending or not.
     * @return list of ActiveSessionObj items starting at the given first index
     * with the given row count, sorted by the given sort field and sort order.
     */
    public List<ActiveSessionObj> list(int firstRow, int rowCount, String sortField, boolean sortAscending) throws SQLException {

        String SqlStatementSmall = null;
        String SQLStatementLarge = null;

        if (ds == null) {
            throw new SQLException();
        }

        Connection conn = ds.getConnection();
        if (conn == null) {
            throw new SQLException();
        }

        int countrow = firstRow + rowCount;
        String sortDirection = sortAscending ? "ASC" : "DESC";

        /*
         * For small tables
         */
        SqlStatementSmall = "SELECT c.*"
                + " FROM (SELECT b.*, rownum rn"
                + " FROM (SELECT a.*"
                + " FROM activeSessionsLog a"
                + " ORDER BY %s %s) b"
                + " WHERE rownum <= ?) c"
                + " WHERE rn > ?";

        /*
         * For huge datatables optimized for perfomance
         */
        SQLStatementLarge = "select * from"
                + " (select asl.*, row_number() over (order by userid asc) r "
                + " from activesessionslog asl)"
                + " where r > 980750 and r <= 980800;";

        String sql = String.format(SqlStatementSmall, sortField, sortDirection);

        PreparedStatement ps = null;
        ResultSet resultSet = null;
        List<ActiveSessionObj> dataList = new ArrayList<ActiveSessionObj>();

        try {
            conn.setAutoCommit(false);
            boolean committed = false;

            ps = conn.prepareStatement(sql);
            ps.setInt(1, countrow);
            ps.setInt(2, firstRow);

            resultSet = ps.executeQuery();
            /*
             * take the result from the SQL query and insert it into Array List
             * collection
             */
            dataList = ActiveSessionsArrayList(resultSet);

            conn.commit();
            committed = true;

        } finally {
            ps.close();
            conn.close();
        }

        return dataList;
    }

    public int countDBRowNum() throws Exception {

        String SqlStatement = null;

        if (ds == null) {
            throw new SQLException();
        }

        Connection conn = ds.getConnection();
        if (conn == null) {
            throw new SQLException();
        }

        SqlStatement = "SELECT count(*) FROM ACTIVESESSIONSLOG";

        PreparedStatement ps = null;
        ResultSet resultSet = null;
        int count = 0;

        try {
            conn.setAutoCommit(false);
            boolean committed = false;
            try {
                SqlStatement = "SELECT count(*) FROM ACTIVESESSIONSLOG";

                ps = conn.prepareStatement(SqlStatement);
                resultSet = ps.executeQuery();

                if (resultSet.next()) {
                    count = resultSet.getInt(1);
                }

                conn.commit();
                committed = true;
            } finally {
                if (!committed) {
                    conn.rollback();
                }
            }
        } finally {
            ps.close();
            conn.close();
        }
        //Returns total amount of rows in table.
        return count;
    }

    /**
     * Map the current row of the given ResultSet to ActiveSessionObj.
     *
     * @param resultSet The ResultSet of which the current row is to be mapped
     * to ActiveSessionObj.
     * @return The mapped ActiveSessionObj from the current row of the given
     * ResultSet.
     */
    private ArrayList<ActiveSessionObj> ActiveSessionsArrayList(ResultSet rs) throws SQLException {
        ArrayList<ActiveSessionObj> list = new ArrayList<>();

        try {
            while (rs.next()) {
                list.add(new ActiveSessionObj(
                        rs.getString("ASESSIONID"),
                        rs.getString("USERID"),
                        timestampToDate(rs.getTimestamp("ACTIVITYSTART")),
                        timestampToDate(rs.getTimestamp("ACTIVITYEND")),
                        rs.getString("ACTIVITY")));
            }
        } catch (Exception x) {
            x.printStackTrace();
        }

        return list;
    }

    //get the selected rows
    private HashMap<String, Boolean> selectedIds = new HashMap<>();

    // get the list from the JSF page
    public Map<String, Boolean> getSelectedIds() {
        return selectedIds;
    }

    //delete all selected checkboxes
    public void deleteSelectedIDs() throws SQLException {
        boolean success = false;

        if (ds == null) {
            throw new SQLException();
        }

        Connection conn = ds.getConnection();
        if (conn == null) {
            throw new SQLException();
        }

        PreparedStatement ps = null;
        ResultSet resultSet = null;

        try {
            conn.setAutoCommit(false);
            boolean committed = false;
            try {

                String sqlDeleteQuery = "DELETE FROM ACTIVESESSIONSLOG WHERE ASESSIONID = ?";

                Set<String> keySet = selectedIds.keySet();
                String[] keys = new String[]{};
                keys = selectedIds.keySet().toArray(keys);
                ps = conn.prepareStatement(sqlDeleteQuery);

                for (int i = 0; i < keys.length; i++) {
                    ps.setString(1, keys[i]);
                    ps.executeUpdate();
                    ps.clearParameters();
                    selectedIds.put(keys[i], false); //get(keys[i]) = false;
                }

                conn.commit();
                committed = true;

                //selectedIds.clear();
            } finally {
                if (!committed) {
                    conn.rollback();
                }
            }
        } finally {
            ps.close();
            conn.close();
        }

        /*
         * // Get selected items. boolean success = false; try { String
         * sqlDeleteQuery = "";
         *
         * Set<String> keySet = selectedIds.keySet(); Iterator keyIterator =
         * keySet.iterator(); while(keyIterator.hasNext()) { keyIterator.next();
         * }
         *
         * }
         * catch(Exception x) { success = false; } // Do your thing with the
         * MyData items in List selectedDataList.
         */
        //return success; // Navigation case.

        //reload the table
        loadDataList();
    }

    private static Date timestampToDate(java.sql.Timestamp ts) {
        Date d = null;
        try {
            d = new Date(ts.getTime());
        } catch (Exception e) {
            e.printStackTrace();
        }

        return d;
    }
}

I opened the page and I select some rows I get this:

But when I press F5 I'm redirected to page 1

It's very strange because the selected rows are changed. I use hash to remember which rows are selected. It seems that the position into the hashmap is changed.
I changed to static the firstrow value into the managed bean. Then I get a second problem: the opened page is shared between the clients - when a second browser opens the page the same page of the pagination will be opened.
I tested other solution - I changed the the scope of the bean to SessionScope. I removed the static variable. But the problem of the selected rows is not fixed. I still get the old problem with the position of the selected rows.
Maybe the problem is the hashmap.
private HashMap selectedIds = new HashMap<>();
I suspect that this hashmap is correct. The index of the row of the h:datatable must be remembered into the hashmap. How I can fix this problem?
Best Wishes
Peter

A: If instead of passing the index on ui, you will pass the aSessionID, then the problem can be solved.
Store the selected sessionsID's in a list or map.
/**
 * Stores checked accounts for the Selected User
 * */
private List<Account> selectedAccounts = new ArrayList<Account>();

Add a flag in SessionsController.dataList type object which will tell whether the item is selected or not.
public boolean isSelectedAccount()
{
    return selectedAccount;
}

Now, when the data is obtained at the server side, iterate the map/list and for the object that are checked, set the flag to true.
for(Account account : customerAccounts){
    if(selectedAccounts.contains(account)){
    account.setSelectedAccount(true);
        }}

On the UI, use this flag to decide whether to show the item as selected or not.
<h:selectBooleanCheckbox id="accounts" value="#{row.selectedAccount}">

Also, whenever any object is selected or deselected, add or remove it from the list/map of selected session id's respectively.
selectedAccount.add(sessionId);

A: Your problem arises because you don't store the current paging position in your session - did you notice that it displays the first page on refresh? And it looks like you may be storing relative (in the page) instead of absolute indexes to selected elements.


text:
Q: keytar.node causing issues in Buildkite pipeline I'm trying to create a CI/CD pipeline using buildkite where the build steps runs on a Virtual Machine (Ubuntu). However, an npm package called keytar which is a dependency of tedious library is causing issues in the pipeline.
When running one of the steps from using the buildkite-agent, it tries to clean up an existing repository. And during the command git clean -fxdq it fails to remove keytar.node file due to a Permission denied Error.
Here's a full log of the step:
> Running global environment hook
> Setting up plugins
> Preparing working directory
$ cd /var/lib/buildkite-agent/builds/build-server-1/someorg/some-repo
# Host "bitbucket.org" already in list of known hosts at "/var/lib/buildkite-agent/.ssh/known_hosts"
$ git remote set-url origin git@bitbucket.org:someorg/some-repo.git
$ git clean -fxdq
warning: failed to remove node_modules/keytar/build/Release/keytar.node: Permission denied
# Removing /var/lib/buildkite-agent/builds/build-server-1/someorg/some-repo
⚠ Warning: Checkout failed! Error running `/usr/bin/git clean -fxdq`: exit status 1 (Attempt 1/3 Retrying in 2s)
# Host "bitbucket.org" already in list of known hosts at "/var/lib/buildkite-agent/.ssh/known_hosts"
$ git clone -v -- git@bitbucket.org:someorg/some-repo.git .
fatal: destination path '.' already exists and is not an empty directory.
# Removing /var/lib/buildkite-agent/builds/build-server-1/someorg/some-repo
⚠ Warning: Checkout failed! Error running `/usr/bin/git clone -v -- git@bitbucket.org:someorg/some-repo.git .`: exit status 128 (Attempt 2/3 Retrying in 2s)
# Host "bitbucket.org" already in list of known hosts at "/var/lib/buildkite-agent/.ssh/known_hosts"
$ git clone -v -- git@bitbucket.org:someorg/some-repo.git .
fatal: destination path '.' already exists and is not an empty directory.
# Removing /var/lib/buildkite-agent/builds/build-server-1/someorg/some-repo
⚠ Warning: Checkout failed! Error running `/usr/bin/git clone -v -- git@bitbucket.org:someorg/some-repo.git .`: exit status 128 (Attempt 3/3 Retrying in 2s)
# Skipping artifact upload, no checkout
 Error: Error running `/usr/bin/git clone -v -- git@bitbucket.org:someorg/some-repo.git .`: exit status 128

Upon examining the permissions on the folder /some-repo using the ls -l command the permissions seem to be drwxr-xr-x and the owner is buildkite-agent. I'm stumped as how this file does not get deleted while all other files get deleted without any issue.


text:
Q: Button must have a tooltip in one of template, but not in the others I include the button for different templates (and different divs). There should be a tooltip in one of these divs, but not in the others. How can I do this?
I think I can check the div class in the button (something like {% if div_class=="..."%}), but I do not know how to do this. Is it possible? Maybe I need to check the template name or something else?
first.html

  {% include 'button.html' %}

second.html

  {% include 'button.html' %}

button.html
{% load user_filters %}
{% if author|isfavorite:user %}>
  <button class="button button_style_none" name="favorites">

  </button>

Delete from favorites

{% else %}
  <button class="button button_style_none" name="favorites" data-out>

  </button>

Add to favorites

{% endif %}

A: You can pass additional context to the included template using the with clause (Reference: documentation). So you can pass some variable that will indicate that the tooltip should be rendered:
first.html:

  {% include 'button.html' with tooltip="yes" %}

button.html:
{% load user_filters %}
{% if author|isfavorite:user %}>
  <button class="button button_style_none" name="favorites">

  </button>
  {% if tooltip == "yes" %}

Delete from favorites

  {% endif %}
{% else %}
  <button class="button button_style_none" name="favorites" data-out>

  </button>
  {% if tooltip == "yes" %}

Add to favorites

  {% endif %}
{% endif %}

A: If your URLs are different for each template.
Suppose you have 2 URLs:
1. domain.com/url1_bro
2. domain.com/url2_bro

Then you can do something like this:
{% if 'url1' in request.path %}

{%else%}

{%endif%}


text:
Q: How to open programs programmatically using file directory I have been building voice applications for a while, and I want to try something different. I want to open programs without manually putting something like this in the programs into code:
Process.Start("notepad.exe");

I am wondering how you would execute a program using the file directory, for example:
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

The reason why I want to do this is I don't know what programs the client will have on the computer system.. I have tried researching and everything I find is like how I have been programming.
So is there a way to pull the program executable and execute the program?
Full example:
if (speech == " ")
{
    Start.Process(Application.ExecutablePath);
}

or is there anyway to accomplish this?

A: Ok, This Can be easily fixed by using the following code:
The following is how to get all exe applications
    using System.IO;
    using System.Windows.Forms;
string appPath = Path.GetDirectoryName(Application.ExecutablePath);

The below code is to get the running Applications
    using System.IO;
    using System.Reflection;
string path = Path.GetDirectoryName(Assembly.GetAssembly(typeof(MyClass)).CodeBase);

Now I can easily pull the procId with the GetProcess Method, to close the application that was open.


text:
Q: Sort a Javascript array based on every other element Assume that I have an array like so:
var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];

Even-numbered array indices are linked with the following odd index. In other words, 94 goes with "Neputunium" and 2 goes with "Helium" etc. How can I sort the array based on the even-numbered indices but keep the following odd-indexed value after it? So that I end up with an array like so:
a = [null, "Hypotheticalium", 2, "Helium", 64, "Promethium", 94, "Neptunium"];

NOTE: And yes, I do know that know that using an object or ES6 Map (or even, in this case, a sparse array with the numbers as indices, if null is left out) would be much more appropriate, but I'm just exploring this to experiment with the language. Thanks for any help.

A: var grouped = [];
for (var i = 0; i < a.length; i += 2) {
    grouped.push([a[i], a[i+1]]);
}

grouped.sort(function (a, b) { return a[0] - b[0]; });

Ideally I'd suggest you use the grouped structure from here on, since it seems to make more sense to group grouped items together, instead of relying on implicit adjacent indices. But if you need to unpack it again:
var b = [];
for (var i = 0; i < grouped.length; i++) {
    b.push.apply(b, grouped[i]);
}

A: Since the order of the calls to sort is not necessarily the same one JavaScript engine to the next (or even between revs of the same engine), you can't use sort directly on that array to do what you've described.
You can use map, filter, sort, then reduce however:

var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
a = a
  .map(function(entry, index, array) {
    return (index % 2 === 1) ? null : {
      value: array[index + 1],
      index: entry
    };
  })
  .filter(function(entry) {
    return entry != null;
  })
  .sort(function(left, right) {
    return left.index - right.index; // Works even when either or both
                                     // indexes are null, PROVIDED
                                     // no non-null index is negative,
                                     // because `null` will coerce to 0
  })
  .reduce(function(acc, entry) {
    acc.push(entry.index, entry.value);
    return acc;
  }, []);
document.body.innerHTML = JSON.stringify(a);

The map lets us produce an array with objects for the paired entries (and nulls).
The filter lets us remove the nulls.
The sort lets us sort.
The reduce lets us produce an array of the results (since we can't use map directly to map one entry to two).
If you may have negative values for your even-numbered entries, the sort callback has to handle things differently because it will sort null above those negative indexes (unless of course that's what you want).

It's a bit more concise in ES6: (live on Babel's REPL)
let a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
a = a
  .map((entry, index, array) => {
    return (index % 2 === 1) ? null : {
      value: array[index + 1],
      index: entry
    };
  })
  .filter(entry => entry != null)
  .sort((left, right) => left.index - right.index)
  .reduce((acc, entry) => {
    acc.push(entry.index, entry.value);
    return acc;
  }, []);
console.log(a);

A: You need some grouping and appropriate sorting and reorganization of the array.

var array = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"],
    sorted = array.reduce(function (r, a, i) {
        i % 2 ? r[r.length - 1].push(a) : r.push([a]);
        return r;
    }, []).sort(function (a, b) {
        return a[0] - b[0];
    }).reduce(function (r, a) {
        return r.concat(a);
    });
document.write('<pre>' + JSON.stringify(sorted, 0, 4) + '</pre>');

A: I like the ideas behind the JS-specific answers I've been given, but here's my own solution that doesn't rely on the native sort function and is instead based on an implementation of gnome sort:
var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
for (var i = 0, temp; i < a.length; i += 2) {
    if (a[i] > a[i + 2]) {
        temp = a[i];
        a[i] = a[i + 2];
        a[i + 2] = temp;
        temp = a[i + 1];
        a[i + 1] = a[i + 3];
        a[i + 3] = temp;
        i = i - 4;
    }
}
alert(JSON.stringify(a));

Of course, it's not the fastest possible sorting algorithm, but just a proof-of-concept to show that it can be done without altering my lack of structure and without lots of (potentially expensive) function calls (although I do agree that functional programming is more of a JS idiom). And I could have put the swapping code into its own function, with two calls, for the sake of DRY, like so:

var a = [94, "Neptunium", 2, "Helium", null, "Hypotheticalium", 64, "Promethium"];
function arraySwapper(array, index1, index2) {
    var temp = array[index1];
    array[index1] = array[index2], array[index2] = temp;
}
for (var i = 0, j; i < a.length; i += 2) {
    if (a[i] > a[i + 2]) {
        for (j = i; j < i + 2; j++) { arraySwapper(a, j, j + 2); }
        i -= 4;
    }
}
alert(JSON.stringify(a));


text:
Q: Django Rest Framework: Serialize multiple images to one post in I am trying to be able to serialize and upload multiple images to associate with each post.
This is my models.py
from django.conf import settings
from django.db import models
from django.db.models.signals import pre_save
from .utils import unique_slug_generator

class Painting(models.Model):
    user                        = models.ForeignKey(settings.AUTH_USER_MODEL, default="", on_delete=models.CASCADE)
    title                       = models.CharField(blank=False, null=False, default="", max_length=255)
    slug                        = models.SlugField(blank=True, null=True)
    style                       = models.CharField(blank=True, null=True, default="", max_length=255)       #need to figure out why there is problem when this is False
    description                 = models.TextField(blank=True, null=True, default="")
    size                        = models.CharField(blank=True, null=True, default="", max_length=255)
    artist                      = models.CharField(blank=True, null=True, default="", max_length=255)
    price                       = models.DecimalField(blank=True, null=True, decimal_places=2, max_digits=20)
    available                   = models.BooleanField(default=True)
    updated                     = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp                   = models.DateTimeField(auto_now=False, auto_now_add=True)

    def __str__(self):
        return self.title

    class Meta:
        ordering = ["-timestamp", "-updated"]

class PaintingPhotos(models.Model):
    title                       = models.ForeignKey(Painting, default="", on_delete=models.CASCADE)
    image                       = models.ImageField(upload_to='uploaded_paintings')

def pre_save_painting_receiver(sender, instance, *args, **kwargs):
    if not instance.slug:
        instance.slug = unique_slug_generator(instance)

pre_save.connect(pre_save_painting_receiver, sender=Painting)

my serializers.py
from django.contrib.auth import get_user_model, authenticate, login, logout
from django.db.models import Q
from django.urls import reverse
from django.utils import timezone

from rest_framework import serializers

from .models import Painting, PaintingPhotos
User = get_user_model()

class UserPublicSerializer(serializers.ModelSerializer):
    username = serializers.CharField(required=False, allow_blank=True, read_only=True)
    class Meta:
        model = User
        fields = [
            'username',
            'first_name',
            'last_name',
            ]

# # add PaintingImagesSerializer with the images model here
class PaintingPhotosSerializer(serializers.ModelSerializer):

    class Meta:
        model = PaintingPhotos
        fields =[
            'image'
        ]

#becareful here, if anyone submits a POST with an empty title, it will result in the empty slug, (which will mess up the url lookup since the title is the slug in this case)
#make title a required field in the actual interface, also remember to don't submit s POST with an empty title from the Django restframework directly
class PaintingSerializer(serializers.ModelSerializer):
    url             = serializers.HyperlinkedIdentityField(
                            view_name='paintings-api:detail',
                            read_only=True,
                            lookup_field='slug'
                            )
    user            = UserPublicSerializer(read_only=True)
    owner           = serializers.SerializerMethodField(read_only=True)
    image           = PaintingPhotosSerializer(many=True, read_only=False)

    class Meta:
        model = Painting
        fields = [
            'url',
            'user',
            'title',
            'style',
            'description',
            'size',
            'artist',
            'price',
            'available',
            'updated',
            'timestamp',
            'owner',
            'slug',
            'image',
        ]

    def get_owner(self, obj):

        request = self.context['request']
        if request.user.is_authenticated:
            if obj.user == request.user:
                return True
        return False

my views.py
from rest_framework.views import APIView
from rest_framework.parsers import MultiPartParser, FormParser
from rest_framework.response import Response
from rest_framework import generics, permissions, pagination, status

from .models import Painting
from .permissions import IsOwnerOrReadOnly
from .serializers import PaintingSerializer

class PaintingPageNumberPagination(pagination.PageNumberPagination):
    page_size = 5
    page_size_query_param = 'size'
    max_page_size = 20

    def get_paginated_response(self, data):
        author  = False
        user    = self.request.user
        if user.is_authenticated:
            author = True
        context = {
            'next': self.get_next_link(),
            'previous': self.get_previous_link(),
            'count': self.page.paginator.count,
            'author': author,
            'results': data,
        }
        return Response(context)

class PaintingDetailAPIView(generics.RetrieveUpdateDestroyAPIView):
    queryset            = Painting.objects.all()
    serializer_class    = PaintingSerializer
    lookup_field        = 'slug'
    permission_classes  = [IsOwnerOrReadOnly]

class PaintingListCreateAPIView(generics.ListCreateAPIView):
    queryset            = Painting.objects.all()
    serializer_class    = PaintingSerializer
    permission_classes  = [permissions.IsAuthenticatedOrReadOnly]
    pagination_class    = PaintingPageNumberPagination

    def perform_create(self, serializer):
        serializer.save(user=self.request.user)

I am getting this error:
AttributeError: Got AttributeError when attempting to get a value for field image on serializer PaintingSerializer.
The serializer field might be named incorrectly and not match any attribute or key on the Painting instance.
Original exception text was: 'Painting' object has no attribute 'image'.
I am also not sure if I should create another app just to handle all the images.
Thanks so much in advance!

A: Your code looks similar enough to the docs here: https://www.django-rest-framework.org/api-guide/relations/#nested-relationships I can't see what exactly is wrong, but it could be that you haven't created a PaintingPhotos object so there is no model to serialize it. I mentioned in a comment that you can create this through the Django admin.

A: Hey guys I ended up finding the answer. This stackoverflow answer explains it really well: Multiple images per Model
where I messed up was not adding the related_name argument to my photo in my PaintingPhotos model.


text:
Q: Windowing Aggregations in Spark I am learning spark structured streaming and I am a bit confused about windowing aggregations. I have following questions.

*

*Does Windowing aggregation always considers time which is passed as a column in window function?

*If so then are we always have to provide timestamp column in dataset?

*What happens when dataset doesn't contain timestamp column?


text:
Q: Python mock running in pytest crashing my instance I've got the following test module, running in Python 2.7 on FreeBSD:
from mock import patch

from t.conf import load_config

@patch('t.conf._load_file')
def test_open_file(mock_open):
    string_read = load_config('foo')
    print(repr(string_read))

It runs fine if I comment out the patch line. It crashes my machine after hanging for about 10 minutes if I leave it in. I'm using patch in other places without any issues. What's going on?
_load_file looks like this:
def _load_file(filename):
    with open(filename, 'rb') as f:
        return f.read()

And load_config looks like this:
def load_config(filename):
    text = _load_file(filename)
    data = yaml.safe_load(text)
    return data


text:
Q: using a for loop for web scraping - cannot "pass" certain data The following code is supposed to scrape the rating and the date the rating was posted.
The issue here is, that employees answers the negative reviews, and the date of their post is scraped as well. So when I scrape the site, there's an uneven number of ratings and dates (20 ratings vs 24 dates), as four of the dates belong to the answers given by employees.
In the code I try to "pass" every time the class "ugc-brand-response" shows up which is for the employee answers. So if no ugc class is met "pass" and if not just continue - but none of the data gets stored. Not even the first couple of reviews.
I've learned so much from reading other peoples questions and answers. Thanks for this awesome community.
import requests
import time
from bs4 import BeautifulSoup

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
url = "https://www.bestbuy.com/site/reviews/jabra-elite-85h-wireless-noise-canceling-over-the-ear-headphones-black/6335100?variant=A"

url_get = requests.get(url, headers=headers)
print(url_get.status_code)
soup = BeautifulSoup(url_get.content, 'lxml')

rating_n_date=[]

for rating in soup.find_all(attrs={"class": "c-review-average"}):
    rating_n_date.append(rating .text)
for date in soup.findAll(attrs={"class":"submission-date"}):
    if "class" == "ugc-brand-response" in date:
        pass
    else:
        continue
    rating_n_date.append(date.text)
time.sleep(2)
print(rating_n_date)

Here's the data including the :

Jimmy

<button aria-expanded="false" aria-controls="ugc-badge-overlay-bf28b82b-76f5-3c85-897e-598a91bbd8a8-0" aria-owns="ugc-badge-overlay-bf28b82b-76f5-3c85-897e-598a91bbd8a8-0" data-track="Custom">

</button>

Rating: 2 out of 5 stars
2

A disappointment: low volum, weak bass, distorts

Posted <time class="submission-date" title="Apr 28, 2019 11:29 PM">3 months ago</time>

Here's the code I don't want - the employee answer:

Brand response

Jabra

<time class="submission-date" title="Apr 29, 2019 8:46 AM">3 months ago</time>

Hello Jimmy - We were sorry to learn that the Jabra Elite 85h did not meet your expectations.  As the Elite 85h is a relatively new product, it is very important that you update the firmware in the headphones as often as necessary to keep up-to-date.  We are constantly improving all aspects of the Elite 85h through firmware updates.  If you have any specific questions or concers, we invite you to contact us directly by completing the web form at https://www.jabra.com/ServiceMenu/contact/ContactJabraSupport/ContactJabraSupportConsumer, or by giving us a call - we love to help!  Thank you.

A: It will never skip over where a class is ugc-brand-response-list, because you explicitly pull everything with class attribute submission-date
You also have continue misunderstood. When you use continue, it doesn't mean what you would think it should mean, in the sense of "continue on with the code". What it really means is, "stop right here. Don't follow with the rest of the loop. Go to the next item." So in the way you have it in your code, when it DOESN'T find class == "ugc-brand-response", it goes to else, which says continue. So it'll never append to your list, which is why your data isn't stored/appended.
What you could do, is go to the parent tags and pull the whole review "block" which is found with the class attribute "col-xs-12 col-md-9" , and then from there, go into each of those and pull out the rating and submission date together using find (find will get the 1st occurrence of what ever you are looking for, which means it won't grab the date of the employee replies), and then store those in to a list. I then just threw it into a dataframe/table.
import requests
import time
from bs4 import BeautifulSoup
import pandas as pd

headers = {'User-Agent':'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36'}
url = "https://www.bestbuy.com/site/reviews/jabra-elite-85h-wireless-noise-canceling-over-the-ear-headphones-black/6335100?variant=A"

url_get = requests.get(url, headers=headers)
print(url_get.status_code)
soup = BeautifulSoup(url_get.content, 'lxml')

rating_list = []
date_list = []

for ratings in soup.find_all(attrs={"class": "col-xs-12 col-md-9"}):
    rating = ratings.find('span', {'class':'c-review-average'}).text
    submission_date = ratings.find('time', {'class':'submission-date'}).text

    rating_list.append(rating)
    date_list.append(submission_date)

data = {'Rating':rating_list, 'Date':date_list}
df = pd.DataFrame(data)

Output:
print (df)
   Rating          Date
0       5  3 months ago
1       5  2 months ago
2       4  3 months ago
3       3  3 months ago
4       4  3 months ago
5       4  3 months ago
6       5  3 months ago
7       4  3 months ago
8       5  3 months ago
9       4    1 week ago
10      4  3 months ago
11      2  3 months ago
12      5  3 months ago
13      4     1 day ago
14      4   1 month ago
15      4  3 months ago
16      4   3 weeks ago
17      2  3 months ago
18      3   3 weeks ago
19      5  3 months ago


text:
Q: Array to multiple checkbox I managed to save the checked boxes using php (implode) and Mysql in a table. The values are divided with comma. You can see something similar here: PHP Multiple Checkbox Array.
So, I have a table like this:
Id                Values
1                  1,3

It was the best solution at that time. Now I want to let user to change his options. I need to show him back the checkbox group, with boxes 1 and 3 checked. Thank you!

A: $checkbox_array = explode(',', $row['Values']);
for ($i = 0; $i < $max_checkboxes; $i++) {
    $checked = in_array($i, $checkbox_array) ? 'checked' : '';
    echo "<input type='checkbox' value='$i' $checked> $i <br>";
}


text:
Q: ¿Cómo matar un hilo cuando termine en vez de tener que esperarlo (sin matar el hilo principal)? Tengo un problema de diseño con Threads en el lado de un servidor.
Me gustaría matar los hilos una vez acaben su trabajo en vez tener que esperarlos para que no estén ocupando memoria y para no tener que matar el hilo principal también.
He intentado usar std::terminate() pero el programa explota. Puede que tenga algo que ver con que estoy usando los threads de POSIX en vez de los de C++ pero no estoy seguro de eso.
Este es el código:
///-----------------------------------------------
///-----------------------------------------------
#include <chrono>
#include <thread>
#include <iostream>
#include "../PThread.h"
#include "Server.h"
///-----------------------------------------------
using namespace std;
///-----------------------------------------------
int countThreads=0;
bool isLaunched=false;
bool isDone=false;
///-----------------------------------------------
///-----------------------------------------------
//funcion para poder terminar el programa
void *Exit(void *param)
{
    char c;
    cin >> c;
    isDone=true;
    exit(0);
    return NULL;
}
///-----------------------------------------------
///-----------------------------------------------
void *ProcessData(void *param)
{

    Server *server = (Server*) param;

    cout<<countThreads<<" waiting "<< endl;

    //esperar a un cliente
    server->WaitForClient();

    //recibir el tamaño de los datos
    int pSize = 0;
    if(!server->Recive( (char*)&pSize, sizeof(int)))
    {
        cout<<"Error al recibir el tamaño de los datos --> "<<endl;
        return NULL;
    }

    Trade *trade = new Trade[pSize+1];

    //recibir los datos
    for(int i=0; i<pSize; i++) server->Recive((char*)&trade[i], sizeof(Trade));

    delete[] trade;

    //permitir que se lance otro hilo
    isLaunched = false;

    ///std::terminate();///--> no sirve
    return NULL;
}
///-----------------------------------------------
///-----------------------------------------------
int main()
{
    cout << "--SERVER--" << endl;

    PThread processThread[10000];

    //Lanzar el hilo para poder salir del programa
    PThread exitThread;
    exitThread.Create(Exit, NULL);
    cout<< "Exit Thread Created"<< endl;

    //Inicializa el socket del server
    Server server;
    cout<< "Serever Created"<<endl;

    while(!isDone)
    {
        if(!isLaunched)
        {
            //Lanzar un hilo cada vez que haya una conexión
            processThread[countThreads].Create(ProcessData, (Server*)&server);
            processThread[countThreads].Detach();

            countThreads++;
            isLaunched = true;
        }

        //Esperar unos milisegundos antes de lanzar el siguente hilo
        //si no se hace esto los clientes no logran conectarse correctamente al servidor
        std::this_thread::sleep_for(std::chrono::milliseconds(10));
    }

    //Por como está diseñado el programa nunca ejecuta las
    //lineas que están por abajo de este comentario

    for (int i = 0; i < countThreads; i++)
    {
        cout<< "Esperando hilos del Server -->"<< i <<endl;
        processThread[countThreads].Wait();
    }

    exitThread.Wait();
    return 0;
}
///-----------------------------------------------
///-----------------------------------------------

NOTA: He pensado que con este código es más que suficiente para ver el problema. Pero si quieren ver el contenido de los archivos  "PThread.h" y "Server.h" me lo dicen y también los añado. No son más que unos envoltorios para las funciones de pthreads de POSIX y el sockets de Windows.

A: Ok, al final lo gonseguí:
 //esta es para que un hilo se suicidie
 static void Exit(void *retval=NULL)
 {
     pthread_exit(retval);
 }

 //y esta es para matarlo desde otro proceso
 void kill()
 {
    const auto explorer = OpenProcess(PROCESS_TERMINATE, false,handler);
    TerminateProcess(explorer, 1);
    CloseHandle(explorer);
 }

//tal vez esto también pueda ser útil según el caso
 pthread_t ptid = pthread_self();

Saludos!!


text:
Q: Добавление лишних картинок ListView в методе getView, проверяю условие и если оно верно, то вставляю в item картинку.
Проблема: при первом запуске из 10 item-ов 2 удовлетворяют условие, всё нормально. в 2-х есть картинка.
Но при попытке пролистать список вниз и снова вверх, уже 4 item-a с картинками, даже те что не удовлетворяют условие, но, в IF те item-ы не проходят, получатся, картинка в них как то по другому попадает.
В итоге пару раз пролистав список, у меня все 10 item-ов c картинками.
if(row == null) {

        }else {
TextView days= (TextView) row.findViewById(R.id.days);
...
...
...
if (days == 0){             title.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.star_big_on, 0, 0, 0);
       }
}

A: if (days == 0)
   title.setCompoundDrawablesWithIntrinsicBounds(android.R.drawable.star_big_on, 0, 0, 0);
else
   title.setCompoundDrawablesWithIntrinsicBounds(0, 0, 0, 0);

советую почитать про то, как работает ListView (в особенности уделить внимание кэшированию View)


text:
Q: GAM - make 2D spline depend on 2 dummy variables Let us say I have 2 continuous variables x1 and x2 and 2 factors f1 and month. Factor f1 has 2 levels and factor month 12. I know how to express the model for x1 and x2 for the target y:
gam(y ~ s(x1, x2))

Just wondering, how can I have a spline for each factor/level combination for f1 + month (bit like in a hierarchical model). Thanks!

A: I can see two main options:

*

*random splines for the combinations given by the interaction of the factors, or

*by factor smooths, with the interaction of the factors used as the by variable

I would create f1f2 in your data frame from the result of interaction(f1, f2, drop = TRUE), then you could do:

Option 1

y ~ t2(x, y, f1f2, bs = c('tp', 're'), d = c(2,1), full = TRUE)

or
y ~ f1f2 + s(x, y, by = f1f2)

Which should result in a spline for each level of f1f2. The main difference between the two models is that the first uses the same wiggliness for each spline, the second has a separate smoothness parameter (hence wiggliness) for each spline.