text:
Q: Add JS Script to this HTML I want to add this "TimeCircles JavaScript but, I can't do it correctly, I will add the files of it in the following location: /js/count-down/timecircles.css and /js/count-down/timecircles.js
The HTML file: https://www.dropbox.com/s/diho8tcumte5pqr/coming-soon.html
The JS link: http://git.wimbarelds.nl/TimeCircles/

A: <script src='/js/count-down/timecircles.js' type='text/javascript'></script>
<link href='/js/count-down/timecircles.css' type='text/css'/>

Stick this in the head of your HTML.


text:
Q: "The stub received bad data" explanation I have this message pop up in Windows 7 sometimes. When it pops up is not relevant because I'm not seeking a solution. I am 90% sure I know what is causing this message to pop up. However, I am not going to bother fixing it for reasons not relevant to the question.
What I really want to know is what is meant by the message, as in, what is this "stub" and what is meant by "bad data"?

A: After some research, I think I can now answer my own question. Actually, the answer to the question can be found in an answer on Stack Overflow.

A "stub" is used in COM when you make calls across an execution boundary. It wasn't stated explicitly in the question but your Ada program is probably an EXE and implements an out-of-process COM server. Crossing the boundary between processes in Windows is difficult due to their strong isolation. This is done in Windows by RPC, Remote Procedure Call, a protocol for making calls across such boundaries, a network being the typical case.
To make an RPC call, the arguments of a function must be serialized into a network packet. COM doesn't know how to do this because it doesn't know enough about the actual arguments to a function, it needs the help of a proxy. A piece of code that does know what the argument types are. On the receiving end is a very similar piece of code that does the exact opposite of what the proxy does. It deserializes the arguments and makes the internal call. This is the stub.
One way this can fail is when the stub receives a network packet and it contains more or less data than required for the function argument values. Clearly it won't know what to do with that packet, there is no sensible way to turn that into a StructData_Type value, and it will fail with "The stub received bad data" error."

SturctData_Type in the 3rd paragraph simply refers to a user defined data type which is something that a programmer defines to store a collection of data in an organised fashion.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to deal with long invoke chain with micro service my project is created with Micro Service architecture, one business may need multiple services call. Currently, most of the services call need serial call, because the request of the next service call is generated from the last service call's response. This makes the invoke chain is very long, the performance is bad, is it any solution to deal with this scenario? Or I need to change my micro service design? Thanks!

A: You can try to solve part of your problem implementing a queue solution like an Apache Kafka, the first microservice process the data and post the data in the queue and the second microservice read from this queue.... process and post to another queue.
This approach can improve the performance because you can increase the numbers of partitions into Kafka, but you need to analyze what's you really need to process before sending the task to next service and if this can be paralyzed, if it can be paralyzed you can scale the microservice instances to process more data.
You have many options, but for microservices "talk" I recommend use queues.
Good luck with your project.


text:
Q: Numpy: np.sum with negative axis I wonder what does "If axis is negative it counts from the last to the first axis." mean in the docs, I've test these:
>>> t
array([[1, 2],
       [3, 4]])
>>> np.sum(t, axis=1)
array([3, 7])
>>> np.sum(t, axis=0)
array([4, 6])
>>> np.sum(t, axis=-2)
array([4, 6])

Still confused, I need some easily understood explanation.

A: First look at list indexing on a length-2 list:
>>> L = ['one', 'two']
>>> L[-1]  # last element
'two'
>>> L[-2]  # second-to-last element
'one'
>>> L[-3]  # out of bounds - only two elements in this list
# IndexError: list index out of range

The axis argument is analogous, except it's specifying the dimension of the ndarray.  It will be easier to see if using a non-square array:
>>> t = np.arange(1,11).reshape(2,5)
>>> t
array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10]])
>>> t.ndim  # two-dimensional array
2
>>> t.shape  # a tuple of length t.ndim
(2, 5)

So let's look at the various ways to call sum:
>>> t.sum()  # all elements
55
>>> t.sum(axis=0)  # sum over 0th axis i.e. columns
array([ 7,  9, 11, 13, 15])
>>> t.sum(axis=1)  # sum over 1st axis i.e. rows
array([15, 40])
>>> t.sum(axis=-2)  # sum over -2th axis i.e. columns again (-2 % ndim == 0)
array([ 7,  9, 11, 13, 15])

Trying t.sum(axis=-3) will be an error, because you only have 2 dimensions in this array.  You could use it on a 3d array, though.


text:
Q: regex to get string between slash's Im using template toolkit, but I believe the regexp works the same as js.
given a string, for e.g:  /home/views/register/success or /home/views/register.tt
how do I get the string after (and including) 'views/' upto the next '/' or '.', giving me in this case 'views/register'
something like:
var template_name = template.name.match('views/'+REGEXP);

A: (views/[^./]*) should do the trick.
I'm not sure if you need to escape the dot. If the abore regex doesn't work try adding a backslash before the dot.

A: This should work for you:
(views\/((?!\/|\.).)*)

ie. views/ followed by any character other than / or a .


text:
Q: Error when use nth-child to create 2 columns I have a list items

01 Clean filter

02 Change filter

03 Change blower

04 Wash blower

05 Change fan belting

   ...

32 Check & comb dented coil fin

33 Check CHW pipe leakage with visual test

And my custom css
#two-columns li {
   width: 50%;
}
#two-columns li:nth-child(n+13) {
   float: right;
}

This is my error

A: You are missing a n in the id.
Change the html:
id="two-colums" into id="two-columns

A: Here's a better way to make 2 columns:

.flexMain {
  display: flex;
  flex-flow: row wrap;
  justify-content: flex-start;
}
ul {
  max-width: 50%;
}

01 Clean filter

02 Change filter

03 Change blower

04 Wash blower

05 Change fan belting

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32 Check & comb dented coil fin

33 Check CHW pipe leakage with visual test

Use flexbox. I made 2 uls to make it easier.

A: You can also use CSS columns
#two-columns {
  -webkit-columns: 2;
  -moz-columns: 2;
  columns: 2;
}

http://codepen.io/anon/pen/eprQMb


text:
Q: Can't Change Variable in onClick I'm trying to use an int to open up different graphs. I want this int to change values when a button is pressed, but it isn't changing. Here's my code:
public class PatientDemographics extends Activity
{
    private GraphicalView mChartView;
    int num = 1;
    int tabnum = 0;
    int finalnum;

    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.tabviews);

        LinearLayout ll = (LinearLayout) findViewById(R.id.buttons);

        Button button1 = new Button(this);
        button1.setText("Disease Type");
        ll.addView(button1);
        button1.setOnClickListener( new View.OnClickListener()
        {
            public void onClick(View v)
            {
                num = 1;
                Intent i = new Intent(PatientDemographics.this, TabHelper.class);
                i.putExtra("num", tabnum);
                startActivity(i);
            }
        });

        Button button2 = new Button(this);
        button2.setText("Gender");
        ll.addView(button2);
        button2.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                num = 2;
                Intent i = new Intent(PatientDemographics.this, TabHelper.class);
                i.putExtra("num", tabnum);
                startActivity(i);
            }
        });

        Button button3 = new Button(this);
        button3.setText("Age at Diagnosis");
        ll.addView(button3);
        button3.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                num = 3;
                Intent i = new Intent(PatientDemographics.this, TabHelper.class);
                i.putExtra("num", tabnum);
                startActivity(i);
            }
        });

        Button button4 = new Button(this);
        button4.setText("Treatment Status");
        ll.addView(button4);
        button4.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                num = 4;
                Intent i = new Intent(PatientDemographics.this, TabHelper.class);
                i.putExtra("num", tabnum);
                startActivity(i);
            }
        });
    }
}

Please ignore tabnum. It is used to determine the tab that everything is in, which is the same. Also, I originally created the buttons with xml, but each tab needed a different number of buttons and I didn't know how to do that so I just made them with code.
You can see that I initialize num to 1, then try to change it inside the onClick methods, but it never changes. Please let me know if you need any more information.
EDIT:
protected void onSaveInstanceState(Bundle outState)
{
      outState.putInt("num", num);
      super.onSaveInstanceState(outState);
}

And then in onCreate:
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null)
    {
        num = savedInstanceState.getInt("num");
    }

A: You start a new Activity of the same type as a result of the button clicks.
In the new Activity the variable is initialized to 1.
If you want to use the new value in the new Activity, you should get it from the Intent and assign the variable in the onCreate() method of the Activity.
You should add something like this to onCreate():
num = (int)this.getIntent().getExtras().get("num");

A: I think that possibly you are not verifying that num is being changed via the debugger.  Because I am doing the exact same thing pretty much as you in my code.  I would recommend putting a breakpoint on the lines that change num and see if num changes.  I assume the start activity is causing you to lose the num value.


text:
Q: React Redux how to dispatch async actions and update state I try to deal with ajax data in my learning react,redux project and I have no idea how to dispatch an action and set the state inside a component
here is my component
import React, {PropTypes, Component} from 'react';
import Upload from './Upload';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as profileActions from '../../../actions/profileActions';

class Profile extends Component {

    static propTypes = {
        //getProfile: PropTypes.func.isRequired,
        //profile: PropTypes.object.isRequired,
    };

    constructor(props) {
        super(props);

        this.state = {
            profile:{
                username: '',
                password: ''
            }
        }
        this.onUpdate = this.onUpdate.bind(this)
    }

    onUpdate(event) {
        alert()
    }

    componentWillMount() {
    }

    componentDidMount() {
    }

    render() {

        const {profile} = this.props;
        return (
            <div>

            </div>
        );
    }
}

function mapStateToProps(state) {
    console.log(state)
    return {
        profile: state.default.profile,
    };
}

function mapDispatchToProps(dispatch, ownProps) {
    return {
        actions: bindActionCreators(profileActions, dispatch)
    };
}

export default connect(mapStateToProps, mapDispatchToProps)(Profile);

I create the store as it follows
import { createStore, combineReducers, applyMiddleware } from 'redux'
import createLogger from 'redux-logger'
import thunk from 'redux-thunk'
import { routerReducer, routerMiddleware, push } from 'react-router-redux'
import reducers from '../reducers'
import { browserHistory } from 'react-router';

const middleware = [ thunk ];
if (process.env.NODE_ENV !== 'production') {
    middleware.push(createLogger());
}

middleware.push(routerMiddleware(browserHistory));

// Add the reducer to your store on the `routing` key
const store = createStore(
    combineReducers({
        reducers,
        routing: routerReducer
    }),
    applyMiddleware(...middleware),

)

export default store;

reducer
export const RESOLVED_GET_PROFILE = 'RESOLVED_GET_PROFILE'

