text:
Q: Incorrect Syntax near Where for an Update query Here is the update query which i am using to update a table. It throws me an exception "Incorrect Syntax near Where" Why is that exception for? i have no idea.
    public bool UpdateLocationCountintoMerchantPackage(int PackageID, long MerchantID,int LocationCount)
    {
        try
        {
            SqlParameter[] parameters = new SqlParameter[]
            {
                new SqlParameter("@packageID",PackageID),
                new SqlParameter("@merchantID",MerchantID ),
                new SqlParameter("@locationCount",LocationCount )
            };
            string CommandText = string.Empty;
            CommandText = "Update Merchant_Package SET LocationCount Where MerchantID=@MerchantID";
            string ConnectionString = DbConnectionStrings.GetDbConnectionString();
            SqlHelper.ExecuteNonQuery(ConnectionString, System.Data.CommandType.Text, CommandText, parameters);
            return true;

        }
        catch (SqlException ex)
        {
            LogError("Error Occurred When Saving Merchant Location Count Data : MerchantID:" + MerchantID.ToString(), ex);
            return false;
        }
    }

this function is called from
protected void imgbtnSubmit_Click(object sender, ImageClickEventArgs e)
{

        UpdatePaymentInfo();
        string QueryString = Request.QueryString.ToString();
        if (string.Equals(QueryString, "MerchantProfilePages"))
        {
            Response.Redirect(ApplicationData.URL_ADD_PROFILE_PAGE, false);
            Merchant mrchnt = new Merchant();
            int PackId = mrchnt.PackageID;
            int x = GetLocationCount() + 1;
            mrchnt.UpdateLocationCountintoMerchantPackage(PackId, merchantId, x);
        }

A: Use SQL like:
Update Merchant_Package SET LocationCount=@LocationCount
Where MerchantID=@MerchantID

Your error on the 1st line was reported when WHERE was encountered

A: It's an issue with your "SET LocationCount" - you're not setting it equal to anything. That's why it's complaining about the WHERE.


text:
Q: Full screen toggle for jQuery video player does not assign class-name correctly I am working on a JavaScript/jQuery video player. It has a bug whose cause I was unable to find.
The players has, among others, an enter/exit full-screen button (it can be seen at the bottom of the HTML snippet):
(function($) {

  /* Helper functions */
  /* 1) full screen */
  function toggleFullScreen(elem) {
    if ((document.fullScreenElement !== undefined && document.fullScreenElement === null) || (document.msFullscreenElement !== undefined && document.msFullscreenElement === null) || (document.mozFullScreen !== undefined && !document.mozFullScreen) || (document.webkitIsFullScreen !== undefined && !document.webkitIsFullScreen)) {
      if (elem.requestFullScreen) {
        elem.requestFullScreen();
      } else if (elem.mozRequestFullScreen) {
        elem.mozRequestFullScreen();
      } else if (elem.webkitRequestFullScreen) {
        elem.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT);
      } else if (elem.msRequestFullscreen) {
        elem.msRequestFullscreen();
      }
    } else {
      if (document.cancelFullScreen) {
        document.cancelFullScreen();
      } else if (document.mozCancelFullScreen) {
        document.mozCancelFullScreen();
      } else if (document.webkitCancelFullScreen) {
        document.webkitCancelFullScreen();
      } else if (document.msExitFullscreen) {
        document.msExitFullscreen();
      }
    }
  }

  $('video').each(function() {
    var video = $(this)[0],
      videoContainer = video.closest('div'),
      $playToggleBtn = $(videoContainer).find('input[name="play-pause"]'),
      $progressBar = $(videoContainer).find('.progress-bar'),
      $progress = $(videoContainer).find('.progress'),
      $current_time = $(videoContainer).find('.current-time'),
      $durationDisplay = $(videoContainer).find('.duration'),
      $volumeSlider = $(videoContainer).find('.volume-slider'),
      $mute_toggle = $(videoContainer).find('.mute-toggle'),
      $muteBtn = $mute_toggle.find('input[type="checkbox"]'),
      $rate_display = $(videoContainer).find('.rate_display'),
      $fullScreenToggler = $(videoContainer).find('input[name="screen-toggler"]'),
      $playSpeed = $(videoContainer).find('.playback-rate ul li');

    $(document).bind('webkitfullscreenchange mozfullscreenchange fullscreenchange', function(e) {
      var state = document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen;
      var event = state ? 'FullscreenOn' : 'FullscreenOff';

      if (event === 'FullscreenOff') {
        $(videoContainer).removeClass('fullscreen');
        $fullScreenToggler.removeClass('exit');
      } else {
        $(videoContainer).addClass('fullscreen');
        $fullScreenToggler.addClass('exit');
      }
    });

  });

})(jQuery);

  <video poster="posters/poster.jpg">
            <source src="videos/mymovie.mp4" type="video/mp4" />
        </video>

<input type="button" name="play-pause" value="Play" class="play" />

Previous

Next

<input type="checkbox" name="mute" />

<input type="range" min="0" max="1" step="0.01" class="volume-slider" />

/

        Normal

0.5x

0.75x

Normal

1.125x

1.5x

2x

        <input type="button" name="screen-toggler" value="Fullscreen" class="toggle-fullscreen" />

The problem: If I have two videos (or more), even if I click the full-screen button of the first clip, the fullscreen class-name will be added to all the video-container elements on the page.
Why does that happen?
UPDATE:
Following Kaiido's answer I have resolved this issue using the following code.
$(document).on('fullscreenchange', evt => {
    if ($(document.fullscreenElement).is(videoContainer)) {
        $(document.fullscreenElement).addClass('fullscreen');
        $(videoContainer).removeClass('fullscreen');
        $fullScreenToggler.removeClass('exit');
    } else {
        $(videoContainer).removeClass('fullscreen');
        $fullScreenToggler.addClass('exit');
    }
});

The problem mentioned above was solved. Yet, I lost the ability to use the ESC key as full-screen exit.
UPDATE 2:
I have pushed the player in a Github repo.

A: You are binding an event to the Document object as many times as you have <video> elements in your page.
Stacksnippets don't allow fullscreen but a mockup of what you are doing is:

$('div').each(function(i, el) {
  $(document).on('click', e => console.log('clicked'));
  console.log('added click event on Document');
})

test

test

test

test

test

test

test

test

test

test

test

test

So every time you will enter or exit the fullscreen mode, all these events will fire and will set the calss on each of the videos regardless it was the one from where the event originated.
You'd be better add a single event handler outside of the each iterator, where you'd do
$(document).on('fullscreenchange', evt => {
  if($(document.fullscreenElement).is('video')) {
    $(document.fullscreenElement).addClass('fullscreen');
  }
  else {
    $('video.fullscreen').removeClass('fullscreen');
  }
});

But actually all your thing with the fullscreen class is useless since there is already a :fullscreen pseudo class that is natively set by browsers.

A: As far as I see the problem is that in the "fixed" version you are attaching a single listener of 'fullscreenchange' to the document. Then in the handler of that event, you are using elements defined in the videos-elements-loop:
$(videoContainer).removeClass('fullscreen');
 $fullScreenToggler.removeClass('exit');/
both videoContainer and fullScreenToggler won't work as you expect.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать валидацию полей react-native Есть экран регистрации, как сделать его валидацию???
export default function RegistrationScreen() {
  const navigation = useNavigation()
  const toLogin = () => {
    navigation.navigate('Login')
  }

  const [surname, setSurname] = useState('')
  const [name, setName] = useState('')
  const [email, setEmail] = useState('')
  const [password, setPassword] = useState('')
  const [confirmPassword, setConfirmPassword] = useState('')

  const [IsLoading, setIsLoading] = useState(false)
  const [error, setError] = useState('')

  const [_, setUser] = useAuth()

  const hanldeRegister = () => {
    setIsLoading(true)
    axios({
      method: 'POST',
      url: ,
      params: {
        key: ,
      },
      data: {
        email,
        password,
      },
    })
      .then((res) => {
        axios({
          method: 'POST',
          url: ,
          params: {
            key: ,
          },
          data: {
            idToken: res.data.idToken,
            displayName: name + ' ' + surname
          }
        }).then((r) => {
          setUser({...r.data, idToken: res.data.idToken})
        }).catch(e => {
          console.log(e, 'updaate profile error');
          alert(e.message);
        })
        .finally(() => {
          setIsLoading(false);
        })

        console.log(res.data)
      })
      .catch((error) => console.log(error.response.request._response))
  }

  return (
    <View
     style={styles.container}>
        <View style={styles.header}>
            <Pressable
            style={styles.quit_button_cont}
            onPress={toLogin}>
                <QuitBtn
                    style={[styles.quit_button]}
                    resizeMode='contain'/>
            </Pressable>
            <RegWord style={styles.regWord}/>
            <Image
                source={require('../assets/images/Logo_small.png')}
                style={styles.logo_s}
                resizeMode='contain'/>
        </View>
            <View
             style={styles.cont_inp}
             behavior="position">
                <CustomInput
                    value={name}
                    setValue={setName}
                    placeholder="Имя"
                    margin={10}/>

                <CustomInput
                    value={surname}
                    setValue={setSurname}
                    placeholder="Фамилия"
                    margin={10}/>

                <CustomInput
                    value={email}
                    setValue={setEmail}
                    placeholder="Логин"
                    margin={10}/>

                <CustomInput
                    placeholder="Пароль"
                    margin={10}
                    secureTextEntry={true}/>
                <CustomInput
                    placeholder="Повторите пароль"
                    value={password}
                    setValue={setPassword}
                    margin={10}
                    secureTextEntry={true}
                    flex={1}/>
                <CustomButton
                    text={"Зарегистрироваться"}
                    onPress={hanldeRegister}
                    margin={0}/>
            </View>
    </View>
)
}


text:
Q: How to update a TYPO3 extension with composer? How do I update a specific extension (and only this extension) in composer mode?

A: To update an extension you only need this command:
composer update <vendor/package>

If you want to update all dependencies in this extension as well, add the option --with-all-dependencies:
composer update <vendor/package> --with-all-dependencies

or in short form
composer update <vendor/package> -W

If you need to perform a major update which cannot be handled with the given version in the composer.json, you can use this command:
composer require <vendor/package>:"^versionString"

Notice that you should not use composer update without a package name since this updates all packages at once. If something is broken after such an update, you will need to revert the whole update. Also Git bisect is impossible to find the specific package update which broke.


text:
Q: Issues when using randomForest in caret with ROC as optimization metric I'm having an issue when constructing random forest models using caret.  I have a dataset of about 46k rows and 10 columns (one of which is the optimization target).  From this dataset, I'm trying to compare different classifiers.  I did the following:
ctrl = trainControl(method="boot"
  ,classProbs=TRUE
  ,summaryFunction=twoClassSummary )

#GLM Model:
model.glm = train(x=d[,2:10]
  ,y=d$CONV_BT, method='glm'
  ,trControl=ctrl, metric="ROC"
  ,family="binomial")

#Random Forest Model:
model.rf = train(x=d[,2:10]
  ,y=d$CONV_BT, method='rf'
  ,trControl=ctrl, metric="ROC")

#Naive Bayes Model:
model.nb = train(x=d[,2:10]
  ,y=d$CONV_BT, method='nb'
  ,trControl=ctrl, metric="ROC" )

Then, model.glm and model.nb both look pretty decent.  I can look at the 25 bootstrap replications, and each case has an ROC of around .7.  However, something appears to be wrong with model.rf, because the reported ROC scores are all around .3.  That suggests to me that something is being specified incorrectly, because I could just switch my predictions from the rf model from p to 1-p and my ROC would then be .7, right?
I'm sorry that I can't provide the data (because it's pretty big to upload and it's proprietary).  The other bizarre thing is that when I simulate data, I no longer have this issue.  Any idea what this could be???  Thanks for your help!


text:
Q: Error when splitting a string in visual basic? I am trying to convert a floating point binary into a decimal number and i am struggling on how to split the mantissa up into two.
I have the following lines but not sure if it is correct:
 Dim mantissaarray() As String = Split(mantissa,,T)
 Dim first As Integer = CInt(mantissaarray(0))
 Dim second As Integer = CInt(mantissaarray(1))

the third line is where there is an error

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

Could someone tell me what i am doing wrong to get this error as i do not understand?
The mantissa is a string e.g 0110 and T is an integer e.g 2
Output to the array should be a split of the string by the third number e.g 01 and 10.

A: A String in .net is an array of Char. So, using this fact we can do one of the following.
Private Sub OpCode()
    Dim mantissa = "0110"
    'The Linq way
    Dim intArray = (From c In mantissa
                    Select CInt(c.ToString)).ToArray
    For Each i In intArray
        Debug.Print(i.ToString)
    Next
    'The For Each way
    Dim intArray2(mantissa.Length - 1) As Integer
    Dim index As Integer
    For Each c As Char In mantissa
        intArray2(index) = CInt(c.ToString)
        index += 1
    Next
    For Each i In intArray2
        Debug.Print(i.ToString)
    Next
End Sub

Same result.


text:
Q: PayPal Sandbox Recurring Payments I am trying to setup recurring payments in our SandBox.
I have followed the instructions here:
How to enable recurring payments for sandbox account?
I have a working Python Django code, have setup billing plans and foward the user to a billing agreement with an Activated plan but it errors on the PayPal page, that this is currently not possible.
So I checked the above link and understand I need to enable recurring payments in my facilitator sandbox account.
Once I go to the Recurring payments dashboard-> Sign up for Enhanced Recurring Payments
I only end up with a message saying: Sorry, this feature is not available at this time.
How am I supposed to test this now ? This Sandbox account is an Account type: Business and verified.


text:
Q: Puppeteer with Brave browser? I'm wondering if it's possible executing a puppeteer script using Brave browser instead of the basic version of chromium. I know that Brave has been developed from chromium, and for that reason you can launch a selenium script using brave, but do you know if it's possible with puppeteer as well?

A: Yes, you can use Brave. The only catch is the adblocking doesn't work with headless mode. For the adblocking in headful mode, you need to set/create a profile and point the userDataDir option to it because Brave downloads the filter lists the first time it launches and stores those lists in the profile.
const browser = await puppeteer.launch({
        headless: false,
        executablePath: "path/to/brave",
        userDataDir: "path/to/profile/dir"
});


text:
Q: find different values in factor in long form I have data in a long format, similar to the following
id <- c(rep(c(1L,2L,3L),3))

year <- c(rep(c(11,12,13),3))

df <- data.frame(id, year)[-c(8,3),]

df$factor <- factor(c("a", "b", "a", "c", "d","a","d"))

df

I would like to create an indicator variable that takes a value when the factor has changed (e.g. 1 for a change, 0 for no change), on the year the change appears. Is there an efficient way of doing this?
I found this question:
Identifying where value changes in R data.frame column
which is somewhat related but does not deal with the ids.

A: Probably, you are looking for :
library(dplyr)

df %>%
  group_by(id) %>%
  mutate(flag = factor != lag(factor, default = first(factor)))

#    id  year factor flag
#  <int> <dbl> <fct>  <lgl>
#1     1    11 a      FALSE
#2     2    12 b      FALSE
#3     1    11 a      FALSE
#4     2    12 c      TRUE
#5     3    13 d      FALSE
#6     1    11 a      FALSE
#7     3    13 d      FALSE

and in data.table :
library(data.table)
setDT(df)[, flag := factor != shift(factor, fill = first(factor)), id]


text:
Q: ES2020 optional chaining: what's the difference between a?.().b and a()?.b and a?.()?.b Suppose we have this object:
let obj = {};

What exactly each of these expressions do?

*

*obj.a?.().b

*obj.a()?.b

*obj.a?.()?.b

A: obj.a?.().b - If obj.a is null or undefined then the expression is undefined otherwise the expression evaluates to obj.a().b.
obj.a()?.b - If obj.a() is null or undefined then the expression is undefined otherwise the expression evaluates to obj.a().b
obj.a?.()?.b if obj.a or obj.a() is null or undefined then the expression is undefined otherwise the expression evaluates to obj.a().b.
Read more about optional chaining here.

A: obj.a?.().b

*

*Dereference obj directly.

*Dereference obj.a in a null-safe way - it will stop at this point if the property is not there, it is undefined or null. If that happens the result of evaluating the expression will be undefined.

*Execute that value directly.

*Receive the return result and continue.

*Get the property b from the result directly.

const tryIt = obj => {
  console.log("------start------");

  console.log("trying with", obj );

  try {
    console.log( "result", obj.a?.().b );
  } catch (e) {
    console.error("problem", e.message);
  }

  console.log("-------end-------");
}

tryIt( null );                 // ERROR
tryIt( {} );                   // undefined
tryIt( { a: undefined } );     // undefined
tryIt( { a: null } );          // undefined
tryIt( { a: false } );         // ERROR
tryIt( { a: "hello" } );       // ERROR
tryIt( { a: function() {} } ); // ERROR
tryIt( {                       // ERROR
  a: function() {
    return null;
  }
});
tryIt( {                       // 42
  a: function() {
    return { b: 42 };
  }
});

obj.a()?.b

*

*Dereference obj directly.

*Dereference obj.a directly.

*Executing that value directly.

*Handle the value in a null-safe way - it will stop at this point if the return value is null or undefined. If that happens the result of evaluating the expression will be undefined.

*Get the property b from the result directly.

const tryIt = obj => {
  console.log("------start------");

  console.log("trying with", obj );

  try {
    console.log( "result", obj.a()?.b );
  } catch (e) {
    console.error("problem", e.message);
  }

  console.log("-------end-------");
}

tryIt( null );                 // ERROR
tryIt( {} );                   // ERROR
tryIt( { a: undefined } );     // ERROR
tryIt( { a: null } );          // ERROR
tryIt( { a: false } );         // ERROR
tryIt( { a: "hello" } );       // ERROR
tryIt( { a: function() {} } ); // undefined
tryIt( {                       // undefined
  a: function() {
    return null;
  }
});
tryIt( {                       // 42
  a: function() {
    return { b: 42 };
  }
});

obj.a?.()?.b

*

*Dereference obj directly.

*Dereference obj.a in a null-safe way - it will stop at this point if the property is not there, it is undefined or null. If that happens the result of evaluating the expression will be undefined.

*Executing that value directly.

*Handle the value in a null-safe way - it will stop at this point if the return value is null or undefined. If that happens the result of evaluating the expression will be undefined.

*Get the property b from the result directly.

const tryIt = obj => {
  console.log("------start------");

  console.log("trying with", obj );

  try {
    console.log( "result", obj.a?.()?.b );
  } catch (e) {
    console.error("problem", e.message);
  }

  console.log("-------end-------");
}

tryIt( null );                 // ERROR
tryIt( {} );                   // undefined
tryIt( { a: undefined } );     // undefined
tryIt( { a: null } );          // undefined
tryIt( { a: false } );         // ERROR
tryIt( { a: "hello" } );       // ERROR
tryIt( { a: function() {} } ); // undefined
tryIt( {                       // undefined
  a: function() {
    return null;
  }
});
tryIt( {                       // 42
  a: function() {
    return { b: 42 };
  }
});

A: The optional chaining operator can be used in three locations:

*

*In place of the dot operator for property access (obj?.a)

*Immediately before the bracket syntax for property access (obj?.['a'])

*Immediately before a function invocation (obj.a?.())

In the property access position, if the property value is nullish (ie. null or undefined), then it immediately short-circuits the entire expression, and returns undefined.
In the function invocation position, if the function is nullish,  then it immediately short-circuits the entire expression, and returns undefined (thereby avoiding an "undefined is not a function" exception).
So:

*

*obj.a?.().b will return undefined if obj.a is nullish.

*obj.a()?.b will return undefined if the result of obj.a().b is nullish.

*obj.a?.()?.b will return undefined if a is nullish, or if the result of obj.a() is nullish.

A: TL;TR
The expression is checked for non-undefined, not-null values with ? and at any point if a value is found to be one of these, the chain simply breaks and returns undefined.
A very important point to note is it guards only against undefined and null values and not against falsy values i.e it will still pass other falsy values like NaN or "".
Long Explanation
Let's start with quoting MDN

The optional chaining operator provides a way to simplify accessing
values through connected objects when it's possible that a reference
or function may be undefined or null.

Consider an object like this:
 var obj = {
       a: {
           b: 1
       },
     }

Now for validating obj, obj's peroperty a and then a's property b to be not undefined and null, you may have to do something like this:
 obj && obj.a && obj.a.b

Optional chaining provides you an alternative to this. You can simply do like this:
obj?.a?.b

Now, let's say a happens to be a function which returns an object with property b which holds a value 1. Something like this:
 var obj = {
           a: function{
               return {b:1}
            },
       }

So, how will you validate obj and its fields now for the deeply nested b? Well, you can do something like this:
obj && obj.a && typeof obj.a === 'function' && obj.a() && obj.a().b

Or you can simply do
obj?.a()?.b

This just means check obj for non-undefined and not-null, (if it is)then check obj?.a() for the same, (if it is then)execute the method a() of obj. If after the execution the method returns a value (which is not undefined or null), then get the value of the property b from it.
At any point during this check, if a value is found to be undefined or null simply break the chain and return undefined
However, this will fail if a does not happen to be a function which was checked with typeof obj.a === 'function' in the previous expression.
Also, Note that at this point if obj.a() happens to return, say, "baz", it will be executed as
"baz".b which will give you undefined.
With this knowledge,  We can decipher this expression  easily:
   obj.a?.().b

It checks whether obj.a is non-undefined, not-null. If it is, execute obj.a() (Note that it will throw an error if obj.a does not happen to be a function but returns say, number 5)
If obj.a() happens execute successfully then .b of the retuned value will be checked.
Now This is left
obj.a?.()?.b

Well, this also executes like our previous executions:
check obj.a if it's  not-null and non-undefined. If it is,         execute obj.a. If that is also non-null and non-undefined, execute obj.a() and so on.
If at any point while checking, value is found to be null or undefined, the chain simply breaks.
A very important point to note that our operator ? guards only against undefined and null not against other falsy values .
Consider this

var a = undefined
var myVal = a?.details.b;
alert(a) //will return undefined

var a = ""
var myVal = a?.details.b;
alert(a) //Our guard fails us here and simply throws an error