const profileReducer = (state = {}, action) => {
    switch (action.type) {
        case 'RESOLVED_GET_PROFILE':
            return action.data;
        default:
            return state;
    }
};

export default profileReducer;

actions
import * as types from './actionTypes';
import Api from '../middleware/Api';

export function getProfile() {
    return dispatch => {
        dispatch(setLoadingProfileState()); // Show a loading spinner
        Api.getAll('profile').then(profile => {
            dispatch(doneFetchingProfile(profile));
        }).catch(error => {
            throw(error);
        });
        /*Api.fetch(`profile`, (response) => {
            console.log(response)
            dispatch(doneFetchingBook()); // Hide loading spinner
            if(response.status == 200){
                dispatch(setProfile(response.json)); // Use a normal function to set the received state
            }else {
                dispatch(error)
            }
        }) */
    }
}

function setProfile(data) {
    return {type: types.SET_PROFILE, data: data}
    //return { type: types.SET_PROFILE, data: data };
}

function setLoadingProfileState() {
    return {type: types.SHOW_SPINNER}
}

function doneFetchingProfile(data) {
    console.log(data)
    return {
        type: types.HIDE_SPINNER,
        profile: data
    }
}

function error() {
    return {type: types.SHOW_ERROR}
}

but I have no idea how would I dispatch action and update the state after getProfile action

A: You need to only dispatch your event RESOLVED_GET_PROFILE right after dispatching doneFetchingProfile, or simply listen RESOLVED_GET_PROFILE and hide spinner on reducing it.
 Api.getAll('profile').then(profile => {
    dispatch(doneFetchingProfile(profile));
    dispatch(resoloveGetProfile(profile));
 })

Actually you r doing everything right - so I didn't understand what is your question is, so if you meant something else - let me know, I`ll try to describe you.
About  dispatch(resoloveGetProfile(profile));
There you dispatch action, which will update your state, simple as you do with some static state, I saw that you already have setProfile action, so you can change that line, to call your existed function.
dispatch(setProfile(profile))

Than you need to reduce your state in this action
case 'SET_PROFILE' : (action, state) => {...state, profile: action.data}

Than your state will change and your components will update. Note that your 'get profile method' better to call from componentDidMount to avoid freezing at rendering because of performing web request.


text:
Q: Removing rows in an excel worksheet if duplicate is found in another worksheet I have two worksheets: "compiled" and "firstpickup". What I'm looking to do is delete rows in the sheet "firstpickup" if the value in column A can also be found in column A of "compiled". "compiled" is 42,000 rows and "firstpickup" is 21,000, so I'd like to be able to just run the macro and have it end after going through all the data.
Here are some options I tried based on cursory Google searches:
 Sub RemoveDuplicates()
    Dim rCrit As Range 'Range To Search For Duplicates
    Dim rFilt As Range 'Range To Remove Duplicates
    Dim lLoop As Long

    Set rCrit = Worksheets("compiled").Range("A1", Worksheets("compiled").Range("A" & Rows.Count).End(xlUp))
    Set rFilt = Worksheets("firstpickup").Range("A1", Worksheets("firstpickup").Range("A" & Rows.Count).End(xlUp))

    For lLoop = rCrit.Rows.Count To 2 Step -1
        If WorksheetFunction.CountIf(rCrit, rFilt(lLoop).Value) > 0 Then
            Worksheets("firstpickup").Rows(lLoop).Delete shift:=xlUp
        End If
    Next lLoop
End Sub

This sub kept not finding matches in the "if" function, so it never deleted any rows, even for rows which I knew had duplicates.
Sub Removeduplicates()

Dim Row As Long
Dim FoundDup As Range

Sheets("compiled").Select

For Row = Range("A24031").End(xlUp).Row To 2 Step -1

Set FoundDup = Sheets("compiled").Range("A:A").Find(Cells(Row, 1), LookIn:=xlValues, lookat:=xlWhole)

If Not FoundDup Is Nothing Then
    Cells(Row, 1).EntireRow.Delete
End If

Next Row

End Sub

This sub also wasn't successful; after the "For" query, the debugger would skip to "end sub".
Any help at all, either reworking my previous attempts or helping me with a different solution, would be greatly appreciated.

A: You can use this VBA code, will help you to Delete Rows from Sheet Firstpickup, if Values in Column A will match with values in Column A of Complied Sheet.
Sub DeleRows()
Dim LR As Long, i As Long
With Sheets("Firstpickup")
LR = .Range("A" & Rows.Count).End(xlUp).Row
For i = LR To 1 Step -1
    If IsNumeric(Application.Match(.Range("A" & i).Value, Sheets("Complied").Columns("A"), 0)) Then .Rows(i).Delete
Next i
End With
End Sub


text:
Q: Promedio de un conjunto de datos con diferentes años y diferentes sitios Tengo una base de datos como el siguiente ejemplo:
Son más de 2000 registros y lo que necesito es generar un promedio de los datos que contienen las columnas de coral y alga por año y por sitio.
Así que utilice la función:
tapply(set1$coral.cover,list(set1$site,set1$survey_year),mean)

Pero me aparece un error y no sé a qué se debe:
Error in tapply(set1$coral.cover, list(set1$site, set1$survey_year), mean) :
  arguments must have same length

A: @Aix, sin un ejemplo de los datos que estas evaluando hay un conjunto de posibilidades que se nos escapan en el diagnóstico. De todas formas te comento que no veo nada raro en tu ejemplo, de hecho hice una simulación para probar la sentencia y funcionó correctamente
set1 <- data.frame(coral.cover = sample(1:100, 100, replace=TRUE),
                   coral.column = sample(1:3, 100, replace=TRUE),
                   site = paste0("site ",sample(1:5, 100, replace=TRUE)),
                   survey_year = sample(2010:2017, 100, replace=TRUE))

str(set1)
tapply(set1$coral.cover,list(set1$site,set1$survey_year),mean)

La salida:
> str(set1)
'data.frame':   100 obs. of  4 variables:
 $ coral.cover : int  63 35 42 15 60 65 63 59 7 55 ...
 $ coral.column: int  2 2 3 1 1 3 2 2 3 3 ...
 $ site        : Factor w/ 5 levels "site 1","site 2",..: 5 1 5 3 1 2 2 1 4 4 ...
 $ survey_year : int  2011 2016 2014 2016 2017 2014 2012 2010 2013 2015 ...

> tapply(set1$coral.cover,list(set1$site,set1$survey_year),mean)
        2010 2011     2012     2013 2014 2015     2016 2017
site 1 52.50   14 64.50000 71.00000 60.0 64.5 42.33333 60.0
site 2 48.00   11 45.75000  4.00000 64.0 74.0 63.00000   NA
site 3 29.00   15       NA 66.20000 39.8 68.0 34.00000 61.6
site 4    NA   NA 49.00000 63.33333 24.0 47.0 35.00000 81.0
site 5 42.25   58 43.16667 38.00000 37.0 40.0 54.50000   NA

Por lo que te diría que revises los nombres de variables y que se correspondan con la realidad, tener en cuenta el tema "CASE Sensitive"


text:
Q: Chrome manifest v3 - is there a viable workaround to use Google's File Picker in a Chrome extension? My searches have turned up nothing concrete. My extension uses Google's file picker to allow the user to browse their sheets and choose a desired file to write some data to, which manifest v3 breaks because of some GAPI limitations. Unless I've missed something obvious, there does not seem to be a simple workaround or method for this to migrate to v3 -- it just seems to be disallowed.
I'm not asking if there's a way to do something that they intend to not be possible (even though I doubt such a thing would exist with Google) but I'm optimistically hoping that maybe there is some hacky/annoying workaround that still fits within their rules. If I absolutely have to just allow them to set a sheet URL manually I will...I'm just trying to avoid it.
Any tips or  suggestions would be appreciated.

A: You  may have to test it yourself to make sure there are no weird behaviors, but Google has some recommendations regarding this in their migration guide:

In Manifest V3, all of your extension's logic must be included in the extension. You can no longer load and execute a remotely hosted file. A number of alternative approaches are available, depending on your use case and the reason for remote hosting. Here are approaches to consider:
Configuration-driven features and logic
In this approach, your extension loads a remote configuration (for example a JSON file) at runtime and caches the configuration locally. The extension then uses this cached configuration to decide which features to enable.
Externalize logic with a remote service
Consider migrating application logic from the extension to a remote web service that your extension can call. (Essentially a form of message passing.) This provides you the ability to keep code private and change the code on demand while avoiding the extra overhead of resubmitting to the Chrome Web Store.
Bundle third-party libraries
If you are using a popular framework like React or Bootstrap, you can download the minified files, add them to your project and import them locally.

For your case, option #3 seems like the easiest. Looking at the Google Picker API documentation it only uses two relatively small script files, https://apis.google.com/js/api.js and https://accounts.google.com/gsi/client. You could try to bundle these in your Chrome extension and call the methods locally.


text:
Q: MongoDB Realm GraphQL - returning multiple types as custom payload in a custom resolver I am currently exploring MongoDB Realm, more specifically the GraphQL integration. I have successfully created resolvers which return a specific type, or an array of one type. However, I can't figure out how to return arrays of multiple types...
I have tried to create a custom payload, but I have to define that payload as JSON, and can't reference non-JSON types from in there.
To clarify:

*

*I can create a custom resolver which resolves: {shirts: [Shirts]}

*I cannot create a custom resolver which resolves: {shirts: [Shirts], trousers: [Trousers], shoes: [Shoes]}

*I cannot create a custom resolver which resolves: {shirts: [Shirts], isFoo: Boolean}

Is there any way to accomplish the latter two? I would be able to do it if I was allowed to edit the GraphQL schema directly, but as far as I can see, one is only able to modify the schema through this custom resolver interface...
Thanks in advance!


text:
Q: Log4net dynamically name xml file, store and use the path and name to append log.txt I am using log4net to capture any error in a try catch block. like so:
      catch (Exception ex)
        {
            //theres been an error and xmlReceipt is not null
            if (xmlReceipt != null)
            {
                //Log the error
                Logger.Error(ex);
                //log the Receipt object to an xml file in App_Data/ReceiptXml
                Logger.Error(xmlReceipt);
                //Append log.txt, explain where the ReceiptXml can be found
                Logger.Error(string.Format("The Xml Receipt was written to {0}", ConfigurationManager.AppSettings["XmlReceiptPath"]));

            }

            //theres been an error and xmlReceipt is null
            else
                Logger.Error(ex);
                Logger.Error("The Xml Receipt was empty so no document was written");

            throw;

        }