text:
Q: jquery apply strike() method to object I am able to getting the selected string value in the following way,
    if(!window.Kolich){
      Kolich = {};
    }
    Kolich.Selector = {};
    Kolich.Selector.getSelected = function(){
      var t = '';
      if(window.getSelection){
        t = window.getSelection();
      }
      return t;
    }
    Kolich.Selector.mouseup = function(){
     var st = Kolich.Selector.getSelected();
  // alert(typeof(st)) //showing object
     var data = st.toString();
     data.strike();
    }

But i need to apply strike() method to the selected string.

A: Rather than using the strike() method, try using the DOM Range surroundContents() method instead.
if(!window.Kolich){
  Kolich = {};
}

Kolich.Selector = {};
Kolich.Selector.getSelected = function(){
  var t = '';
  if(window.getSelection){
    t = window.getSelection();
  }
  return t;
}

Kolich.Selector.mouseup = function(){
  var st = Kolich.Selector.getSelected();
  // alert(typeof(st)) //showing object
  //var data = st.toString();
  var range = st.getRangeAt(0);
  var strike = document.createElement("strike");

  range.surroundContents(strike);
}

Demo: http://jsfiddle.net/F8saX/


text:
Q: Fragmenting Data from a Data Frame So I am just starting out with Python and have a confusing task at hand. I have this dataframe of 100 elements with an column of 'counter' going from 1 to 10, and repeating 10 times.
Now, I want to split this dataframe into 10 different dataframes based on the counter.
I have tried using for loop and conditional statements to reset the loop when the counter goes back to 1, but then I am losing on the 10th element.
I hope I am able to explain my problem well.
Kindly guide me. I just need a direction about how to proceed in a situation like this.
Cheers!

A: import pandas as pd

# creating mock df
df = pd.DataFrame([{'counter':e,'col_name':'some_value'} for e in
range(1,11)])
df = pd.concat([df,df]).reset_index()

#slicing the df at every 10nth index
splitted_dfs = [df.iloc[e-10:e,:] for e in range(10,len(df)+1,10)]

You are probably loosing the 10th element because range(x,y) includes y-1 and not y.


text:
Q: AWS SNS and APNS: Can't use MDM certificate? I'm trying to use AWS SNS to send Apple Push Notifications using APNS for a simple mobile device manager (MDM) application.  I have the necessary certificates and APNS topics, and have verified that they work as expected when using other utilities to send an APNS message.  Now I'm trying to configure SNS, but am running into an issue.
I've created my SNS topic...
aws sns create-topic \
    ${REGION} \
    --name ${APNS_SNS_TOPIC_NAME}

That works successfully.  I try creating the SNS platform application...
ARN_STR=$(aws sns create-platform-application \
    ${REGION} \
    --name MDM_APNS \
    --platform APNS \
    --attributes PlatformCredential="\"$(openssl pkcs12 -in ${CERT_PATH}/${CERT_FILE} -nodes -nocerts -password pass:${CERT_PASSWORD})\"",PlatformPrincipal="\"$(openssl pkcs12 -in ${CERT_PATH}/${CERT_FILE} -nodes -nokeys -password pass:${CERT_PASSWORD})\"")

When this command runs, however, I get the following error:
An error occurred (InvalidParameter) when calling the CreatePlatformApplication operation: Invalid parameter: Attributes Reason: You provided a certificate of type MDM, which cannot be used to create an application of type iOS Production. Please select an application of type MDM or provide a certificate of type iOS Production

Can AWS SNS not be used to send APNS using an MDM certificate?  Does it only support standard APNS certificates?  Am I missing a parameter or setting here?


text:
Q: How to run multiple Selenium tests back to back I'm trying to perform dynamic web scraping by using Selenium and Python. The website I am trying to scrape has an input where almost 600 or so locations can be chosen. Each location has different facilities.
I want to scrape the name of the facilities as well as the address for each location.
I have the list of locations in an excel file. I used Pandas to import those locations and then tried to do a for loop where I go through each location, enter the location in the input, and then scrape the facilities that are outputted underneath.
But my for loop hasn't worked as intended and so every time I run the script, Selenium driver opens up and I scrape the facilities as intended for the first location. But then nothing happens after that. My goal is for the script to continue, either new Selenium browsers opening or a new location is entered into the input to scrape the facilities of the second location.
df = pd.read_excel('MA Cities - Licensed Child Care Search.xlsx')

for i in df:
    driver = webdriver.Chrome(options = options)
    driver.get('https://eeclead.force.com/EEC_ChildCareSearch')
    res = driver.execute_script("return document.documentElement.outerHTML")

    search = driver.find_element_by_id('j_id0:j_id2:j_id29:city')
    search.send_keys(i)
    search.send_keys(Keys.ENTER)

Solved it by putting the driver part in a function and then calling that function with a for loop from 0 to # of cities I am dealing with.

A: Solved it by putting the selenium driver part in a function and then calling that function with a for loop from 0 to # of cities I am dealing with.
for i in range(x):
    my_function(i)

And then in the function added
search.send_keys(df.iloc[i])


text:
Q: Making an optional template parameter a friend? There is a post explaining that a template parameter can be declared as friend with the following syntax:
template <typename T>
class A {
   friend T;
};

but what if in some scenarios A needs a fried and in others does not? Is it possible to make T an optional argument?
Is there a better solution than using some kind of FakeClass as T?
EDIT1: I found another solution:
    class B {};

    template <typename T>
    class A {
       friend T;
    };

    template <>
    class A<void> {
    };

int main()
{
    A<B> a1;
    A<void> a2;
    return 0;
}

but what if A is a complicated class with 300 lines of code? Is there an alternative solution without template specialization?

A: I think befriending a dummy is the cleanest thing you can do, since you can't inherit or conditionally declare friends. You don't even need to create a new dummy type, since:

[class.friend§3]
If the type specifier in a friend declaration designates a (possibly cv-qualified) class type, that class is declared as a friend; otherwise, the friend declaration is ignored.

Which means that you can pretend to befriend int or even void and they'll play along just fine.
This advice is valid only within the limits of the C++ standard and is not intended as a real life guideline. The poster declines any and all responsibilities concerning the application of the advice.

A: Try this
template<typename... T>
class A {
    private:
        static const int i = 10;
    public:
        friend typename std::conditional<sizeof...(T) == 1, T..., void>::type;
};

class X {
    public:
        static const int a = A<X>::i;
};

class Y {
    public:
        static const int a = A<>::i; // error, A::i is private
};


text:
Q: Получить данные в next js только один раз Как получить данные в Next Js только один раз на серверной стороне? Мне нужно получить актуальные данные пользовательской сессии, и сделать это только один раз. Сейчас все работает странно:
Данные получаются при один раз, но вот при смене роутера, Next JS опять пытается получить данные из сервера, но при этом куки уже = null
_app.js
MyApp.getInitialProps = async (appContext) => {
  const { ctx } = appContext;
  let users = []
  await network.api({
    method: 'get',
    url: 'users/'+appContext.ctx.req.user_id,
  headers: {
      'Api-Key': appContext.ctx.req.cookies.access_token
  }
  }).then(response => {
    users = response.data
  })
  return { users};
};

При роутинге:
TypeError: Cannot read properties of undefined (reading 'user_id')


text:
Q: Seeing if all the values in an array are the same - Visual basic My code is below, what I need from the sub quicker is if the first value in the array A is the same as every single other value in A, I could do it by typing out some large if statements but I would rather not do that.
Thanks in advance
Public Function Areas_Of_England_Checker()
    Dim South_East() As System.Drawing.Color = {Oxfordshire.BackColor, Buckinhamshire.BackColor, Berkshire.BackColor, Hampshire.BackColor, Isle_Of_White.BackColor, West_Sussex.BackColor, Kent.BackColor, Surrey.BackColor, London.BackColor}
    Dim South_West() As System.Drawing.Color = {Devon.BackColor, Cornwall.BackColor, Somerset.BackColor, Whiltshire.BackColor, Gloucestershire.BackColor, Dorset.BackColor}
    Dim East_Anglia() As System.Drawing.Color = {Hertfordshire.BackColor, Bedfordshire.BackColor, Cambridgeshire.BackColor, Essex.BackColor, Suffolk.BackColor, Norfolk.BackColor, Northamptonshire.BackColor}
    Dim East_Midlands() As System.Drawing.Color = {Lincolnshire.BackColor, Nottinghamshire.BackColor, Leicestershire.BackColor, Derbyshire.BackColor}
    Dim West_Midlands() As System.Drawing.Color = {Shropshire.BackColor, Staffordshire.BackColor, Herefordshire.BackColor, Worcestershire.BackColor, Warwickshire.BackColor, Cheshire.BackColor}
    Dim North_West() As System.Drawing.Color = {Manchester.BackColor, Merseyside.BackColor, Lancashire.BackColor, Cumbria.BackColor}
    Dim Yorkshire() As System.Drawing.Color = {North_Yorkshire.BackColor, West_Yorkshire.BackColor, South_Yorkshire.BackColor, East_Yorkshire.BackColor}
    Dim North_East() As System.Drawing.Color = {Northumberland.BackColor, County_Durham.BackColor}
    quicker(South_East, 9)
    quicker(South_West, 6)
    quicker(East_Anglia, 7)
    quicker(East_Midlands, 6)
    quicker(North_West, 4)
    quicker(Yorkshire, 4)
    quicker(North_East, 2)
End Function

Public Sub quicker(A As Array, B As Integer)
     If A(0) Is the same as any value in A Then ' sort-of pseudo-code
        resupplytroops += B
    End If
End Sub

A: There's a disconnection between the question text and the sample code. I'll answer both options. This is based on the sample code, where any value in the array could match the first value:
Public Sub quicker(A() As System.Drawing.Color, B As Integer)
    ' If A(0) Is the same as any other value in A
    If A.Skip(1).Any(Function(i) i.Equals(A(0))) Then
        resupplytroops += B
    End If
End Sub

The is based on the question text, where all the values in the array must match the first value:
Public Sub quicker(A() As System.Drawing.Color, B As Integer)
    If A.All(Function(i) i.Equals(A(0))) Then
        resupplytroops += B
    End If
End Sub

A: Do a quick function to scan through the array...
Public Sub quicker(A As Array, B As Integer)
    If IsSame(A) Then ' sort-of pseudo-code
        resupplytroops += B
    End If
End Sub

Private Function IsSame(A As Array) As Boolean
    For I as Integer = 1 to A.Length - 1
       If A(I) <> A(0) Then Return False
    Next
    Return True
End Function

A: FYI Here is my LinQ vs In-Line Scan time benchmark test code and results.
Public Sub LinqVsScanTest()

    Dim A() As System.Drawing.Color
    ReDim A(1000000)
    A.Initialize()
    A(1000000) = Color.Blue
    Dim ST As Double
    Dim MinT As Double = Double.MaxValue
    Dim MaxT As Double = 0
    Dim C As Color = A(0)
    For l = 1 To 1000
        Dim T As Date = Now
        Dim B As Boolean = A.All(Function(i) i = C)
        Dim DT As Double = Delta_MilliSeconds(T, Now)
        ST += DT
        If DT > MaxT Then MaxT = DT
        If DT < MinT Then MinT = DT

    Next
    Debug.Print("LinQ took - Average :" & ST / 1000 & " Min :" & MinT & " Max :" & MaxT)

    ST = 0
    MinT = Double.MaxValue
    MaxT = 0

    For l = 1 To 1000
        Dim T As Date = Now
        Dim B As Boolean = True
        For x As Integer = 1 To A.Length - 1
            If A(x) <> A(0) Then B = False : Exit For
        Next
        Dim DT As Double = Delta_MilliSeconds(T, Now)
        ST += DT
        If DT > MaxT Then MaxT = DT
        If DT < MinT Then MinT = DT

    Next
    Debug.Print("Scan took - Average :" & ST / 1000 & " Min :" & MinT & " Max :" & MaxT)

End Sub

Results

LinQ took - Average :23.640000144951 Min :21.9999812543392 Max :36.0004836693406
Scan took - Average :7.11899993475527 Min :5.99976629018784 Max :9.00027807801962

All times in milliseconds.
Something to remember.. Coding shortcuts <> Coding Efficiency.


text:
Q: passing pointer to recursive function in C I'm just starting on the road the learning C, and ran into some difficulty:
The code listed below is giving me the following error:
Attaching to program: `/workfolder/cocoa/c_stuff/bookshelf/build/Debug/bookshelf', process 1674.
Cannot access memory at address 0xa0df194
Cannot access memory at address 0xa0df194
// code start

#define MAX_NAME_LENGTH 200
#define MAX_AUTHOR_LENGTH 200
#define MAX_DESCRIPTION_LENGTH 1000
#define MAX_PUBLISHER 200
#define MAX_ISBN 50

//structures<
typedef struct {
    char title[MAX_NAME_LENGTH];
    char author[MAX_AUTHOR_LENGTH];
    char ISBN[MAX_ISBN];
    char description[MAX_DESCRIPTION_LENGTH];
    char publisher[MAX_PUBLISHER];
} Book;

void getUserInput(Book *s[])
{
    printf("what is the book's title ?\n");
    fgets(s[book_count]->title, MAX_NAME_LENGTH, stdin);

    printf("what is the author's name?\n");
    fgets(s[book_count]->author, MAX_AUTHOR_LENGTH, stdin);

    printf("what is the ISBN?\n");
    fgets(s[book_count]->ISBN, MAX_ISBN, stdin);

    printf("write a short description\n");
    fgets(s[book_count]->description, MAX_DESCRIPTION_LENGTH, stdin);

    printf("what is the book's publisher\n");
    fgets(s[book_count]->publisher, MAX_PUBLISHER, stdin);

    printf("want to add another book ? Y\\N\n");

    book_count++;

    if(tolower(fgetc(stdin)) == 'y')
    {
        return getUserInput(s);
    }
    else
    {
        return;
    }
}

int main (int argc, const char * argv[]) {
    // insert code here...
    Book *book_shelf[100];

    if((book_shelf[0] = (Book *)malloc(sizeof(Book))) == NULL)
    {
        exit(1);
    }

    getUserInput(book_shelf);

    return 0;
}

The code compiles properly, and the function runs fine the first time (all the questions get asked and the struct receives the data); but when the user types 'y' to add another book, the mem error occurs.
Any ideas where the error is happening?
Thanks in advance!

A: Unless I'm reading something wrong, you haven't defined book_count before using it as an array subscript.

A: Within main, you allocated on the stack an array of 100 pointers to the Book Structure.  I believe it was your intent to allocate 100 structures and then pass the address to that block of structures to getUserInput
Change main to:
Book book_shelf[100];
...
getUserInput(book_shelf);
...

EDIT:  OOPS Missed the single Book malloc mentioned in the earlier post.  That ones Correct for the first book.  If you edit as above and eliminate the
if (book_shelf[0]...) check, you'll accomplish your intended results

A: You've only ever allocated memory for the first book in main - after that it tries to write to the next slot in the array, which doesn't point to an allocated block of memory, giving you a seg-fault.  You're going to have to allocate memory for each book you want to read in.
In addition, since C doesn't know how long an array is, you have to pass that information along into function calls.  (And I don't see where you're defining book_count.)
You might try something along these lines:
void getUserInput(Book *s[], int *book_count, int max_book_count)
{
   if (book_count == max_book_count) return; // If we've filled all the slots, we can't add anymore without causing trouble.
   s[book_count] = malloc(sizeof(Book));

   ..

   if(tolower(fgetc(stdin)) == 'y')
   {
       (*book_count)++;
       getUserInput(s, book_count, max_book_count);
   }
   return;
}

int main (int argc, const char * argv[]) {
    // insert code here...
    Book *book_shelf[100];

    int book_count = 0;
    getUserInput(book_shelf, &book_count, 100);
    // Make sure to free all the malloc'd data
}

Even better in this situation, would just be using a loop and skipping the whole recursion step.
int main (int argc, const char * argv[]) {
    // insert code here...
    Book *book_shelf[100];

    char response = 'y';
    int book_count = 0;
    while (book_count < 100 && response == 'y')
    {
        book_shelf = malloc(sizeof(Book));
        response = getUserInput(book_shelf[book_count++]);
    }
    // make sure to free all the allocated data!
}

char getUserInput(Book *book)
{
   // write input straight to book
   printf("what is the book's title ?\n");
   fgets(book->title, MAX_NAME_LENGTH, stdin);

   ...

   return tolower(fgetc(stdin));
}

A: *

*You allocate just space for the firstbook, not for the others (malloc in main)

*I guess there is some code missing, no declaration and initialization of book_count

*You should use loops instead of recursion

*Use not recursion but loops for this kind of repetition

A: Recursion is probably overkill for this problem where a simple do { ... } while(user keeps answering yes) would do. However the problem you having is in main with your Book *book_shelf[100]. There are several ways you could solve this problem.
First change it to an array of Book's like samills suggests:
Book book_shelf[100];

and then change your getUserInput to something like this:
getUserInput(Book *book_shelf, int offset, int length) {
    if(offset < 0 || offset >= length) {
        return;
    }

    //...

    return getUserInput(book_shelf, offset + 1, length)
}

Or you could use your existing code and change you getUserInput function to look something like this and remove the malloc from main:
getUserInput(Book *book_shelf) {
     book_shelf[book_count] = (Book*)malloc(sizeof(Book));
     // ...
}

props for correct use of the sizeof operator (I see that thing misused so often it makes my eyes bleed).

A: As in Josh's answer, by adding the following lines to your code should make it work:

book_count++;

if(tolower(fgetc(stdin)) == 'y')
{
    if((book_shelf[book_count] = (Book *)malloc(sizeof(Book))) == NULL)
    {
        printf("Cannot allocate memory for Book");
        exit(1);
    }
    return getUserInput(s);
}
else
{
    return;
}

However, I encourage you not to use the recursive function for getting input. Recursive can lead to difficulties in debugging. You may consider using normal loop instead.
Note: I'm assuming the book_count is global variable which has been initialized to 0

A: thanks a lot for the replies!
I realized that I hadn't malloc-ed enough memory to handle more then one element of the struct array (Exactly what Josh is saying). So essentially:
Book *book_shelf;
if(book_shelf = (Book*)malloc(sizeof(Book)) == NULL)//exit code
so the second time around I would hit a memory issue.
thanks again!

A: Looks like your still doing it wrong:
Book *book_shelf;
if(book_shelf = (Book*)malloc(sizeof(Book)) == NULL)//exit code
book_shelf is only the size of a pointer.  When you do the malloc you only allocate one Book at a time.  This is wrong.  You need to allocate contiguous memory for an array of Book objects all in one instanciation of an array.
Like
Book book_shelf[100];
not
Book *book_shelf[100];
or using malloc, use your pointer to point to an array instanciated using
100*malloc(sizeof(Book)).
You may get lucky that no other heap memory is allocated in between your malloc(sizeof(Book)) calls and that the memory management system  is alocating contiguous memory by default.  Also, book_shelf will only point to the last malloced Book structure, not the first one as you indicated you want in your original question.
Josh is also not allocating enough memory at one time. Use a linked list if you want to keep extending elements to the end of your book_shelf one-by-one.

A: factorial with pointer and recursion
#include<iostream.h>
#include<conio.h>

int show(int *p)

{

int f;

int x=*p;
if(*p==1)  //boundry checking for recursion

return 1;

else

f=x*show(&(--*p)); //this code is similar to f=x*show(n-1); with non-pointers

return f;

}

void main()

{

int a=6;

int b=show(&a);

cout<<b;

getch();

}


text:
Q: BigCommerce - Hide the 'add to cart' for a product based on customer group? I am building a BigCommerce site for a client who is splitting his customer groups into Wholesalers and Retail. Some of the Wholesale products can't be sold to Retail clients, but he still wants them to be visible to the Retail clients so to encourage them to move to a Wholesale account.
Can I hide the 'Add to Cart' button in BigCommerce based on the Customer Group? I'm guessing I can do this with an IF statement but I'm not sure.

A: I'd recommend using the {{#unless}} block helper instead of {{#if}}:
{{#unless customer.customer_group_name '===' 'Wholesale'}}
<style>
CSS to hide the add to cart button
</style>
{{/unless}}

The display:none on the cart button will be active unless the customer is logged into a Wholesale account (note that the customer group name will need to match the customer group name in your store exactly--it will be case sensitive). You could also use customer.customer_group_id if you know the id of the wholesale customer group.


text:
Q: Can do browser back or forward action in chrome extension Can do browser back or forward action in chrome extension? Is there any related api?

A: You can inject Content Scripts and execute window.history methods for browser back and forward actions.


text:
Q: Stored procedure doesnt return any value I got simple problem but I got no idea about where is problem :/ So in my GridView I am using ObjectDataSource with custom paging like in this tutorial http://www.codedigest.com/Articles/ASPNET/180_Custom_GridView_Paging_with_ObjectDataSource_Control_with_ASPNet_20.aspx
Here is my aspx markup:
<asp:ObjectDataSource ID="ObjectDataSource2"
        runat="server"
        onselecting="ObjectDataSource2_Selecting"
        EnablePaging="true"
        SelectCountMethod="GetItemsCount"
        SelectMethod="BindItems"
        StartRowIndexParameterName="startRowIndex"
        MaximumRowsParameterName="maximumRows"
        TypeName="eSova.Utilities.RecordUtilities"
         >

And method which calling:
  public static DataTable BindItems(int category,int search,int startRowIndex,int maximumRows)
    {
        DataTable table = new DataTable();
        using (SqlConnection connection = new SqlConnection())
        {
            ConnectionUtilities.OpenConnection(connection);
            SqlTransaction transaction = connection.BeginTransaction();
            try
            {
                SqlCommand command = new SqlCommand("GetItems",connection,transaction);
                command.CommandType = CommandType.StoredProcedure;
                command.Parameters.Add("@RowIndex", SqlDbType.Int, 4).Value = startRowIndex;
                command.Parameters.Add("@MaxRows", SqlDbType.Int, 4).Value = maximumRows;
                SqlDataAdapter adapter = new SqlDataAdapter(command);
                adapter.Fill(table);
                transaction.Commit();
            }
            catch
            {
                transaction.Rollback();
            }
        }
        return table;
    }

My stored procedure works just fine and return in all items from table.
But when I analyze the code, I got breakpoint on return and table variable is without records. I don't know where is problem.
UPDATE:
create proc [dbo].[GetItems](@RowIndex int,@MaxRows int)
as
    declare @StartRows int
    declare @EndRow int

    set @StartRows=(@RowIndex+1)
    set @EndRow=(@StartRows+@MaxRows)

    select *
    from ( select  id, name, filepath, descript, itemlanguage,
           filetypeid, ROW_NUMBER() over (ORDER by id)as row  FROM Items)as NumberesItems
    where row between @StartRows and @EndRow

A: Your connectionstring is empty.


text:
Q: cannot find module in server.js I get the error "Error: Cannot find module './todo.model'"
schema is in the same folder
here is the folder content :
- backend
  - data:db
  - node_modules
  - todo.model.js
  - package.json
  - server.js
this is the server.js
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cors = require('cors');
const mongoose = require('mongoose');
const todoRoutes = express.Router();
const PORT = 4000;
**var Todo = require('./todo.model');**
app.use(cors());
app.use(bodyParser.json());
mongoose.connect('mongodb://127.0.0.1:27017/todos', { useNewUrlParser: true });
const connection = mongoose.connection;
connection.once('open', function() {
    console.log("MongoDB database connection established successfully");
})

this is the schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
let Todo = new Schema({
    todo_description: {
        type: String
    },
    todo_responsible: {
        type: String
    },
    todo_priority: {
        type: String
    },
    todo_completed: {
        type: Boolean
    }
});
module.exports = mongoose.model('Todo', Todo);

A: I'm assuming require is getting confused about the file extension, thinking the file is actually a .model extension.
Try being more explicit and include .js
require('./todo.model.js');


text:
Q: Execute Update from table info Good Day! I have this Sample Output:

The left table is my item in my database and the right table would be a table for viewing what items are to be purchased. Clicking Bill out should update the database quantity based on all inputs on the view table (right table).
Here is my code and I'm not sure what to put on my prepared statement for it to get all inputs from the view
        String sql="update medinfo set quantity=quantity-? where medID=?";
        PreparedStatement ps = connMed.prepareStatement(sql);

        ps.setInt(1, ));
        ps.setString(2, );
        ps.executeUpdate();

Thanks!

A: Do something likewise,
String sql="update medinfo set quantity=? where medID=?";
PreparedStatement ps = connMed.prepareStatement(sql);

Integer updateNetQuantity = Integer.parseInt(get-Quantity-on-Hand)) - Integer.parseInt(get-Quantity-to-purchased)); // here , in your case it's 995-3 = 992

Integer medID= getCurrentItem's MedID; // here , in your case it will be 22/21/20...etc

ps.setInt(1, updateNetQuantity );
ps.setString(2, medID);
ps.executeUpdate();


text:
Q: How to modify default options in Salt Minion config file from Master I want to set "grains_cache" variable to "True" from Salt Master on all Minions. This variable is from default options that exist in minion config file and cannot be overridden by pillar data. So how can I set variables (for example "grains_cache", "grains_cache_expiration" or "log_file") from Master?

A: this should be an easy one. Manage the minion configuration file using the file.managed function.
A simple sls should help here:
minion_configuration:
  file.managed:
    - name: /etc/salt/minion
    - contents: |
        grains_cache: true
        backup_mode: minion

salt-minion-restart:
  cmd.wait:
    - name: salt-call --local service.restart salt-minion
    - bg: True
    - order: last
    - watch:
      - file: salt-minion-config

In this example, saltstack ensures that the two lines beneath - contents: | are present within the minions configuration file.
The second state: salt-minion-restart will restart the salt-minion if the minion configuration file is being touched (managed by the first state).
So in short terms, this state adds your variables to the minion's configuration and restarts the minion afterwards.
This formula is os-independent.
The last thing left to do is, to target all of your minions with this.
If you want to know more about the cmd.wait and the shown example, please refer to this documentation.
I hope i could help.


text:
Q: How to prove that this determinant is zero by MMA? Say,
$\boldsymbol{A}^2=\boldsymbol{I}$,
$\boldsymbol{B}^2=\boldsymbol{I}$,
$|\boldsymbol{A}|+|\boldsymbol{B}|=0$,
to prove,
$|\boldsymbol{A}+\boldsymbol{B}|=0,and  |\boldsymbol{I}+\boldsymbol{A B}|=0$
here is my code,
Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
detmApdetmB = Det[mA] + Det[mB];
detmApmB = Det[mA + mB];
detmIpAB = Det[mI3 + mA . mB];
listmA = Flatten[mA];
listmB = Flatten[mB];
listmAmB = Flatten[{listmA, listmB}];
statement = detmApmB == 0;

Assuming[MatrixPower[mA, 2] == mI3 && MatrixPower[mB, 2] == mI3 &&
  detmApdetmB == 0,
 Refine[Reduce[$Assumptions && statement, listmAmB, Reals]]]

$Aborted

Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
detmApdetmB = Det[mA] + Det[mB];
detmApmB = Det[mA + mB];
detmIpAB = Det[mI3 + mA . mB];
listmA = Flatten[mA];
listmB = Flatten[mB];
listmAmB = Flatten[{listmA, listmB}];
statement = detmApmB == 0;

Assuming[MatrixPower[mA, 2] == mI3 && MatrixPower[mB, 2] == mI3 &&
  detmIpAB == 0,
 Refine[Reduce[$Assumptions && statement, listmAmB, Reals]]]

$Aborted

EDIT
Thanks for @ user64494's answer. The code runs very fast. I tried to prove my question with FindInstance before, but the code has been running without results. After reading the answer to @ user64494, I checked my code again and found a problem. In my code, whether to restrict the Reals field in FindInstance has a great impact on the running results. The @ user64494 code has no this effect. Does anyone know why?
my code:
Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
detmApdetmB = Det[mA] + Det[mB];
detmApmB = Det[mA + mB];
listmA = Flatten[mA];
listmB = Flatten[mB];
listmAmB = Flatten[{listmA, listmB}];
FindInstance[
 detmApmB != 0 && MatrixPower[mA, 2] == mI3 &&
  MatrixPower[mB, 2] == mI3 && detmApdetmB == 0, listmAmB, Reals]

$Aborted

Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
detmApdetmB = Det[mA] + Det[mB];
detmApmB = Det[mA + mB];
listmA = Flatten[mA];
listmB = Flatten[mB];
listmAmB = Flatten[{listmA, listmB}];
FindInstance[
 detmApmB != 0 && MatrixPower[mA, 2] == mI3 &&
  MatrixPower[mB, 2] == mI3 && detmApdetmB == 0, listmAmB]

{}

@user64494's code:
Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
FindInstance[
 Det[mA + mB] != 0 && mA^2 == mI3 && mB^2 == mI3 &&
  Det[mA] + Det[mB] == 0, Flatten[{Flatten[mA], Flatten[mB]}]]

{}

Clear["Global`*"];
mA = Array[a, {3, 3}];
mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
FindInstance[
 Det[mA + mB] != 0 && mA^2 == mI3 && mB^2 == mI3 &&
  Det[mA] + Det[mB] == 0, Flatten[{Flatten[mA], Flatten[mB]}], Reals]