What I am trying to achieve is, when an error is detected and the xmlReceipt object is not null, log the error in the log.txt, this can be appended so it grows over time. I then append the same log.txt with the path and then finally I wish to create an xml document using the xmlReceipt object. Ignore the else.
See below for the web.config, I have tried to dynamically create a new xml document each time with  a dynamic date within the name however what is actually happening is the xml document is created with the name Receipt.xml and no date and the xml inside also contains the stack trace.
Can anyone help me change the web.config so that it dynamically adds the date to the file name and does not include the stack trace, just the xmlReceipt object. If you could also advise how I can add the xml filepath with the dynamic date to the IF statement in the string.Format line that would be great because I could then advise in log.txt the exact name of the xml document that relates to the error log.
<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>
  <log4net>

    <root>
      <level value="ERROR"/>
      <appender-ref ref="LogFileAppender" />
      <appender-ref ref="ReceiptXmlAppender" />
    </root>

    <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
      <file value="App_Data/log.txt"/>
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c %m%n" />
      </layout>
    </appender>

    <appender name="ReceiptXmlAppender" type="log4net.Appender.RollingFileAppender" >
      <param name="File" value="App_Data/ReceiptXml/Receipt.xml"/>
      <param name="RollingStyle" value="Date"/>
      <param name="DatePattern" value="yyyy-MM-dd.\tx\t" />
      <param name="StaticLogFileName" value="false"/>
      <appendToFile value="false" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message %stackTrace%newline" />
      </layout>
    </appender>

  </log4net>
  <appSettings>
    <add key="XmlReceiptPath" value="C:\Development\Payment\trunk\WebsiteFrontEnd\App_Data\ReceiptXml"/>
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
  </system.web>
</configuration>


text:
Q: What is $r-n+1$ equal to? So I am working on factorials and can easily show that
$$r = \frac{r!}{(r-1)!}$$
By expanding the factorial $$r! = r(r-1)\cdots(r-n+1)$$
Then dividing both sides by $(r-1) \cdots (r-n+1)=(r-1)!$
However, I cannot figure out the equivalent for
$$r-n+1 = \frac{r!}{r(r-1) \cdots(r-n)}$$

A: Oh, I get what you are asking!
You are asking what does $r(r-1)\cdots(r-n+1)$ equal in a simple factorial equation.
Well. $r!$ is $r$ multiplied by everything down to $1$.  But $r(r-1)\cdots(r-n+1)$ is $r$ multiplied only down to $r-n+1$.  Everything else $r-n$ down to $1$ is missing.  If we multiplied by $(r-n).......2\cdot 1$ we'd get.
$r! = [r(r-1)\cdots(r-n+1)]\times [(r-n)...... 2\cdot 1]$.
Note: $[(r-n)...... 2\cdot 1] = (r-n)!$ so if we divide both sides by that we get:
$\frac {r!}{(r-n)!} = [r(r-1)\cdots(r-n+1)]$
This is useful as shorthand to think whenever you see $\frac {r!}{(r-n)!}$ that that means $r(r-1).........(r-n+1)$.
This way if anyone ask you "If you have $52$ cards and you deal out $17$ of them then how many different sequence of $17$ cards can you have" you can say "Well there are $52$ choices for the first dealt card and $51$ choices for the second all the way down to $36$ choices for the $17$th card so that is $52\cdot 51\cdot .... \cdot 36 = \frac {52!}{35!}$".  Now you can know you can just take a shortcut... There are $\frac {52!}{(52-17)!}$ ways to do it.


text:
Q: django post_delete() signal handler doesn't work I am trying to make it so that the 'num_posts' field of a blog object is decremented every time a post belonging to that blog is deleted, and incremented every time a post is created. I was able to implement the overloaded save method easily enough:
def save(self, *args, **kwargs):
    '''After saving a new post, increment the num_posts value in the
    relevant blog.'''
    super(Posts, self).save(*args, **kwargs)
    self.blog_id.num_posts += 1
    tmp = self.blog_id
    tmp.save()

But for whatever reason, the logic does not work when deleting a Posts object. I'm following best practices by using signal handlers in a handlers.py file in a signals submodule. I then import the submodule in my ready() method in my TasksConfig(Appconfig) method in apps.py
I don't seem to be getting any syntax errors, or any errors at all. The num_posts field on the relevant blog simply fails to decrement. Here is the relevant code:
From my handlers.py:
from django.db.models.signals import pre_delete
from django.dispatch import receiver
from webcomics.models import Pages, Posts, Blogs

@receiver(pre_delete, sender=Pages)
def handle_page_delete(sender, **kwargs):
    obj = kwargs['instance']

    if(obj != None):
        tmp1 = obj.prev_id
        tmp2 = obj.next_id

    if(tmp1 != None):
        tmp1.next_id = tmp2
        obj.prev_id = None

    if(tmp2 != None):
        tmp2.prev_id = tmp1
        obj.next_id = None

@receiver(pre_delete, sender=Posts)
def handle_bpost_delete(sender, **kwargs):
    obj = kwargs['instance']

    if(obj != None):
        tmp = Blogs.objects.get(pk = obj.blog_id)
        tmp.num_pages = tmp.num_pages - 1

From my apps.py:
from django.apps import AppConfig

class WebcomicsConfig(AppConfig):
    name = 'webcomics'

class TasksConfig(AppConfig):
    name = 'tasks'
    verbose_name = "Tasks"

    def ready(self):
        import binshellpress.webcomics.signals.handlers

Also, here is the full Posts object in models.py, just in case you guys can see something I'm missing:
class Posts(models.Model):
    title = models.CharField(max_length=180)
    pub_date = models.DateTimeField('date publishied', default=timezone.now)
    blog_id = models.ForeignKey('Blogs', on_delete=models.CASCADE)
    series_id = models.ForeignKey('Series', on_delete=models.SET_NULL,
                                  blank=True, null=True)

    # Note: Vanilla TinyMCE Integration seems to be working. Need to
    # modify the implementation to handle links, images, etc.
    data = HTMLField()

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        '''After saving a new post, increment the num_posts value in the
        relevant blog.'''
        super(Posts, self).save(*args, **kwargs)
        self.blog_id.num_posts += 1
        tmp = self.blog_id
        tmp.save()

I suspect that it is something obvious. I'm just at a loss because there doesn't seem to be any error message coming from anywhere.

A: You forgot to save the updated Blogs instance in handle_bpost_delete
def handle_bpost_delete(sender, instance, **kwargs):
    instance.blog.num_pages -= 1
    instance.blog.save()

There's a simpler way to get the count of related objects, though. You can simply let the database do the count when you need it. Quite fast, and much less error prone.
Example:
from django.db.models import Count

blogs = Blogs.objects.annotate(num_pages=Count('posts'))
print(blogs[0].num_pages)

https://docs.djangoproject.com/en/1.11/topics/db/aggregation/#following-relationships-backwards


text:
Q: Formatting a sharepoint list view I am trying to do a couple of things in a sharepoint list but not getting anywhere. I wondered if you could help.
I am trying to firstly - work it so when someone hits the 'Submit' button (renaming of the 'exitGridView') it not only saves the submission but redirects to another url? Is that possible with only using the custom JSON editor in sharepoint?
Secondly, it would be great if we could remove the 'Add new item' when in grid view so they can only see whats already there. again is this possible in the same way?
so far the JSON looks like this:
    {
  "$schema": "https://developer.microsoft.com/json-schemas/sp/v2/row-formatting.schema.json",
  "additionalRowClass": {
    "operator": ":",
    "operands": [
      {
        "operator": "==",
        "operands": [
          {
            "operator": "%",
            "operands": [
              "@rowIndex",
              2
            ]
          },
          0
        ]
      },
      "sp-css-backgroundColor-BgLightGray30",
      {
        "operator": ":",
        "operands": [
          {
            "operator": "==",
            "operands": [
              {
                "operator": "%",
                "operands": [
                  "@rowIndex",
                  2
                ]
              },
              1
            ]
          },
          "sp-css-backgroundColor-noFill",
          ""
        ]
      }
    ]
  },
  "commandBarProps": {
    "commands": [
      {
        "key": "exitGridView",
        "text": "Submit"
      },
      {
        "key": "editInGridView",
        "text": "Edit"
      },
      {
        "key": "new",
        "hide": true
      },
      {
        "key": "export",
        "hide": true
      },
      {
        "key": "automate",
        "hide": true
      },
      {
        "key": "share",
        "hide": true
      },
      {
        "key": "integrate",
        "hide": true
      }
    ]
  }
}

Any help would be greatly appreciated.

A: *

*Is it possible to redirect to another URL after click on the exitGridView button using view formatting?

*

*As far I know unfortunately it is not possible

*Is it possible to hide Add new item in Command bar?

*

*Yes, it is possible. You can hide buttons on Command bar, change text or icon and many more. You will find more information here
Please do not forget mark this as answer if it helps you.


text:
Q: Qt5: Запрос представления в QTableView Есть некоторые представления. Нужно вывести их в QTableView, а так же запрос всех представления существующих в БД, результат это
Делаю:
{
    ui->setupUi(this);
    QSqlDatabase db = QSqlDatabase::addDatabase("QMYSQL");
    db.setHostName("адрес");
    db.setDatabaseName("xelfebix");
    db.setUserName("xelfebix");
    db.setPassword("пароль");
    if(!db.open()) {
        qDebug() << "Cannot open    database:" << db.lastError();
    }
    else {
        qDebug() << "Connection established";
    }
    QTableView view;
    QSqlQueryModel model;
    model.setQuery("SELECT * FROM `ТехПроцесс`;");
    qDebug() << model.lastError();
    view.setModel(&model);
    view.show();
}

В итоге вся таблица пустая. Что я делаю не так и как поправить?

A: У вас
QSqlDatabase db;
QTableView view;
QSqlQueryModel model;

уничтожаются при выходе из конструктора, сделайте их переменными класса.


text:
Q: spring boot 1.3.1 devtools hot reload not work if your project name is spring-boot Spring boot 1.3.1.RELEASE, used devtools.
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-devtools</artifactId>
    </dependency>

Now I add some code in controller method, e.g.
logger.info("delete {} ", name);

but in eclipse console, nothing output, and access this url , the new add logger did not output. So why is so? why hot reload not work?
I found something could explain this phenomenon. Because my project name is spring-boot, and run Application class in eclispe you could see:

you could see after Application name appended (1)
I don't know what's this mean.
After rename project name to anything else(e.g. spring-boot-reservation), now I found devtools could work normally.
And this time the number after Application name is changed to 2,


text:
Q: Errors while creating a Single Context Provider in React TypeScript I am trying to create a context for Cart by following this: https://github.com/AlexSegen/react-shopping-cart/blob/master/src/contexts/CartContext.js for a React TypeScript project.
I am confused of what does this Context take in as parameters. I am getting errors a multiple places. This is what I have written so far:
import React, { createContext, useReducer } from 'react';
import { CartReducer, sumItems } from './CartReducer';