{}

A: Your claim is not true. Here is a simple counterexample.
a = {{1, 0}, {0, 1}};
b = {{-1, 0}, {0, 1}};
b.b

{{1, 0}, {0, 1}}

Det[a] + Det[b]

0

a+b

{{0, 0}, {0, 2}}

Addition. If you mean $|mA+mB|=0$ as your claim, then the following does the job in three dimensions.
Clear["Global`*"];mA = Array[a, {3, 3}];mB = Array[b, {3, 3}];
mI3 = IdentityMatrix[3];
FindInstance[Det[mA + mB] != 0 && mA^2 == mI3 && mB^2 == mI3 && Det[mA] +
Det[mB] == 0,  Flatten[{Table[a[i, j], {i, 1, 3}, {j, 1, 3}],
Table[b[i, j], {i, 1, 3}, {j, 1, 3}]}]]

{}


text:
Q: filter size in convolution layers what happens if I add another convolution layer after convolution layer with the same filter size
for example, in a network of around 20 layers, I have to choose different filter sizes among convolution layers. so what will be the impact if  I do something like this

inner = MaxPooling2D(pool_size=(1,2),strides=2,padding='valid', name ='max3')(inner)

inner = Conv2D(64, (3,3),strides=1,padding= 'same', name='conv6', kernel_initializer='he_normal')(inner)

inner = Conv2D(64, (3,3),strides=1,padding= 'same', name='conv7', kernel_initializer='he_normal')(inner)

inner = Conv2D(64, (3,3),strides=1,padding= 'same', name='conv8', kernel_initializer='he_normal')(inner)
inner = BatchNormalization()(inner)

A: Trained with both scenarios where with same filters and different filters
(1) The observation is when trained with more weights(means more filters with increase in number) the test accuracy is more
(2) when trained with same filters the accuracy is not as good as earlier case.
Ran the below code on CIFAR10 dataset.
   model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
   model.add(layers.MaxPooling2D((2, 2)))
   model.add(layers.Conv2D(64, (3, 3), activation='relu'))
   model.add(layers.MaxPooling2D((2, 2)))
   model.add(layers.Conv2D(64, (3, 3), activation='relu'))

Total params: 56,320
Trainable params: 56,320
Non-trainable params: 0
in this case loss: 0.9110 - accuracy: 0.6937
   model = models.Sequential()
   model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(32, 32, 3)))
   model.add(layers.MaxPooling2D((2, 2)))
   model.add(layers.Conv2D(32, (3, 3), activation='relu'))
   model.add(layers.MaxPooling2D((2, 2)))
   model.add(layers.Conv2D(32, (3, 3), activation='relu'))

Total params: 19,392
Trainable params: 19,392
Non-trainable params: 0
in this case: loss: 0.9760  and accuracy: 0.6695


text:
Q: How to get the value of selected select using localStorage I'm trying to get the value of selected select using localStorage.getItem() but it gives me an error.

Here is my select:

                Work Area
              <select class="ui fluid dropdown work_area" id="work_area" name="work_area">
                  <option selected value="">Select Work Area.</option>
                  <?php selectWorkArea(); ?>
              </select>

Here is my PHP function

 function selectWorkArea(){
    $conn = New Connection;
    $sql = "SELECT DISTINCT work_area FROM machine ORDER BY work_area ASC";
    $qry = $conn->select($sql,NULL,'0129180857');
    while($row= $qry->fetch(PDO::FETCH_OBJ)){
        $work_area = $row->work_area;
        echo "<option data-value='$work_area' >$work_area</option>";
    }

 }

here is my Javascript

 var select = document.querySelector(".work_area");
      var selectOption = select.options[select.selectedIndex];
      var lastSelected = localStorage.getItem('select');
      if(lastSelected) {
          select.value = lastSelected;
      }
      select.onchange = function () {
        lastSelected = select.options[select.selectedIndex].value;
        console.log(lastSelected);
        localStorage.setItem('workarea', lastSelected);

     }

And i got this error:
  Error image click here
But when i tried to change my select into this  it works totally fine

                Work Area
                <select class="ui fluid dropdown work_area" id="work_area" name="work_area">
                  <option selected value="">Select Work Area.</option>
                  <option  data-value="1">1</option>
                  <option data-value="2">2</option>
                </select>

click here to see the image

A: I solved this problem by removing the data in the  data-value attribute. And after, i tried to refresh the page and the value of select is removed. that is not good. the solution is modify the javascript, here is the modification:

Javascript code:

      $('#work_area').val(localStorage.workarea);
      localStorage.setItem('workarea','');
      var select = document.querySelector(".work_area");
      var selectOption = select.options[select.selectedIndex];
      var lastSelected = localStorage.getItem('select');
      if(lastSelected) {
          select.value = lastSelected;
      }
      select.onchange = function () {
        lastSelected = select.options[select.selectedIndex].value;
        localStorage.setItem('workarea', lastSelected);

      }

html code:

            Work Area
            <select class="ui fluid dropdown work_area" id="work_area" name="work_area">
              <option selected value="">Select Work Area.</option>
               <?php selectWorkArea(); ?>
             </select>

PHP function code:

 function selectWorkArea(){
    $conn = New Connection;
    $sql = "SELECT DISTINCT work_area FROM machine ORDER BY work_area ASC";
    $qry = $conn->select($sql,NULL,'0129180857');
    while($row= $qry->fetch(PDO::FETCH_OBJ)){
        $work_area = $row->work_area;
        echo "<option value='$work_area' >$work_area</option>";
    }

}

A: Check for null before use.
if (localStorage.getItem("select") === null) {
  var lastSelected = localStorage.getItem('select');
  select.value = lastSelected;
}


text:
Q: Check that combinations not in list Simplified – have a dict:
flags = { 'a': 0, 'b': 1, 'c': 1, 'd': 0, 'e': 1, 'f': 1 }

Now there are certain combinations that are not allowed:
no_combo = [
    ['a', 'c'],
    ['b', 'd', 'e']
]

How best to validate I do not have combinations in flags that are not allowed according to no_combo?
From example above we have a conflict because both b and e are set to 1.
set_flags = [k for k in flags if flags[k]]

gives:
['b', 'c', 'e', 'f']

which is in conflict with restriction of no combinations of no_combo[1]:
['b', 'd', 'e']

Now to cross check with no_combo?
I have this:
for combo in no_combo:
    if len([f for f in combo if f in set_flags]) > 1:
        print('fail on', combo)

But wondering if there is a better way to solve it?
Is there for example some similar method to all() and any() for this purpose?

A: You could use sum:
flags = {'a': 0, 'b': 1, 'c': 1, 'd': 0, 'e': 1, 'f': 1}

no_combo = [
    ['a', 'c'],
    ['b', 'd', 'e']
]

for combo in no_combo:
    if sum(flags.get(c, 0) for c in combo) > 1:
        print('fail on', combo)

Output
fail on ['b', 'd', 'e']

This saves you the list creation (the one you use in the call to len). Note that this assumes the values of the flags are 0 or 1.
You could also use a while loop and break it as soon as the sum reaches 2. For example:
for combo in no_combo:
    total = 0
    for c in combo:
        total += flags.get(c, 0)
        if total > 1:
            print('fail on', combo)
            break

It is a little bit cumbersome but avoids iterating over the whole list, so it saves you some time.


text:
Q: Is the ST_ prefix appropriate for functions not included in SQL/MM Part 3? I was reading a thread on the geospatial extension for Presto in this Github issue, where a function, line_locate_point, was introduced. It was based off PostGIS's ST_LineLocatePoint function, which returns a float representing the fraction along a line of the closest point on that line to a given location.
The question was brought up why it was named line_locate_point and not ST_LineLocatePoint like the PostGIS version. The response was that this function does not exist in the SQL/MM Part 3 standard, and so it should not start with ST_.
Reading quickly through the standard, I don't see any comments on how to handle cases where you introduce a spatial function to your database that is not in the standard. Is the spirit of the ST_ prefix to differentiate spatial functions from non-spatial functions (as seems to be the case with PostGIS), or is it to indicate that the function complies with an equivalent function in SQL/MM Part 3?
Looking at the current state of Presto's API, I have to say that the latter approach looks less clean and introduces some confusion as to why the names aren't consistent, but perhaps this could be addressed by a simple note at the top.
My question, then, is whether there is some aspect of the standard that I'm overlooking that allows for extensions to it beyond the defined set of spatial objects, or alternatively, if this is expressly forbidden by some written or unwritten rule of following standards.

A: The OpenSpatial spec says numerous things about this,

When integrating this SQL with that of SQL/MM, the type-name prefix "ST_" should be used as appropriate.

And,

Class names in SQL/MM carry a "ST_" prefix. This is optional and implementations may chose to drop this prefix as has been done in various places in this standard.

From this Committee Draft ISO/IEC CD13249-3 ed 5

This part of ISO/IEC 13249 uses the prefix ST_ for user-defined type, attribute, SQL-invoked routinetable and view names. This part of ISO/IEC 13249 uses the prefix 'ST_Private' for names of certain attributes.  The use of 'ST_Private' indicates that the attribute is not for public use.

So here is what we have,

*

*SQL/MM suggests using the prefix.

*SQL/MM says the prefix is however optional.

*ISO uses the ST_ prefix too..

I would say this,

*

*The use of ST_ should be thought of as non-reserved keywords to end users. There is really no reason to make end-user functions with this prefix. You're better off just using STx_. We know of at least two bodies that have published with this prefix suggestions (OpenSpatial) SQL/MM and ISO. In addition, many RDBMS's pollute symbols with that prefix.
There may be more to the history, but I can't find any more contemporary information on this.


text:
Q: Why FireFox can't play long videos (.mp4 2GB+) on HTML5 I was testing html5 video on firefox, I tried to play large (.mp4) 720p HD file. But Firefox crashes and unable to play video.
Same HTML5 video works perfect on Google Chrome,
Have a look here: http://goo.gl/FiAE6j


text:
Q: Javascript - how to create an array of objects where the object's keys all have the same value I created a descending array of integers from the current year to 1930 using moment:
options = Array(moment().year() - 1929).fill().map((_, index) => moment().year() - index)

I'm trying to convert options into an array of objects such that the resulting array is something like this:
[{value: '2018', label: '2018'}, {value: '2017', label: '2017'}, ..., {value: '2', label: '2'}, {value: '1', label: '1'}]

A: Just .map each item to an object instead of to a single number:

const options = Array(moment().year() - 1929)
  .fill()
  .map((_, index) => {
    const value = moment().year() - index;
    return { value, label: value };
  });
console.log(options);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>

A: What What you want is another map. map will always take an array of a given length in an order and produce another array of the same length in the same order (in JS). So if we take your code and then add on:
options.map(o => o.toString).map(o => ({ value: o, label: o }))
you'd get get your objects.


text:
Q: Awk compare 2 files and match 2 columns, get % difference between column 3s I have 2 files, with the formatting below.  I am trying to compare lines where columns 1 and 2 match and then get the difference in the 2 #'s that are in column 3.
if file 2 column 3 is greater than file1 column 3, i would like a + at the end of the row
if file2 column is less than file 1 column 3, i would like a - at the end of the row
if either file column 3 is 0 i would like a * at the end of the row.

I only want to print lines where the difference between the 2 columns is > 15%
file1
abc,1,472
abc,2,536
abc,3,652
abc,4,512
abc,5,474
abc,6,266
abc,7,520
def,1,954
def,9,538
def,10,136
def,11,341
def,12,183
def,13,1209
def,14,365
def,15,536
def,16,979
def,17,0
xyz,1,547
xyz,19,0
xyz,20,0
xyz,21,0
xyz,22,0
xyz,23,0
xyz,24,0

File 2
abc,1,456
abc,2,533
abc,3,643
abc,4,444
abc,5,124
abc,6,255
abc,7,520
def,1,954
def,9,538
def,10,435
def,11,341
def,12,155
def,13,1209
def,14,365
def,15,536
def,16,979
def,17,0
xyz,1,547
xyz,19,124
xyz,20,0
xyz,21,0
xyz,22,0
xyz,23,0
xyz,24,0

expected output
abc,5,474,124,74%,-     // (474-124)/474 = 74%
def,10,136,435,31%,+.   // (435-136)/474 = 69%
xyz,19,0,124,100%,*.    // either file has 0 , print 100% and *

I have tried multiple iterations of this but cannot seem to get the formatting to work.
  awk -F, 'FNR==NR{a[$1,$2]; next ;b[$1,$2,$3]; next} $1,$2 in a {if ($3>b[$3]) {Q=((b[$3]/$3) *100)) {print Q,$0 }} else if (b[$3]>$3) {Q=(($3/b[$3]) *100)){print Q,$0 }}' file1 file2

i get this error
^ unexpected newline or end of string
also tried variations on this line but i cannot figure out the division by 0 error
awk -F, 'FNR==NR{a[$1,$2]; next ;b[$1,$2,$3]; next} $1,$2 in a {if ((Q=(b[$3]/$3) > 15) || (Q=($3/b[$3])) > 15 ){print Q,$0}}' file1 file2
awk: cmd. line:1: (FILENAME=file2 FNR=1) fatal: division by zero attempted

A: you need to handle if the denominator is zero in the base case, since you cannot find the relative change in that case, you need to report absolute change.
$ awk -F, -v OFS=, '{k=$1 FS $2}
            FNR==NR {a[k]=$3; next}
            k in a  {if(a[k]) q=$3/a[k]-1;
                     else if($3) zero=1
                     else q=0
                     plus=q>0.15
                     minus=q<-0.15
                     q=q<0?-q:q;
                     if(zero) plus=minus=0
                     if(plus || minus || zero)
                       print k,a[k],$3,(zero?100:int(100*q))"%",(plus?"+":minus?"-":"*")
                     q=zero=0}' file1 file2

abc,5,474,124,73%,-
def,10,136,435,219%,+
def,12,183,155,15%,-
xyz,19,0,124,100%,*

you can put this in a diff.awk file and run with awk -f diff.awk file1 file2
the file contents should be
BEGIN{FS=OFS=","}
{k=$1 FS $2}
 ...  the code in between
   q=zero=0}

note that text body is without the single quotes.  You can make it executable with the right shebang but I think this will be simpler.


text:
Q: check the condition if the values are less then or equal or greater than MongoDB check the conditions

*

*if the value is greater equal 1000.

*if the value is less than equal 2000.
from the parameters, the user will select either 1 or 2. User get the output in the same structure but only those documents that fulfill the condition in MongoDB

{
    "data": [
        {
            "value": 1000
        },
        {
            "value": 3000
        },
        {
            "value": 1500
        }
    ]
}

A: This query answers in the question :

*

*user enters 1 or 2 saved in a application variable lets say var=parameter

*if he entered 1 => i want the documents that data.value>=1000

*if he entered 2 => i want the documents that data.value<=1000

*also assumes that data(in your sample data) is an array not a collection.
Query

*

*make {"eq" : [1 ,1]} to {"eq" : [parameter ,1]} where parameter is your variable that has the value the user selected

*works using a condition, if the user entered 1, first comparison is made or if user entered 2 , second comparison is made

*the comparison is done with the aggregate operators, the query operators when you compare an array(the auto take the min or max), but aggregate ones doesn't do auto, so its done here with the $max and $min operators. Istead of searching for the number we find the max/min and we compare (like query operators auto-do)

Test code here
db.collection.aggregate([
  {
    "$match": {
      "$expr": {
        "$cond": [
          {
            "$eq": [
              1,
              1
            ]
          },
          {
            "$gte": [
              {
                "$max": "$data.value"
              },
              1000
            ]
          },
          {
            "$lte": [
              {
                "$min": "$data.value"
              },
              2000
            ]
          }
        ]
      }
    }
  }
])