export const CartContext = createContext({}); <-- 1) Ambiguity Here

type Props = { children: React.ReactElement }

const storage = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart')) : []; <-- Error1 here
const initialState = { cartItems: storage, ...sumItems(storage), checkout: false };

const CartContextProvider = ({children} : Props) => {
     const [state, dispatch] = useReducer(CartReducer, initialState)
     const increase = payload => {    <-- Error2 Here and for all Payloads below
          dispatch({ type: 'INCREASE', payload })
     }
     const decrease = payload => {
          dispatch({ type: 'DECREASE', payload })
     }
     const addProduct = payload => {
          dispatch({ type: 'ADD_ITEM', payload })
     }
     const removeProduct = payload => {
          dispatch({ type: 'REMOVE_ITEM', payload })
     }
     const clearCart = () => {
          dispatch({ type: 'CLEAR' })
     }
     const handleCheckout = () => {
          console.log('CHECKOUT', state);
          dispatch({ type: 'CHECKOUT' })
     }
     const contextValues = {
          removeProduct,
          addProduct,
          increase,
          decrease,
          clearCart,
          handleCheckout,
          ...state
     }
     return (
          <CartContext.Provider value={contextValues} >
               { children}
          </CartContext.Provider>
     );
}
export default CartContextProvider;

These are the errors I am facing:
// Ambiguity Here:
I am not sure if I can pass an empty JSON object, it might be working for now, but Ideally in Typescript we must pass a parameter type. And I am wondering what Parameter(Interface) this context could take.

// Error1:
var localStorage: Storage
Argument of type 'string | null' is not assignable to parameter of type 'string'. Type 'null' is not assignable to type 'string'.ts(2345)

// Error2:
(parameter) payload: any
Parameter 'payload' implicitly has an 'any' type.ts(7006)

In order to fix this, I have tried following approaches:
// Fix for Error1:
const storage = localStorage.getItem('cart') ? JSON.parse(localStorage.getItem('cart') || '{}') : [];

// Fix for Error2:
type PropsforPayload = { payload: React.ReactElement }
const increase = (payload: PropsforPayload) => { //Similar for all the occurences.

My question here is: Are my two approaches valid? Will they be consistent through out and how do I correctly use the Context for types(interface)

A: 1 - React.createContext argument is default value. It's used only when you get context value without provider. If there is no reasonable defaults, you might want to throw error in this case. I use null as default value and custom wrapper arround React.useContext which throws an error if this would happen.
https://reactjs.org/docs/context.html#reactcreatecontext
2 - Typescript doesn't know that localStorage.getItem('cart') always returns the same value in this case, so when it's called the second time, typescript still thinks it might be null. So you should save it to a variable first:
const cartString = localStorage.getItem('cart');
const storage = cartString  ? JSON.parse(cartString) : [];

or
const storage = JSON.parse(localStorage.getItem('cart') ?? "[]");

3 -  Typescript have no idea what is payload, so you should specify it manually. Alternatively you can try to use some typescript friendly library to do it i.e. https://github.com/piotrwitek/typesafe-actions#action-helpers


text:
Q: Java ball object doesn't bounce off of drawn rectangles like it's supposed to. Sorry for the awful title.  The purpose of the Java applet is as such: A ball is bouncing around the screen.  The size and speed of this ball can be changed via scrollbars.  The user can press and drag the mouse on the screen to draw rectangles.  The ball will bounce off of these rectangles as well.  The bounds of these rectangles are stored in a vector.  When a rectangle is clicked, it (and all other rectangles at that point) are removed from the vector (and the screen).
The problem I'm having is two-fold: One, when I click a rectangle to remove it, it doesn't get removed, but that can be solved later.
Two: The ball doesn't bounce off of the rectangles like it's supposed to.  When I draw a rectangle in either the same row or column as the ball, the ball bounces around inside of a tiny rectangle, like it's stuck.
Here's my code to detect if the ball is hitting the boundaries of either the applet or any of the rectangles:
  public void move()
  {
    //if it will hit the right or left boundary, flip the x direction and set it
    if (loc.x+size >= boundx || loc.x <= 0)
    { dx *= -1; }
    //if it will hit the top or bottom boundray, flip the y direction and set it
    if (loc.y+size >= boundy || loc.y <= 0)
    { dy *= -1; }

    for (int i = 0; i < r.size(); i++)
    {

      temp = new Rectangle(r.elementAt(i));
      int rx = temp.x;
      int ry = temp.y;
      int rh = temp.height;
      int rw = temp.width;
      //If the ball hits either side of the rectangle, change the x direction
      if((loc.x > rx && loc.x > ry && loc.x < (ry + rh))||(loc.x < (rx + rw) && loc.x > rx && loc.x <(ry + rh)))
        {dx *= -1;}
      //If the ball hits either the top or bottom, change the y direction
      if((loc.y > ry && loc.y > rx && loc.y < (rx + rw))||(loc.y < (ry + rh) && loc.y > ry && loc.y <(rx + rw)))
        {dy *= -1;}
    }
    //Increment or decrement the location of the ball based on the X and Y directions.
    loc.x += dx;
    loc.y += dy;
  }

If you want to view the code in its entirety, it's here: http://ideone.com/R1hpBx
Thanks in advance for all the wonderful help.

A: I finally found a edge detection system I like...

Basically, the magic happens here...
// Detect if we collided with any one (collision is the rectangle, bounds is us)
if (collision.intersects(bounds)) {
    // Determine the intersect of the collision...
    insect = collision.intersection(bounds);

    // Flags...
    boolean vertical = false;
    boolean horizontal = false;
    boolean isLeft = false;
    boolean isTop = false;

    // Left side...
    if (insect.x == collision.x) {
        horizontal = true;
        isLeft = true;
    // Right side
    } else if (insect.x + insect.width == collision.x + collision.width) {
        horizontal = true;
    }
    // Top
    if (insect.y == collision.y) {
        vertical = true;
        isTop = true;
    // Bottom
    } else if (insect.y + insect.height == collision.y + collision.height) {
        vertical = true;
    }

    // Technically, we can really only collide with a single edge...more or less
    if (horizontal && vertical) {
        // Basically, we try and give precedence to the longer edge...
        if (insect.width > insect.height) {
            horizontal = false;
        } else {
            vertical = false;
        }
    }

    // We collided with a horizontal side...
    if (horizontal) {
        dx *= -1;
        // Move the ball to the approriate edge so we don't get caught...
        if (isLeft) {
            bounds.x = collision.x - bounds.width;
        } else {
            bounds.x = collision.x + collision.width;
        }
    // We collided with a vertical side...
    } else if (vertical) {
        dy *= -1;
        // Move the ball to the approriate edge so we don't get caught...
        if (isTop) {
            bounds.y = collision.y - bounds.height;
        } else {
            bounds.y = collision.y + collision.height;
        }
    }

}

Now, I only have a single obstacle, but I doubt it would take much effort to get it working with a series of obstacles... ;)
public class TestBouncingBall {

    private Rectangle insect;

    public static void main(String[] args) {
        new TestBouncingBall();
    }

    public TestBouncingBall() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException ex) {
                } catch (InstantiationException ex) {
                } catch (IllegalAccessException ex) {
                } catch (UnsupportedLookAndFeelException ex) {
                }

                JFrame frame = new JFrame();
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new BallPane());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }

    public class BallPane extends JLayeredPane {

        private Ball ball;
        private Timer timer;
        private Rectangle world;

        public BallPane() {

//            world = new Rectangle(random(400), random(400), random(100), random(100));
            world = new Rectangle(100, 100, 200, 200);

            ball = new Ball();
            ball.setSize(ball.getPreferredSize());
            ball.setLocation(10, 10);

            add(ball);

            timer = new Timer(16, new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    ball.move(getBounds(), world);
                    invalidate();
                    repaint();
                }
            });
            timer.setRepeats(true);
            timer.setCoalesce(true);
            timer.start();

        }

        protected int random(int max) {

            return (int) Math.round(Math.random() * max);

        }

        @Override
        public Dimension getPreferredSize() {
            return new Dimension(400, 400);
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.GRAY);
            g2d.fill(world);
            if (insect != null) {
                g2d.setColor(Color.RED);
                g2d.fill(insect);
            }
            g2d.dispose();
        }
    }

    public class Ball extends JPanel {

        public int maxSpeed = 10;
        private BufferedImage beachBall;
        private int dx = 10 - (int)Math.round(Math.random() * (maxSpeed * 2)) + 1;
        private int dy = 10 - (int)Math.round(Math.random() * (maxSpeed * 2)) + 1;
        private int spin = 20;
        private int rotation = 0;

        public Ball() {
            try {
                beachBall = ImageIO.read(getClass().getResource("/ball.png"));
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            setOpaque(false);
        }

        @Override
        public Dimension getPreferredSize() {
            Dimension size = beachBall == null ? new Dimension(48, 48) : new Dimension(beachBall.getWidth(), beachBall.getHeight());
            size.width += 4;
            size.height += 4;
            return size;
        }

        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            if (beachBall != null) {
                Graphics2D g2d = (Graphics2D) g.create();
                g2d.setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY);
                g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
                g2d.setRenderingHint(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY);
                g2d.setRenderingHint(RenderingHints.KEY_DITHERING, RenderingHints.VALUE_DITHER_ENABLE);
                g2d.setRenderingHint(RenderingHints.KEY_FRACTIONALMETRICS, RenderingHints.VALUE_FRACTIONALMETRICS_ON);
                g2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2d.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
                g2d.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_PURE);

                int x = (getWidth() - beachBall.getWidth()) / 2;
                int y = (getHeight() - beachBall.getHeight()) / 2;
                AffineTransform transform = g2d.getTransform();
                AffineTransform at = new AffineTransform();
                at.translate(getX(), getY());
                at.rotate(Math.toRadians(rotation), getWidth() / 2, getHeight() / 2);
                g2d.setTransform(at);
                g2d.drawImage(beachBall, x, y, this);
                g2d.setTransform(transform);
                g2d.dispose();
            }
        }

        public void move(Rectangle world, Rectangle collision) {
            Rectangle bounds = getBounds();
            bounds.x += dx;
            bounds.y += dy;

            if (bounds.x < 0) {
                bounds.x = 0;
                dx *= -1;
            }
            if (bounds.y < 0) {
                bounds.y = 0;
                dy *= -1;
            }
            if (bounds.x + bounds.width > world.width) {
                bounds.x = world.width - bounds.width;
                dx *= -1;
            }
            if (bounds.y + bounds.height > world.height) {
                bounds.y = world.height - bounds.height;
                dy *= -1;
            }

            if (collision.intersects(bounds)) {
                insect = collision.intersection(bounds);

                boolean vertical = false;
                boolean horizontal = false;
                boolean isLeft = false;
                boolean isTop = false;

                if (insect.x == collision.x) {
                    horizontal = true;
                    isLeft = true;
                } else if (insect.x + insect.width == collision.x + collision.width) {
                    horizontal = true;
                }
                if (insect.y == collision.y) {
                    vertical = true;
                    isTop = true;
                } else if (insect.y + insect.height == collision.y + collision.height) {
                    vertical = true;
                }

                if (horizontal && vertical) {
                    if (insect.width > insect.height) {
                        horizontal = false;
                    } else {
                        vertical = false;
                    }
                }

                System.out.println("v = " + vertical + "; h = " + horizontal);

                if (horizontal) {
                    dx *= -1;
                    if (isLeft) {
                        bounds.x = collision.x - bounds.width;
                    } else {
                        bounds.x = collision.x + collision.width;
                    }
                } else if (vertical) {
                    dy *= -1;
                    if (isTop) {
                        bounds.y = collision.y - bounds.height;
                    } else {
                        bounds.y = collision.y + collision.height;
                    }
                }

            }

            rotation += spin;

            setBounds(bounds);
            repaint();

        }
    }
}