text:
Q: json.data.totalItems == 0 not working Using the YouTube API. Trying to get an alert("No search results") when json.data.totalItems == 0 but it just doesn't happend, nothing happens at all... when json.data.totalItems > 0 it all works fine.
Any idea to why this is?
i.e.
json.data.totalItems == 0 :
https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&max-results=20&format=5&orderby=relevance&uploader=partner&q=oierjt
code:
           var url = "https://gdata.youtube.com/feeds/api/videos?v=2&alt=jsonc&max-             results=20&format=5&orderby=rating&uploader=partner&q=" + searchinput ;
        var request = $.ajax({

            url: url,

            type: "GET",

            timeout: 8000,

            dataType: "json",

            error: function(xhr, ajaxOptions, thrownError) {

                alert("Something went wrong");

            },

            success: function(json) {

                var numberOfItems = json.data.items.length;
        var totalItemsAmount = json.data.totalItems;

        if (totalItemsAmount == 0) {
                    alert("No videos found");
                }
                else {

                    for (var i = 0; i < numberOfItems; i++) {
                            alert("videos found")
                        }
                 }

A: Check the results -- if totalItems is zero, then items is not present at all.  You will get an exception at the line json.data.items.length.  You need to remove that line, or put it inside the else block:
success: function(json) {
    var totalItemsAmount = json.data.totalItems;
    if (totalItemsAmount == 0) {
        alert("No videos found");
    } else {
        var numberOfItems = json.data.items.length;


text:
Q: Rails: Controller-specific menu in layout How do I add a controller-specific menu (or div) inside a general application layout in Rails?

A: If I have correctly understood the question you needs to special place in layout.
Use <%= yield(:) %> in desired position in layout, for example:
    # application.html.erb
    <%= yield(:right_menu) %>

    # show.html.erb
    <% content_for :right_menu do %>
    <!-- Everything in this block will be shown at the position yield(:right_menu) in layout -->
    <% end %>

See more in
http://api.rubyonrails.org/classes/ActionView/Helpers/CaptureHelper.html#method-i-content_for

A: method 1: set a variable in that controller
class SomeController
  before_filter :set_to_use_menu

  private

  def set_to_use_menu
    @use_menu = true
  end
end

method 2: determine the controller's name in the layout
<%- if controller_name == "your_controller_name" %>
  <%= render :partial => "the_menu" %>
<%- end %>

A: Other than the content_for approach (which may or may not be what you want), there are a few additional options.
You could use a before_filter in your controller to set a variable:
# Controller
class TestController < ApplicationController
  before_filter :set_variable

  def set_variable
    @my_variable = true
  end
end

# Layout
if @my_variable
  # Do the controller-specific stuff you want to do
end

Or, you could leave the controller alone and just check for the controller name in your layout:
# Layout
if controller.controller_name == 'test'
  # Do the controller-specific stuff you want to do
end

A: Just call an appropriately named partial in your layout
<%= render :partial => "#{controller_name}_menu" %>

If your controller is WidgetsController, then this will use the partial _widgets_menu.html.erb under ./app/views/layouts


text:
Q: How to make css not apply to certain attributes? I am working on a plugin for a wordpress page and in the theme it's going in, there is a style.css for that theme. In that style.css there are CSS attributes that apply to all img and p tags and that is messing up the appearance of my plugin. How can I make it so my plugin, which has its own stylesheet, ignore the style of the theme's css?

A: Include your stylesheet after the style.css
So:
<link rel="stylesheet" type="text/css" href="/path/to/style.css">
<link rel="stylesheet" type="text/css" href="/path/to/yourStylesheet.css">

If this still is not working use !important, but try to avoid this.
!important is placed after the style rule, like so:
p {
    color: red !important;
}

You can also use more specific styles like @SarahBourt said.
#news-item > p {
    color: red;
}

A: Craete a new CSS file and include your stylesheet after the default bootstrap css file, your styles will override the bootstrap styles
If still you are getting some problems you can also use !important next to that style
!important will ensure that your style will be given first preference
Ex:
p{
display:inline-block !important;
}

A: You can place styles in your stylesheet specifically to override the theme's styles.
Assuming your stylesheet is loading after the default theme stylesheet, then you can do the following.
In your web inspector, find the offending style in the theme's stylesheet. Copy it into your stylesheet, and replace every value with 'initial' to reset it to the defaults, or with your custom styles if that's more appropriate.
If your stylesheet is loading before the theme's styles, then you can still override the theme styles, even if they include !important. To override !important, create a more specific selector than the theme uses (Read about CSS specificity to figure out the best way of doing this), and add !important only to those which have !important in the theme style. If the style you're overriding doesn't use !important, just use the more specific style, as including too many !important tags can make it harder for you or someone else to modify your code later, as you're experiencing now.
In addition, you want to be sure that your overrides only get applied to your plugin, and not the rest of the site. So, wrap the plugin with a div or other element if it isn't already, and give the wrapper a unique class or id, e.g. class="my-plugin". Preface all of your overrides with this class to avoid breaking other areas of the site.
HTML:
<div class="my-plugin>
    <!--plugin HTML-->
</div>

CSS:
.my-plugin img {
   //override styles
}
.my-plugin p {
   //override styles
}

Overriding original styling like this can get messy, but sometimes it's the only way to get things done when you don't have access to the other .css files. Just do the minimum necessary to make your styles more specific and you should be okay.


text:
Q: How can I use the data in private area when I click the button I am trying to get bytes from a private class and using it in btn.click.What should I do for doing this?
Here is the sample code:

private void CameraConnnection_DataReceived(object sender, BReceivedData x)
        {
            byte[] data = e.ReceivedData;
        }

        private void BtnGetImage_Click(object sender, EventArgs e)
        {
            unsafe
            {
               byte a[]= e.ReceivedData;// This is not working how can I get received data from there.There is a event and it's triggering from there.
            }

A: Since EventArgs class doesn't have ReceivedData field or property, the code below doesn't compile:
private void BtnGetImage_Click(object sender, EventArgs e)
{
  ...
  // Compile time error: ReceivedData doesn't exist
  byte a[] = e.ReceivedData;

You can obtain and save ReceivedData on DataReceived event but use it on Click:
private byte[] receivedData = new byte[0];

private void CameraConnnection_DataReceived(object sender, BReceivedData x)
{
    // ?? new byte[0] - to be on the safe side and never have null
    receivedData = e.ReceivedData ?? new byte[0];
}

private void BtnGetImage_Click(object sender, EventArgs e) {
  byte[] a = receivedData;

  ...
}


text:
Q: Why I get error when I try to install pyaudio? The first error whas Microsoft Visual C++ 14.0 is not installed and I fixed it... Now when I try to install pyaudio I get another error. (I've Windows 10)
I've installed all visual studio's packages... I tried also to use wheel installation but it says that wheel is not supported on this platform
Collecting pyaudio
  Using cached https://files.pythonhosted.org/packages/ab/42/b4f04721c5c5bfc196ce156b3c768998ef8c0ae3654ed29ea5020c749a6b/PyAudio-0.2.11.tar.gz
Installing collected packages: pyaudio
  Running setup.py install for pyaudio ... error
    Complete output from command C:\Users\Hp\PycharmProjects\Jarvis\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\Hp\\AppData\\Local\\Temp\\pip-install-r8s
c6ih0\\pyaudio\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record C:\Users\Hp\AppDa
ta\Local\Temp\pip-record-zm1aoh_y\install-record.txt --single-version-externally-managed --compile --install-headers C:\Users\Hp\PycharmProjects\Jarvis\venv\include\site\python3.7\pyaudio:
    running install
    running build
    running build_py
    creating build
    creating build\lib.win-amd64-3.7
    copying src\pyaudio.py -> build\lib.win-amd64-3.7
    running build_ext
    building '_portaudio' extension
    creating build\temp.win-amd64-3.7
    creating build\temp.win-amd64-3.7\Release
    creating build\temp.win-amd64-3.7\Release\src
    C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.22.27905\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -DMS_WIN64=1 -IC:\Users\Hp\PycharmPro
jects\Jarvis\venv\include -IC:\Users\Hp\AppData\Local\Programs\Python\Python37\include -IC:\Users\Hp\AppData\Local\Programs\Python\Python37\include "-IC:\Program Files (x86)\Microsoft Visua
l Studio\2019\BuildTools\VC\Tools\MSVC\14.22.27905\ATLMFC\include" "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.22.27905\include" "-IC:\Program Files (
x86)\Windows Kits\NETFXSDK\4.7.2\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC
:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.1
8362.0\cppwinrt" /Tcsrc/_portaudiomodule.c /Fobuild\temp.win-amd64-3.7\Release\src/_portaudiomodule.obj
    _portaudiomodule.c
    C:\Users\Hp\AppData\Local\Programs\Python\Python37\include\pyconfig.h(117): warning C4005: 'MS_WIN64': ridefinizione macro
    src/_portaudiomodule.c: note: vedere la precedente definizione di 'MS_WIN64'
    src/_portaudiomodule.c(29): fatal error C1083: Non Š possibile aprire il file inclusione: 'portaudio.h': No such file or directory
    error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.22.27905\\bin\\HostX86\\x64\\cl.exe' failed with exit status 2

A: From the official docs:

To build PyAudio from source, you will also need to build PortAudio v19

That being said and seeing your error message: 'portaudio.h': No such file or directory error, I think you  have not installed this dependency.
The key part here is that PyAudio only provides python bindings to the Portaudio library, but does not include the library itself, unless you install using a .whl, but these are not available for python 3.7. Again, from the docs (emphasis mine):

pip will fetch and install PyAudio wheels (prepackaged binaries). Currently, there are wheels compatible with the official distributions of Python 2.7, 3.4, 3.5, and 3.6. For those versions, both 32-bit and 64-bit wheels are available.

So your solution is to either download and install the missing library, or move to a python version for which there are pre built wheels that include Portaudio


text:
Q: How to convert a string into timestamp, with moment js? I have the string "18/04/19 5:17 PM EDT" which represents a date.
I'm using moment and the add-on moment-timezone and I need to convert this sting into a timestamp.
I'm trying something as:
var date = moment("18/04/19 5:17 PM EDT").format('DD/MM/YY h:m a z');
alert(date);

But this is not working and saying "invalid date".

A: Please note that moment(String):

When creating a moment from a string, we first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found.

Warning: Browser support for parsing strings is inconsistent. Because there is no specification on which formats should be supported, what works in some browsers will not work in other browsers.

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.
so you are getting Invalid Date because your input is neither in ISO 8601 nor RFC 2822 recognized format, then you have to provide format parameter when parsing it.
moment(String, String) does not accept 'z' token, so you have to use moment-timezone to parse your input using zone, see Parsing in Zone docs:

The moment.tz constructor takes all the same arguments as the moment constructor, but uses the last argument as a time zone identifier.

You can use format() and other methods listed in the Displaying section of the docs (e.g. valueOf()) to display the value of a moment object.
Here a live sample:

var date = moment.tz("18/04/19 5:17 PM EDT", 'DD/MM/YY h:m A', 'America/New_York');
console.log(date.valueOf()); // 1555622220000
console.log(date.format());  // 2019-04-18T17:17:00-04:00
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>

As a side note, remeber that time zone abbreviations are ambiguous, see here for additional info.


text:
Q: OpenSuse: Cannot start Omnisharp because Mono version >=3.10.0 is required Im running Visual Studio Code on OpenSuse 13.2 and get "Cannot start Omnisharp because Mono version >=3.10.0 is required". I have reinstalled mono-complete and mono-devel.

A: OpenSuse 13.2 repositories contains mono version 3.8.0. To install newer version, firstly uninstall current version of mono and then visit this page and click "1-click Install mono-complete" to install latest version of mono (currently version 4.0.2)


text:
Q: Hearing vs listening to someone I've heard phrases similar to

It was if they wear hearing me but they weren't listening

My first request is what are the common forms of this statement as I've heard some that seem more logical than others.
What precisely does the phrase mean? I believe taken literally it's an oxymoron as most dictionaries define hearing and listening very similarly. From the definitions I've red, listening tends to imply that the sound being heard carries meaning (but don't all sounds?). For example you could say "listen to his instructions to know what to do" but you could also listen to something non-verbal to gain information, for example if you heard a tree come falling down, you know that a tree fell down.
For the over all meaning of the phrase, I can think of a few different meanings and was wondering if any are right or wrong:

*

*The person was perceiving the message but knowingly chose not to comply. e.g. Joe heard Bob tell him to come early but he chose to disregard the request.

*The person's capacity to hear is working well but cognitively he is disengaged. e.g. Joe stood in front of Bob while Bob was talking, but Joe's mind was elsewhere.

*The person is incapable of interpreting the message. e.g. Joe doesn't speak the language Bob was speaking to him in.
This is what I don't get, in example 3. most people would say Joe was listening to Bob but couldn't understand him. So this seems to show that the phrase in question missuses the word "listen".
TL;DR
In a sense I'm asking what the difference is between "hearing" and "listening" and if the quoted phrase is an idiom in the sense it does not logically apply the rule.

A: Hearing is recognizing the presence of sound. You may or may not pay attention.
Listening is the recognition of the sound or trying to process the sound and making an attempt to understand it.
In simple terms, when you look at the license/number plate of a vehicle, you visually "hear" the number plate. You may know there are numbers on it, you may recognize the colors, but you do not actually try to process the numbers and letters.
When you "listen" to a number you know the letters and numbers in there, you know the color, you may even process the number to mean something that you can connect or relate it to.
In the third example, Joe was paying attention to Bob, but he was simply unable to understand. Hence Listen.
So hear is when you involuntarily sense the sound, Listen is when you sense the sound and pay attention to it.
Hope this answered your question. Sorry if my analogy was misleading or did not make sense. :)

A: To hear ("to perceive with the ear the sound made by (someone or something)" - OED) doesn't necessarily mean compliance or comprehension. On the other hand, to listen ("to give one's attention to a sound") does. I believe your 1st and 2nd examples are correct; the receiver's ears get the sound waves, but the receiver ignores the message conveyed.
I believe hearing can also involve less recognition than listening (as in your 3rd example). For example, "I hear music" just means that I am aware that there is some melodic sound around me. "I listen to music" means that I am more cognitively involved in the activity, perhaps thinking about the lyrics or the way the notes are played.

A: I can hear you - you are audible.
I hear what you are saying / I hear you - I understand what you are saying.
I am listening - I am trying to make sense of the sounds I can hear.
The OP asks for other versions of -
It was if they wear hearing me but they weren't listening.
The phrase that comes to mind is that
The lights were on but there was no-one at home.


text:
Q: One way replication between 2 sql servers on different networks I would like to replicate between 2 sql servers that exist in different networks. This link is not relevant to my case as the servers are not connected: https://learn.microsoft.com/en-us/sql/relational-databases/replication/tutorial-replicating-data-between-continuously-connected-servers?view=sql-server-2017
If we assume that I can get the first copy of the database and then move it to the new server, in order to set up transactional replication, is it necessary that I use a vpn?
I have checked these links but were of no help:
SQL Server Transactional Replication over Internet
SQL Server replication over internet error
Is there a tutorial somewhere on 1) How to do replication over the internet
2) How to do replication if a vpn is required?
More info: The source would be a sql server 2014 and the destination a sql server 2016.


text:
Q: Is there a "partition uuid" for a logical volume? I'm doing a kickstart installation. On the kernel boot line, the kickstart file is specified by inst.ks=hd:LABEL=<lv label>:/ks.cfg. The kernel/anaconda finds and loads this. In the kickstart script, though, I need to specify a partition where the os root that anaconda can boot from. But if the os root is on a lv, then what is the partition needed (ie, for the harddrive kickstart command)?
TIA
ken

A: There are UUIDs for LVs, too. I am not familiar with kickstart but perhaps you can just use them:
$ lvdisplay linux0/rootfs | grep UUID
  LV UUID                iU1gdu-X9GM-xcgw-gHTe-yeBq-BlkV-SRgVn8


text:
Q: ubuntu 22.04 - phpmyadmin not working On Ubuntu 22.04, after installing apache, php, mysql and phpmyadmin, the link http://localhost/phpmyadmin/ returns a blank page.
The only code outputted is:
<?php

declare(strict_types=1);

use PhpMyAdmin\Routing;

if (! defined('ROOT_PATH')) {
    // phpcs:disable PSR1.Files.SideEffects
    define('ROOT_PATH', __DIR__ . DIRECTORY_SEPARATOR);
    // phpcs:enable
}

global $route, $containerBuilder;

require_once ROOT_PATH . 'libraries/common.inc.php';

$dispatcher = Routing::getDispatcher();
Routing::callControllerForRoute($route, $dispatcher, $containerBuilder);

Thanks to anyone who can help me get phpmyadmin running.

A:
returns a blank page. The only code outputted

is the PHP code returned from the page and not executed ?
if yes, seems like you did not install libapache2-mod-php(version), where version is your PHP version, i.e for PHP 8.1:

sudo apt install libapache2-mod-php8.1

after that, reload the apache :

sudo systemctl restart apache2

and try to access phpmyadmin
hope this help

A: Looks simple, but in my case, after updating Ubuntu to 22.4 LTS, my phpmyadmin stopped working. Problem was the Apache server that was not running at all. So it's important to check if your Apache is doing well first using this command:
systemctl status apache2.service

A: I had the same problem when I upgraded my google server from ubuntu 20.04lts to 22.04lts
when I checked the version of the php installed, it was php8.2 but all the guides online talk about 8.1 and installing sudo apt install libapache2-mod-php8.1, instead I did this:
sudo apt install libapache2-mod-php8.2

and then
a2query -m php8.2

And problem solved!!
Hope this helps


text:
Q: Добавление элемента в одномерный динамический массив Предположим в задаю массив так:
int *p,q; ///q мне предварительно известно
p=new int q;

так вот, как мне увеличить при необходимости кол-во элементов в массиве?
A: Если не хотите использовать родной для C++ STL vector<int>, то вместо new/delete можно использовать абсолютно POSIX-овские malloc/realloc/free из libc.
Собственно, можно обойтись и одним realloc(ptr, size), умело управляя значениями ptr и size.
См. man 3 realloc.
A: Никак. Только создав новый динамический массив и скопировав туда старый.
В реальных проектах в таких случаях, чтобы на выделять память каждый раз, выделяют ее с запасом.


text:
Q: ActionScript 3 Profiler & Memory Analysis Tool I'm using Adobe Flash CS 4 and would like to know are there any profiler or memory analysis tools available for it ? (actionscript 3). I know there are available tools for Flex, but are there for Flash CS 4 instead? Thanks.

A: I'm sure there is a program out there, still looking myself, but I found this on a forum:
Most AS3 beginners have programmed something and then heard about memory leaks. So first I'm going to cover ways to detect and fix leaks in preexisting code, and then talk about preventative measures to take when starting to program.
So how do you know if your program has an issue? The clearest way to tell is if it crashes, but that's very impractical. Fortunately, in AS3 we have an object called System whose properties tell us about the conditions under which Flash is running. System.totalMemory, for instance, is the amount of computer memory being used by the Flash Player instance that's running your program. Different platforms determine the value of System.totalMemory in different ways, so I suggest you only run one Flash player instance at a time when measuring its value.
package {

    import flash.utils.Timer;
    import flash.system.System;

    public class SpitMem {
        var t:Timer = new Timer(0);
        var n:int, lastN:int;

        public function SpitMem():void {
            t.addEventListener("timer", spit2, false, 0, true);
        }

        private function spit1():void {
            trace(System.totalMemory);
        }

        private function spit2():void {
            n = System.totalMemory;
            if (n != lastN)
                trace(n);
            lastN = n;
        }
    }
}

If you create an instance of the SpitMem class above and run your code, you can observe the fluctuations in your program's memory usage in the Output window. This is a lot of information, though, and in this format it cannot give you a clear picture of how your program is using its memory.
(Notice the difference above between spit1() and spit2(). spit2() won't output the System.totalMemory if it hasn't changed. Later I'll show how similar logic can turn our data into something more useful.)
If you make a graph of your data in a spreadsheet program, you'll notice that it always seems to be increasing. That doesn't mean that you have a memory leak. Flash's built-in memory management allows certain types of data to sit around until there is an appropriate time to get rid of it. This is called garbage collection, and for most Flash projects, it will cause your memory to accumulate and then dip down. This is called a sawtooth graph, and it's completely normal.

A: This is good tool for actionscript 3 memory analysis and profiling http://demonsterdebugger.com/

A: With the release of the Flash Player 10.1 preview builds, Adobe put out a component that does memory monitoring for you: Memory Monitoring Component


text:
Q: Filter by name after applying a filter that changes characters I've come across a situation where I need to filter elements created by the 'ng-repeat' directive, but I've applied a custom filter that swaps one character by another and vice versa, for each created element.
Then, if I search for the new character that was swapped, the filter won't find it - unless I search for the old one.
How do I apply this input filter after using my custom filter which swaps characters?
In my custom filter brNumber, dots are swapped by commas and vice-versa, so if I search for a dot the filter will find only the ones with comma.
FIDDLE

First Name: <input type="text" ng-model="firstName">

The persons's objects have: | {{ ( i.firstName + ' ' + i.lastName ) | brNumber }} |

{ Javascript.js }
app.filter( 'brNumber', function()
{
    return function( text )
    {
        string = text.toString();
        returnString = '';

        for ( i = 0; i < string.length; i++ )
        {
            returnString += string[i] ===  ',' ? '.' :
            (
                string[i] === '.' ? ',' : string[i]
            );
        }

        return returnString;
    }
});

A: You can wrap a filtered value in same function as a filter in view. Check this https://jsfiddle.net/5Lcafzuc/3/
/// wrap filter argument in function
ng-repeat="i in person | orderBy: 'firstName' | filter: replace(firstName)"

/// add function in scope and use it in display filter
var replace = function(text) {
         if(!text) {
           return false;
         }

         if(text.indexOf(".") >= 0) {
           text = text.replace(".", ",");
         } else if(text.indexOf(",") >=0) {
           text = text.replace(",", ".");
         }

         return text;
      }

app.controller('myCtrl', function($scope) {
    $scope.replace = replace;
});

app.filter( 'brNumber', function() {
    return function(text) {
         return replace(text);
    }
});