text:
Q: Faulting module path: C:\Windows\system32\KERNELBASE.dll I have a .Net 4.0 C++ application that used to be built in 32bits. Obviously when running on a 64bits station I was having issues, therefore I started rebuilding everything in 64 bits. The whole project is converted as well as the libraries I had made for this in other project files. All references have been updated and everything compiles fine.
Once deployed to a 64bit station I now get the following errors in the windows event viewer:
Information : Windows Error Reporting
Fault bucket , type 0
Event Name: APPCRASH
Response: Not available
Cab Id: 0

Problem signature:
P1: EDI.exe
P2: 0.0.0.0
P3: 4e32e547
P4: KERNELBASE.dll
P5: 6.1.7601.17625
P6: 4de88429
P7: e0434352
P8: 000000000000cacd
P9:
P10:

Attached files:

These files may be available here:
C:\Users\developer\AppData\Local\Microsoft\Windows\WER\ReportArchive\AppCrash_EDI.exe_b14cfebcf86ccaf91a35dacab06a28cdf7277ba_17f14701

Analysis symbol:
Rechecking for solution: 0
Report Id: c9983227-ba04-11e0-9299-002713d66c71
Report Status: 0

Error : Application Error
Faulting application name: EDI.exe, version: 0.0.0.0, time stamp: 0x4e32e547
Faulting module name: KERNELBASE.dll, version: 6.1.7601.17625, time stamp: 0x4de88429
Exception code: 0xe0434352
Fault offset: 0x000000000000cacd
Faulting process id: 0x1704
Faulting application start time: 0x01cc4e118bde9f1d
Faulting application path: C:\Users\developer\Desktop\EDI_6.1.0.4160_x64\EDI_6.1.0.4160_x64\EDI.exe
Faulting module path: C:\Windows\system32\KERNELBASE.dll
Report Id: c9983227-ba04-11e0-9299-002713d66c71

Error : .Net Runtime
Application: EDI.exe
Framework Version: v4.0.30319
Description: The process was terminated due to an unhandled exception.
Exception Info: System.IO.FileNotFoundException
Stack:
   at <Module>.main(System.String[])

When I run dependency walker on the executable, I get to see the executable listed in the modules and nothing else at all comes up.  I am kind of out of ideas at the moment and wondering if anyone can make something of this?

A: Exception code: 0xe0434352
Not very common. Check this:
http://social.msdn.microsoft.com/Forums/en-GB/pex/thread/b9728c2d-130e-48f9-80c1-442ddbc1e85b

A: I just experienced this same error-code, also in Kernelbase.dll when attempting to debug a C++ application in VS2012.  Fortunately in my case I tracked the issue down to the Document Well (from Productivity Powertools Extension) option:
Environment-Tabs and Windows-Maintain pin status if document is removed from well.
Clearing this option fixed my problem.  It appears that DevStudio was crashing when rearranging the tabs/windows for debugging.
This may not be the cause of your particular issue, but I've added it here because if anyone else searches for error code: 0xe0434352 in Kernelbase.dll, this issue is at the top of the Google search.


text:
Q: Which of these two deck of card design pattern is more stable/ preferred? I am learning OOP concepts and this is in continuation of my previous question. Just for practice, I am designing a deck of cards.  I have two patterns in minds
public interface ISuit {
    String getLogo();
    String getName();
}

public class Card {
    ISuit suit;
    Integer n;

    public Card(ISuit suit, Integer n) {
        this.suit = suit;
        this.n = n;
    }

    void setSuit(ISuit suit){
        this.suit = suit;
    }

    void display(){
        System.out.println(suit.getName()+","+n);
    }
}

Second pattern
public interface Icard<T extends ISuit> {
    T getSuit();
    String getNumber();
}

public  class Queen<E extends ISuit> implements Icard<E> {
    Class<E> clazz;

    public Queen(Class<E> clazz) {
        this.clazz = clazz;
    }

    @Override
    public String getNumber() {
        return "12";
    }

    @Override
    public E getSuit() {
        try {
            return clazz.newInstance();
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}

Obviously, the first one is more intuitive and straight-forward. Over there, I will 52 objects of cards with right suit, number as parameter.
In the second design, I will create 13 classes for each index of cards and then instantiate them with correct suits. In future, if there is a new index, I can create a new class extending Icard.
As a newbie, I can't figure out if there are any disadvantages of the second design or if I am violating any design principle.
Could somebody please help me with this?

A: 52 classes (54 if you wanted to include jokers)  is extreme.  This is easily accomplished with one, maybe two classes, if you wanted to have another construct to represent the specific suits.
Think of it like this.  What actually makes up a card?

*

*The suit

*The face value

*Its proper name (i.e. 10 of Clubs)

If we want to decompose that a bit more, we could say that a suit is only ever going to be one of four values - spades, clubs, hearts, and diamonds - which lends itself well to an enumeration.
The face value varies between card games, and depending on how you want to represent Ace, it could either be the highest valued card for a suit, or the lowest valued card for the suit.  You'd want some special behavior for the face value that you want.
I see two classes to begin with - one for Card that defines the basic containers of all of the metadata we care about, and an enum for Suit that defines the four cardinal suits we support.
For joker support, you could either consider jokers to be either red or black (and you could choose an appropriate red/black suit to follow), or leave the suit undefined.  This again varies for what kind of card game you're actually playing, but it's important to consider.


text:
Q: jquery not working in .appended content I have a div, which has content populated on load (a bunch of 'span' tags with a delete link in each. clicking the delete button will remove that span. Now you can also add new 'span' tags to it using a separate button (each with their own delete button). The initially loaded span delete buttons work fine, but the newly added ones do not delete.

Instance 1 delete
Instance 2 delete

Add an instance

$('.addinstance').click(function () {
$('.instances').append('More delete ');
});

$('.instances .del').click(function (event) {
event.preventDefault();
$(this).parent('.item').hide();
});

Check out the fiddle I made for a working version of this:
http://jsfiddle.net/Ac7x6/3/
In the fiddle:

*

*Click the delete button on Instance 1 - works fine.

*Click the 'Add an Instance' button - this adds an new entry.

*Click the 'delete' button on the newly added instance - does not delete.
I have read a lot about this issue, including jquery .on(). Just not sure exactly how to implement them.
Help! :)

A: Use event delegation for dynamically generated items, If you wanna remove the item then use remove()
$('.instances').on('click','.del',function (event) {
    event.preventDefault();
    $(this).parent('.item').remove();
});

Fiddle Demo

A: try this,
$(document).on("click", '.instances .del', function (event) {
    //your code
});


text: Q: Hide window resize button When creating an NSWindow that has the NSResizableWindowMask flag set, Cocoa always draws a resize button in the bottom-right hand corner of the window. This button doesn't integrate very nicely with my custom drawn UI graphics so I'd like to know: Is there a way to tell Cocoa not to draw this button but still keep my window resizable?


text:
Q: Lowenheim-Skolem number for satisfaction via continuous function rings EDIT: now asked at MO.
For $\mathcal{X}$ a topological space, let $C(\mathcal{X})$ be the ring of continuous functions $\mathcal{X}\rightarrow\mathbb{R}$. For a first-order sentence $\varphi$ in the language of rings, write $\mathcal{X}\models_{C}\varphi$ iff $C(\mathcal{X})\models\varphi$ in the usual sense. Say that $\varphi$ is C-satisfiable iff $\mathcal{X}\models_C\varphi$ for some topological space $\mathcal{X}$.
I'm generally curious about analogues of classical model-theoretic questions in this context. For example:

What is the least cardinal $\kappa$ such that, if $\varphi$ is $C$-satisfiable, then $\mathcal{X}\models_C\varphi$ for some space $\mathcal{X}$ with cardinality $<\kappa$?

The obvious Lowenheim-Skolem argument doesn't help much here. Roughly speaking, given $\mathcal{X}\models_C\varphi$ we can form a "small" elementary substructure $(\mathcal{Y}, R)$ in the usual first-order sense of (an appropriate version of) the pair $(\mathcal{X},C(\mathcal{X}))$. However, in general we might have $R\subsetneq C(\mathcal{Y})$ (this is similar to the distinction between Henkin and standard semantics for second-order logic).
(Of course number of points isn't the only cardinal invariant for which we could ask a Lowenheim-Skolem flavored question, but it seems the simplest to start with. Another natural thing to do would be to restrict attention to a "nice" class of spaces, e.g. the compact Hausdorff spaces, but again this seems like a better first step.)
One issue here is that I don't know an abstract characterization of which rings are isomorphic to some $C(\mathcal{X})$. Obviously any such ring $R$ must be the underlying ring of a commutative associative unital $\mathbb{R}$-algebra, but beyond that I don't see anything. I recall seeing a very snappy theorem addressing this, but I can't find it at the moment (I think it was more complicated than just "any commutative associative unital $\mathbb{R}$-algebra's underlying ring," but I'm not certain).

My broader interest incidentally is in what happens if we replace $\mathbb{R}$ with some other topological structure (= first-order structure + topology such that all functions are continuous and all relations are closed, as subsets of the appropriate product space). Given a topological structure $\mathcal{A}$ and a topological space $\mathcal{X}$ we can always turn the set of continuous maps from $\mathcal{X}$ to $\mathcal{A}$ into a structure of the same type as $\mathcal{A}$ by defining everything "pointwise." So for each topological structure $\mathcal{A}$ we get an analogue $\models_C^\mathcal{A}$ of the relation $\models_C$ above.
Ultimately my interest is in developing a connection between "coarse" model-theoretic properties (e.g. variants of the Lowenheim-Skolem number) of $\models_C^\mathcal{A}$ and topological algebraic properties of $\mathcal{A}$. While this question specifically asks about $\mathcal{A}=\mathbb{R}$, if anyone has information about a different ("nontrivial") $\mathcal{A}$ or class of $\mathcal{A}$s I'd be very interested.

A: This is not even close to a complete answer, but it at least shows that $\text{ZFC}\vdash\kappa>2^{\aleph_0}$, so I will record it here. Let $$\varphi\equiv\forall u\left[u^2=u\to(u=0\vee u=1)\right]$$ be the sentence expressing that there are no non-trivial idempotents. Then $\mathcal{X}\models_C\varphi$ if and only if $\mathcal{X}$ is connected. To see this, first suppose $\mathcal{X}$ is disconnected, say with a decomposition $\mathcal{X}=U\sqcup V$ for non-empty open subsets $U,V$; then the map $\alpha:\mathcal{X}\to\mathbb{R}$ defined by $x\mapsto 0$ if $x\in U$ and $x\mapsto 1$ if $x\in V$ is a non-trivial idempotent element of $C(\mathcal{X})$. Conversely, suppose $C(\mathcal{X})$ has a non-trivial idempotent $\alpha$. Since the ring $\mathbb{R}$ has no non-trivial idempotents, we have $\alpha(x)\in\{0,1\}$ for each $x\in\mathcal{X}$; since also $\alpha\neq 0,1$, we have that $\alpha^{-1}(\{0\})$ and $\alpha^{-1}(\{1\})$ are both non-empty. This gives a partition of $\mathcal{X}$ into disjoint non-trivial open subsets, whence $\mathcal{X}$ is not connected.
Now let $\psi\equiv \exists u\left[u\neq 0\wedge\forall v(u\cdot v\neq 1)\right]$. I claim that $\varphi\wedge\psi$ is $C$-satisfiable, but that $\mathcal{X}\not\models_C\varphi\wedge\psi$ for any $\mathcal{X}$ whose cardinality is smaller than $2^{\aleph_0}$. To see that it is $C$-satisfiable, note that, for example, $\mathbb{R}\models_C\varphi\wedge\psi$, where $\mathbb{R}$ has the standard topology. Indeed, $\mathbb{R}$ is connected, so $\mathbb{R}\models_C\varphi$ by the remarks above; furthermore, the function $\alpha:\mathbb{R}\to\mathbb{R}$ given by $x\mapsto 0$ when $x\leqslant 0$ and $x\mapsto x$ when $x\geqslant 0$ is a non-invertible non-zero element of $C(\mathcal{X})$, whence $\mathbb{R}\models_C\psi$ as well.
To see that $\mathcal{X}\not\models_C\varphi\wedge\psi$ for any $\mathcal{X}$ of cardinality smaller than $2^{\aleph_0}$, suppose that $|\mathcal{X}|<2^{\aleph_0}$ and that $\mathcal{X}\models_C\varphi$. Then $\mathcal{X}$ is connected by the remarks in the first paragraph, so for any $\alpha\in C(\mathcal{X})$ the subspace $\alpha(\mathcal{X})\subset\mathbb{R}$ is connected as well. Connected subsets of $\mathbb{R}$ are precisely intervals; since $|\mathcal{X}|<2^{\aleph_0}$, this forces each $\alpha(\mathcal{X})$ to be a singleton. So every element of $C(\mathcal{X})$ is a constant function, whence $C(\mathcal{X})\cong\mathbb{R}$ as rings, whence $\mathcal{X}\models_C\neg\psi$, as desired.

A: If $\mathcal Y\Vdash \phi$ for some compact Hausdorff space $\mathcal Y$ then $\mathcal X\Vdash \phi$ for some compact Hausdorff $\mathcal X$ of cardinality $\leq \beth_2.$ So a "compact Hausdorff satisfiability" version of your question has $\kappa\leq\beth_2^+.$ I don't know how to improve your bound in the general case, or whether $\beth_2^+$ is optimal for the compact Hausdorff case.
Fix a compact Hausdorff $\mathcal Y.$ We will try to find a space $\mathcal X$ of cardinality $\leq\beth_2$ that is elementarily equivalent to $\mathcal Y.$
Let $B(\mathcal Y)$ denote the set of continuous functions $\mathcal Y\to[-1,1].$ The approach will be to take a subset $A\subset B(\mathcal Y)$ of cardinality $\leq\mathfrak c$ that is "countably saturated with respect to $B(\mathcal Y)$" in the sense that for any countable $F\subseteq A,$ any type $\Lambda(f)$ over $A$ that is realized in $B(\mathcal Y)$ is also realized by a scalar multiple of an element of $A.$
Introduce variables $x_i, i<\mathfrak c.$
For each $\alpha\in\mathfrak c$ pick a 1-type $\Lambda_\alpha$ over a countable subset of $\{x_\beta:\beta<\alpha\},$ such that every such type gets hit at some point. Then build $A$ by transfinite iteration, where at step $\alpha$ we add a realization $f_\alpha\in B(\mathcal Y),$ if any exists, for the type $\Lambda_\alpha(f)$ with variables $x_\beta$ replaced by $f_\beta$ for $\beta<\alpha,$ and set $f_\alpha=0$ otherwise.
Let $P$ be the product $[-1,1]^A.$ Take $\mathcal X$ to be the image of $\phi:\mathcal Y\to P,$ where $x$ is sent to $a\mapsto a(x).$ Consider a continuous function $f:\mathcal X\to\mathbb R.$ Since $\mathcal X$ is compact, $f$ is bounded, so it is an integer multiple of a function $f/k$ with values in $[-1,1].$ I claim that $f/k$ is already a scalar multiple of a function in $A.$ We can extend $f/k$ to a function $g:P\to[-1,1].$
This $g$ factors through the projection $[-1,1]^A\to[-1,1]^{A_0}$ for some countable $A_0.$ One way to see this is that the preimage of each closed interval $[a,b]$ with $a,b\in\mathbb Q$ is a compact $G_\delta,$ which can be written as a countable intersection of finite unions of basic opens. So $g$ is continuous using the topology on $[-1,1]^A$ generated by basic opens using indices in some countable $A_0.$ But $g$ will then already be uniquely specified by some type over $A_0,$ and hence will already be in $A.$ The countable saturation, in fact just finite saturation, shows that $\mathcal Y$ is an elementary submodel of $\mathcal X.$ Note $|\mathcal Y|\leq \beth_2.$
Remarks.

*

*C. Ward Henson studied a related question in "Nonstandard hulls of Banach spaces", for positive bounded formulas.

*For general spaces there is a ring isomorphism $C(\mathcal X)\cong C(\mathcal Y)$ if and only if the "Hewitt realcompactifications" of $\mathcal X$ and $\mathcal Y$ are homeomorphic. I'm not sure this helps directly, but it might be what you were thinking of as a characterization interesting.

*Some papers (at least Henson's) talk in terms of Banach algebras. For the compact Hausdorff case we're talking about (the ring reduct of) the real Banach algebra $C(\mathcal X).$ There is a bi-interpretation of complex arithmetic with complex conjugation, so we could equivalently talk about complex Banach algebras.

*My guess is that we can always take $\mathcal X$ to be a Polish space. Perhaps we can take $A$ to be a countable sequence of generic functions, i.e. an element in a comeager set of $B(\mathcal Y)^\omega.$


text:
Q: In composer.json is there a way to specify the repo to use for an individual package? I'm working in PHP and there are two repositories from which I am pulling packages.  Call them Repository1 and Repository2.  Repository1 has the higher priority.  One of the packages I need (PackageA) is in both repositories.  I need version X, which resides in Repository2.  Since Repository1 doesn't have version X, I have to make Repository1 not canonical.  Another package (PackageB) also exists in both repositories.  Furthermore, both repositories have a version Y.  The packages are not indentical.  When I specify "PackageB": "Y" it is giving me the package from Repository2, but I need the one in Repository1.
"repositories": [
    {
        "type": "composer",
        "url": "https://packagist.repo1.net",
        "canonical": false
    },
    {
        "type": "composer",
        "url": "https://packagist.repo2.net",
    }
],
"require": {
    "PackageA": "X",
    "PackageB": "Y"
}

So my question is, given that Repository1 can't be canonical, is there a way to tell composer to pull PackageB from Repository1?

A: TBH, I think this is like asking if there is a way to hit yourself with a hammer and not have it hurt. The answer is stop hitting yourself with a hammer. The solution for this problem is for me to clean up the mess of two repos with identical packages.
To clarify, I still don't know if there is a way to specify repos at a per-package level, but I suspect the answer is no.  I don't think there is any "reasonable" use case for such functionality.  My case of having two packagist repos with non-matching package with the same name and version is not reasonable.  What I did to solve it was figure out which package we wanted to use and either rename or remove the packages in our private packagist.


text:
Q: Win32 not recognising the outlook email in Jupyter notebook Tried to read the outlook email in jupyter notebook for creating a ML algorithm but the win32 is not recognising my outlook account. It was working fine yesterday but somehow same code not wrking today.
Any suggestions please?
Attached my code below.
import win32com #.client
import pyttsx3
#other libraries to be used in this script
import os
from datetime import datetime, timedelta

outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
# mapi = outlook.GetNamespace("MAPI")
# mapi
# for account in outlook.Accounts:
#     print(account.DeliveryStore.DisplayName)
# account
# inbox = outlook.GetDefaultFolder(6)
outlook.Accounts

The result I'm getting is

A: I've hit something similar in this question.
EDIT: An update. It seems that the Python iter(obj) function implicit in the for loop is not necessarily calling obj.__iter__() but calls instead obj.__class__.__iter__(obj) and this isn't working properly for some reason (I read this in an SO answer that I have lost), so one solution is to call __iter__() directly.
eg this works:
import win32com.client
ns = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")

accs = ns.Accounts
for ac in accs.__iter__():
    print(ac.DisplayName)

//EDIT
The issue seems to be that all of a sudden the Collection objects are not iterable when they should be. For example:
import win32com.client
ns = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")
accs = ns.Accounts

then:
accs.Count

returns 1 (I have one account)
But this subsequent code:
for ac in accs:
    print(ac.DisplayName)

gives this error:
TypeError                                 Traceback (most recent call last)
Cell In [20], line 1
----> 1 for ac in accs:
      2     print(ac.DisplayName)

TypeError: 'Accounts' object is not iterable

If you don't use the built-in Python iteration, but instead iterate by (1-based) index:
accs = ns.Accounts
for n in range(1,accs.Count+1):
    ac = accs.Item(n)
    print(ac.DisplayName)

you get a list of accounts as expected.
I did raise a bug-report for win32com here but I am not sure anything happened. Interestingly I don't get this issue with the Folders collection, eg
fldrs = ns.Folders
for f in fldrs:
    print(f.Name)

works as expected.
So the workaround is to use explicit indexing using the Item() method of the collection.
EDIT: You can also try deleting everything in your %APPDATA%\Local\Temp\gen_py\x.x folder (where x.x is the Python version) and re-trying.

A: The following line of code contains multiple method calls:
outlook = win32com.client.Dispatch('outlook.application').GetNamespace("MAPI")

So, I'd recommend splitting them by declaring each method call on a separate line of code:
outlook = win32com.client.Dispatch('outlook.application')
nameSpaceObj = outlook.GetNamespace("MAPI")

Following that way you can find which method exactly gives the error (if any).
Sometimes you need to get the standard folder first (for example, Inbox) to get MAPI subsystems initialized:
inbox = nameSpaceObj.GetDefaultFolder(6)

Another possible cause is already running Outlook instance. In that case you need to try to retrieve the running instance on the system. Use the GetObject function instead:
outlook = win32com.client.GetObject('outlook.application')

You can't run two instances of Outlook at the same time on the computer.


text:
Q: Using a composer script with a hyphen in the name? I a'm trying to use the following script from Github: https://github.com/php-webdriver/php-webdriver
Installing with composer in "/mnt/hgfs/" was easy, but loading the class in a php file seems impossible
As you can see, there is a hyphen in the name, and i can't seem to load the class in any way. I have googled for a lot and tried many things, but same problem, either i get:
Trying to use the hyphen in namespace and use i get

PHP Parse error:  syntax error, unexpected '-', expecting '{' in
  /mnt/hgfs/test.php on line 3

Replacing hyphen with underscore, or just removing it i get:

PHP Fatal error:  Uncaught Error: Class
  'php_webdriver\WebDriver\Remote\DesiredCapabilities' not found in
  /mnt/hgfs/test.php:10

This is how my code looks (/mnt/hgfs/test.php):
namespace php_webdriver\WebDriver;
require 'vendor/autoload.php';
use php_webdriver\WebDriver\Chrome\ChromeOptions;
use php_webdriver\WebDriver\Chrome\ChromeDriver;
use php_webdriver\WebDriver\Remote\DesiredCapabilities;
use php_webdriver\WebDriver\Remote\RemoteWebDriver;

$host = 'http://localhost:4444/wd/hub'; // this is the default
$capabilities = DesiredCapabilities::htmlUnitWithJS();
{
    $options = new ChromeOptions();
    $options->addArguments(array(
        '--disable-extensions',
        '--no-sandbox',
        '--headless',
        '--no-proxy-server'
    ));
    $capabilities = DesiredCapabilities::chrome();
    $capabilities->setCapability(ChromeOptions::CAPABILITY, $options);
    $capabilities->setPlatform("Linux");
}
$driver_spec = RemoteWebDriver::create($host, $capabilities, 600000, 600000);

How should I load this class?

A: There are a couple of things wrong here:
namespace php_webdriver\WebDriver;

You shouldn't be trying to add your code to the webdriver namespace. For a test script you don't need your own namespace. You can probably delete this line.
As for:
require 'vendor/autoload.php';
use php_webdriver\WebDriver\Chrome\ChromeOptions;
use php_webdriver\WebDriver\Chrome\ChromeDriver;
use php_webdriver\WebDriver\Remote\DesiredCapabilities;
use php_webdriver\WebDriver\Remote\RemoteWebDriver;

I get the impression you're not 100% familiar with how PSR-4 / autoloading works. The namespace is mapped to a code directory by autoload.php, and the two don't necessarily have to have the same naming structure.
Take a look at the composer.json in the webdriver project, and pay attention to the PSR-4 section.
"Facebook\\WebDriver\\": "lib/" tells you that anything in the lib directory is to be considered as being in the Facebook\WebDriver namespace.
Try
require 'vendor/autoload.php';
use Facebook\WebDriver\Chrome\ChromeOptions;
use Facebook\WebDriver\Chrome\ChromeDriver;
use Facebook\WebDriver\Remote\DesiredCapabilities;
use Facebook\WebDriver\Remote\RemoteWebDriver;


text:
Q: How to Upload Multipart Data Using Alamofire.upload with HTTPS Request? I have made it work with HTTP request, however still cannot find a way to make HTTPS request using alamofire/upload/multipartFormData. Anyone could help?
func UploadUserPhoto (Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){
    let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
        certificates: ServerTrustPolicy.certificates(),
        validateCertificateChain: true,
        validateHost: true
    )
    let serverTrustPolicies: [String: ServerTrustPolicy] = [
        "***********": serverTrustPolicy,
    ]
    let sessionManager = SessionManager(
        serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
    )
    let parameters = ["Authorization": Token ?? "Does not contain authorization information"]
    sessionManager.upload(multipartFormData: { multipartFormData in
        if let imageData = Photo.jpegData(compressionQuality: 1) {
            multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
        }
        for (key, value) in parameters {
            multipartFormData.append((value.data(using: .utf8))!, withName: key)
        }}, to: "https://***********/uploaduserphoto/\(Username)", method: .post, headers: parameters,
            encodingCompletion: { encodingResult in
                switch encodingResult {
                case .success(let upload, _, _):
                    upload.response(completionHandler: { (response) in
                        if response.response?.statusCode == 200{
                            completion(true)
                        } else {
                            completion(false)
                        }
                    })
                case .failure(let encodingError):
                    print("error:\(encodingError)")
                    completion(false)
                }
    })
}

Update:
I finally found the code is good, the certificate was bad. After re-create a self-signed certificate, i worked. Thanks
Error Indicate That:
2018-11-20 12:49:45.130697+0800 TalentBaby1.0[1359:288066] Task <09FA46A5-9791-42DB-97AD-78A351050916>.<1> load failed with error Error Domain=NSURLErrorDomain Code=-999 "cancelled" UserInfo={NSErrorFailingURLStringKey=https://*******/uploaduserphoto/User, NSErrorFailingURLKey=https://*******/uploaduserphoto/User, _NSURLErrorRelatedURLSessionTaskErrorKey=("LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>"), _NSURLErrorFailingURLSessionTaskErrorKey=LocalUploadTask <09FA46A5-9791-42DB-97AD-78A351050916>.<1>, NSLocalizedDescription=cancelled} [-999]

A: Since you are already using Alamofire, try and use their upload instead of the SessionManager upload. Try this :
func UploadUserPhoto(Photo: UIImage, Username: String, completion: @escaping (_ result: Bool) -> Void){

    let headers = ["Authorization": Token ?? "Does not contain authorization information"]

    Alamofire.upload(multipartFormData:{ multipartFormData in
        if let imageData = Photo.jpegData(compressionQuality: 1) {
            multipartFormData.append(imageData, withName: "Photo", fileName: "file.png", mimeType: "image/png")
        }
    },
                     usingThreshold:UInt64.init(),
                     to:"https://***********/uploaduserphoto/\(Username)",
        method:.post,
        headers:headers,
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .success(let upload, _, _):
                upload.response(completionHandler: { (response) in
                    if response.response?.statusCode == 200{
                        completion(true)
                    } else {
                        completion(false)
                    }
                })
            case .failure(let encodingError):
                print("error:\(encodingError)")
                completion(false)
            }
    })
}


text:
Q: Math function in python not working when creating a python.exe file I am using this in cmd to create a .exe python file to run on PC.
pyinstaller --hidden-import plyer.platforms.win.notification --onefile abc.pyw

However, after which the program gets executed, math function is not working. While the program gets executed properly when run on cmd as a python file.
Is there any specific import which is required.?
Please help me out.


text:
Q: JavaNullPointerException on calling function I get an error when I call a function in java.
The return type is void, and I just call it and display a string inside.
Here is the call of the bugging function :
@RequestMapping(method = RequestMethod.POST)
public String findDevicesByCriteria(@Valid @ModelAttribute Device device, BindingResult bindingResult, Model uiModel) {
    if (isCriteriaEmpty(device)) {
        uiModel.addAttribute("criteriaEmptyWarning", "error_search_criteria_empty");
        return ViewConstants.DEVICE_SEARCH_VIEW;
    }
    identityService.searchDevices(device.getSerialNumber(), device.getOwner().getSiteName(), device.getIpAdress(), device.getInstallDate(), device.getEndDate()); // the error come from here

    return ViewConstants.DEVICE_SEARCH_VIEW;
}

The prototype in the interface of the bugging function :
/**
 * Search devices.
 *
 * @param sn the serial number of the device
 * @param site the site of it
 * @param ipAdress the ip adress of it
 * @param installDt the install date of it
 * @param endDt the end date of it
 * @return the list of device
 */
void searchDevices(String sn, String site, String ipAdress, Date installDt, Date EndDt);

And finally the function that cause problem :
 public void searchDevices(String sn, String site, String ipAdress, Date installDt, Date EndDt) {

    System.out.println("toto");

}

Please advice
Regards

A: Check whether the device is null or not before accessing the values
if(device != null)
{
   identityService.searchDevices(device.getSerialNumber(), device.getOwner().getSiteName(), device.getIpAdress(), device.getInstallDate(), device.getEndDate());
}

A: Check that none of the following objects is null.
identityService
device
device.getOwner()

A: Either of identityService or service has not been initialized and therefore is null. Then you get a NullPointerException when you try to use it.

A: 1.Plz. Confirm whether you have declared and defined the bean for identity service. (Most probably it would be @Autowired in your controller and defined as bean in your SpringBean context file) and correct the discrepancies found if any.

*Whether Object device is null or not. If it is, then check your request headers and body (which leads to creation of Device object referenced by you).

It would be far more easy to pin point the issue if you could share whole your controller file(from where the function is called and debug point on line from where null pointer is thrown).


text:
Q: Static initializer not called on Activity creation I have the following code in my main Activity:
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Fabric.with(this, new Crashlytics());
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        MyClass[] arr = MyClass.values();
        System.out.println(Arrays.deepToString(arr));

MyClass is as follow:
public class MyClass {

    public static MyClass A;
    public static MyClass B;
    public static MyClass C;

    static {
        System.out.println("Invoked");
        A = new MyClass("a");
        B = new MyClass("b");
        C = new MyClass("c");
    }

    private static Map<String, MyClass> values = null;
    private final String name;

    private MyClass(String name) {
        this.name = name;
        if (values == null)
            values = new HashMap<>();
        values.put(name, this);
    }

    public static MyClass[] values() {
        return values.values().toArray(new MyClass[values.size()]);
    }
}

My issue is that values() triggers a NullPointerException, as values is null, i.e. the static initialization block seems not to be invoked. Nevertheless, the console out "Invoked" appers, so the initialization block DOES get called.
What's wrong?
EDIT: this question is strictly related to this: Issue with static code in Android

A: It's because private static Map<String, MyClass> values = null; is after the static initializer: this assignment will be run after the static initializer block, so it is being assigned a non-null value, and then nulled out.
Move the values field before the initializer block.

BTW, I would decouple the creation of the instances from inserting them into the map, in order to remove the side effects when creating an instance of MyClass. You can also do it without a static initializer block:
public class MyClass {
    private static final Map<String, MyClass> values = new HashMap<>();

    public static final MyClass A = register(new MyClass("a"));
    public static final MyClass B = register(new MyClass("b"));
    public static final MyClass C = register(new MyClass("c"));

    private static MyClass register(MyClass instance) {
      values.put(instance.name, instance);
      return instance;
    }

    private MyClass(String name) {
      this.name = name;
    }
    // ...
}

Actually, I wouldn't even do this: I'd use an enum - but I guess there is something in your real code that stops you from doing that.


text:
Q: Translating form collection input values to hide true values from users I have a form input on which an algorithm will depend.  I'd rather not expose the actual value to the users since it will unnecessarily reveal some business logic.  I'm currently using a helper options_for_val1 hash with the dropdown text as key and values as [1,2,3,4,5], which are not the values I ultimately need for the algorithm.  My form is:
=f.select :val1, options_for_val1, :prompt => 'Select One'

Is there a smart way to translate the 1-5 values submitted by the form to the actual values I need? Like some type of validator?


text:
Q: Laravel view not found 5.2 I am getting 1 error, which is very strange.
Error : View [pages.email_templates.welcome_template_5] not found.
But the fact is that view file does exist in the mentioned folder.
I have tried following command but with no luck.
php artisan cache:clear
php artisan config:clear
php artisan config:cache

Controller :
$templatename = strtolower(str_replace(' ','_',$template_text->template_name));
return view('pages.email_templates.'.$templatename);

Best Part : Its working fine in localhost but  not in the server

A: did you tried php artisan dump-autoload or composer dump-autoload ?

A: First You need to clear your application cache and configuration
php artisan cache:clear
php artisan config:clear
php artisan view:clear

 $string1 = "pages.email_templates";
 $string2 = $templatename = strtolower(str_replace(' ','_',$template_text->template_name));

$page = sprintf("%s%s",$string1,$string2);

return view($page);

Autoload your all classes and class dependencies
composer dump-autoload

A: You should try this:
composer dumpautoload
php artisan config:cache
php artisan cache:clear
php artisan config:clear
php artisan view:clear

$templatename = strtolower(str_replace(' ','_',$template_text->template_name));
return view('pages.email_templates.'.$templatename);


text:
Q: Anonymous comparator in constructor using a cast to Comparable I'm having trouble writing an anonymous comparator inside a constructor. My instructions are as follows:
" your code should assume that the key type is comparable, that is, implements Comparable"
However, we're using
private Comparator<K> _comparator;

Our Data strcture also has a private class of Node:
private static class Node<K,V> extends AbstractEntry<K,V> {
    Node<K,V> left, right;
    Node(K k, V v) {
        super(k,v);
        left = right = null;
    }
}

I did try writing it like this:
public TreeMap() {

    _comparator = (Comparator<K>) new Comparator<Node<K,V>>(){
        @Override
        public int compare(Node<K, V> o1, Node<K, V> o2) {
            return ((Integer) o1.getKey()).compareTo((Integer) o2.getKey());

        }
    };
}

But this isn't correct because we're not supposed to be comparing nodes, or assuming the that key is an Integer. I'm also supposed to use an unchecked cast to Comparable, and I can't figure out how or where to do this.
The actual instructions from the assignment are as follows:
There are two constructors in the class you will write: one takes a comparator for the key type, which must not be null. The other doesn't, but if this constructor is used, your code should assume that the key type is comparable, that is, implements Comparable. Then this assumption is used to create a comparator that uses the compareTo method to do its work.
Any hints or ideas would be appreciated.

A: OK. So you need to write a comparator that sorts comparable keys, using their natural ordering. I.e. it should just delegate to their compareTo method.
So you want
Comparator<K> comparator = (a, b) -> ((Comparable<K>) a).compareTo(b);

Or, if you really want to write it as an anonymous inner class:
Comparator<K> comparator = new Comparator<K>() {
    @Override
    public int compare(K a, K b) {
        return ((Comparable<K>) a).compareTo(b);
    }
};


text:
Q: How to add elements to a vector in a loop Let's say I have a cell array raweeg each cell of which is a matrix with time points in the first column and some markers in the second. I want to create a vector to store the time points, when the marker is not equal to -1. I found a non-elegant (and not working) way to create a vector of zeros of size 1x1 and then to append the following values in a loop.
P.S.: There are exactly 96 non-"-1" values and corresponding time points.
startpoints = zeros(1,1);

for i = length(raweeg{1,1}(:,1))
   if raweeg{1,1}(i,2) ~= -1
   startpoints(end+1,1) = raweeg{1,1}(i,1);
   end
end

Thank you

A: Vectorize it like this, for a given cell of raweeg:
startpoints = raweeg{1,1}(raweeg{1,1}(:,2) ~= -1, 1);

This is called logical indexing.
Just be sure your markers are not generated with floating point computations, or the comparisons will likely fail often.

P.S.  The problem in your code is the for loop statement, which should be:
for i = 1:length(raweeg{1,1}(:,1))
Or better, for i = 1:size(raweeg{1,1},1).
With out the "1:" part, it just has a single iteration, the last row.


text:
Q: Knockout custom binding in foreach to get iterator I am trying to make a custom binding that is to be used within a foreach binding and would need access to the current observableArray and the $data.
Now I notice the bindingContext arg contains the $data, $parent, $root etc however I cannot seem to find a way to access the array being iterated, so is there a way?
Just to be clear here is a sort of example of what I mean:

   <button data-bind="customBinding: someArg">DoSomethingWithArrayAndElement</button>

In this instance customBinding seems to yield:

*

*$data = current element in iteration

*$parent = view model containing the People array

*root = same as $parent

*$index = current index in the iterating array

*$parents = array containing the view model

A: I'm not sure if this is the way to go, but without further knowledge about your app it's the only thing I can suggest: make a custom foreach binding that exposes the full array.

ko.bindingHandlers.customForeach = {
    init: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
      var newBindingContext = bindingContext.extend({iterator: valueAccessor()});

      return ko.bindingHandlers.foreach.init(element, valueAccessor, allBindingsAccessor, viewModel, newBindingContext);
    },
    update: function(element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
      var newBindingContext = bindingContext.extend({iterator: valueAccessor()});

      return ko.bindingHandlers.foreach.update(element, valueAccessor, allBindingsAccessor, viewModel, newBindingContext);
    }
  };

var ViewModel = function ViewModel() {
  this.items = ko.observableArray(['a', 'b', 'c', 'd']);
  };

ko.applyBindings( new ViewModel() );

This adds a new iterator property to your bindingContext, exposing the full array from inside it.

A: So your goal is to make the underlying array accessible within the foreach template?  If you asked me, you shouldn't model your code in that way.
With that said, all you really need is an alias to your array and make sure you set the alias when you use the foreach binding.  Naturally, there's many ways you can do this.
Probably the cleanest way would be to create an alias binding handler.  Then extend the existing foreach binding to add the aliases or create a new one.
ko.bindingHandlers.alias = {
    update: function(element, valueAccessor, allBindings, viewModel, bindingContext) {
        var value = valueAccessor();
        var aliasValue = value.data;
            aliasName = value.aliasName || '$alias';
        if (ko.isObservable(aliasValue)) {
            var rawValue = aliasValue,
                rawAliasName = value.rawAliasName || '$rawAlias';
            bindingContext[rawAliasName] = rawValue;
            aliasValue = rawValue();
        }
        bindingContext[aliasName] = aliasValue;
    }
};
ko.bindingHandlers.foreachex = {
    preprocess: function (value, name, addBinding) {
        addBinding('alias', "{ data: "+value+", aliasName: '$source', rawAliasName: '$rawSource' }");
        addBinding('foreach', value);
    }
};

Then you can just use the aliases in your view.

    <button data-bind="customBinding: someFunction($rawSource, $data)">
        DoSomethingWithArrayAndElement
    </button>

fiddle


text:
Q: Xslt template. xsl if not working I'm trying to create 2 tables one that display when is greater and one for when is less. The first table is working fine but creating a second table is not working.
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
                xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl"
>
  <xsl:output method="html" indent="yes"/>

  <xsl:template match="/">

        <title> Movies</title>

          Movies  Listing

            Movie ID
            Title
            Director
             Movie Year

          <xsl:apply-templates select="movies/movie">
            <xsl:sort select="title" order="ascending"></xsl:sort>
          </xsl:apply-templates>

  </xsl:template>

  <xsl:template match="movie">
    <xsl:if test="year<2005">

        <xsl:apply-templates select="@id"/>

        <xsl:apply-templates select="title"/>

        <xsl:apply-templates select="Director"/>

        <xsl:apply-templates select="year"/>

    </xsl:if>
    <xsl:apply-templates select="year">
  </xsl:template>

  <xsl:template match="year">

        Movie ID
        Title
        Director
         Movie Year

      <xsl:if test="year>=2005">

            <xsl:apply-templates select="@id"/>

            <xsl:apply-templates select="title"/>

            <xsl:apply-templates select="Director"/>

            <xsl:apply-templates select="year"/>

      </xsl:if>

  </xsl:template>

  <xsl:template match="@id">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="title">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="Director">

      <xsl:value-of select="."/>

  </xsl:template>

  <xsl:template match="year">

      <xsl:value-of select="."/>

  </xsl:template>

</xsl:stylesheet>

I created an if statement but is only working for the first table. Can I do a choose statement to create both table and test the element?

A: In the match="year" template, you use the condition test="year>=2005". A bare name year in an XPath expression means ./child::year, that is, select the year children of the context node. But the context node is a year element, and I doubt it has a child called year. Use test=".>=2005".
I suspect that the year element doesn't have children called title or Director either. I suspect what you really want is to have one template rule with match="movie[year>=2005]" and one with match="movie[year<2005]".
But since you haven't shown your input or expected output, it's hard to know exactly what you are trying to achieve.