text:
Q: asp.net if else without codebehind I am trying to implement if else in ASP file. But it is giving 500 internal server error.
Earlier code was
<title><%=title_tag%></title>

But I've tried to do
<%= if(meta_keywords_tag.IndexOf("MI")!= -1){ %>
<title>MI</title>
 <% }
else { %>
<title><%=title_tag%></title>
<% } %>

When I remove this, It works fine. I'm unable to make it work. Thanks.

A: After commenting, it seems you have a typo at
<%= if(meta_keywords_tag.IndexOf("MI")!= -1){ %>

goes to
<% if(meta_keywords_tag.IndexOf("MI")!= -1){ %>
<title>MI</title>
 <% }
else { %>
<title><%=title_tag%></title>
<% } %>

A: I found a solution to this
<title><%If 2 > 1 Then%>
       MI
   <% Else %>
        <%=title_tag%>
    <%End If %>
        </title>

This works like a charm, But the issue is that I want to use a code behind variable in if statement
<%If ("" <%=title_tag%>"".ToString().Contains("MI") = True) Then%>

It is not working.


text:
Q: How to calculate this limit? Here is my question:
$\displaystyle\lim_{n\rightarrow \infty}n^2[(1+\frac{1}{1+n})^{n+1}-(1+\frac{1}{n})^{n}]=?$
Any hints will be fine. Thank you!

A: As simple as using Limit:
Clear[n];
Limit[n^2 ((1 + 1/(1 + n))^(n + 1) - (1 + 1/n)^n), n -> ∞]
(*E/2*)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Lazarus play music in loop I've been working on a little tool the past few days and the functionality itself is fine.
I wanted to make the tool a little nicer to work with (at least for me) and included a sound-file (called test.wav) which plays one of my favorite songs.
The idea was that the song constantly repeats itself but after one go through, the music stops. This is my code-snippet for the music-part:
procedure TForm1.music();
begin
    PlaySound('test.wav', 0, SND_ASYNC);
end;

When i change SND_ASYNC to SND_LOOP and start debug my project my .exe-Windows does not appear but the music plays (also just once).
Also the Procedure is called at the project.lpr:
begin
      ...
      Form1.music();
      Application.Run;

So how do I get the music to play in a constant loop? It doesn't have to be .wav btw.

A: The PlaySound function is (still) documented
The interesting setting is in the third parameter fdwSound and there what is said about SND_LOOP:

SND_LOOP   The sound plays repeatedly until PlaySound is called again with the pszSound parameter set to NULL. If this flag is set, you must also set the SND_ASYNC flag.

Note the last sentence. So the proper call would be:
PlaySound('test.wav', 0, SND_ASYNC or SND_LOOP);

To activate it automatically at program start, use the forms OnCreate() event.


text:
Q: Why not correct check "is"? Here Kotlin's snippet:
fun withBackgroundColorResId(@IdRes expectedId: Int): Matcher<Any> {

        return object : BoundedMatcher<Any, Any>(Any::class.java) {
            override fun matchesSafely(view: Any): Boolean {
                if (view !is View || view !is ViewGroup) {
                    Log.w(TAG, "withBackgroundColorResId_incorrect_type, view = $view")
                    return false
                }
                val currenColor = (view.background.current as ColorDrawable).color
                val expectedColor = ContextCompat.getColor(view.context, expectedId)
                return currenColor == expectedColor
            }

            override fun describeTo(description: Description) {
                description.appendText("textView with background color resId: ")
                description.appendValue(context.getResources().getString(expectedId))
            }
        }
}

and usage:
onView(withRecyclerView(tradersRecyclerView).atPositionOnView(traderCheckPos, pauseTextView)).check(matches(withBackgroundColorResId(trade_not_running_color)))

and here logcat:
06-05 10:25:12.787 I/ViewInteraction(22053): Checking 'MatchesViewAssertion{viewMatcher=textView with background color resId: "#ffbde6ff"}' assertion on view RecyclerView with id: com.myproject.debug:id/tradersRecyclerView at position: 0
06-05 10:25:12.787 W/com.myproject.custom.matcher.CustomMatchers(22053): withBackgroundColorResId_incorrect_type, view = androidx.appcompat.widget.AppCompatTextView{a412c35 V.ED..C.. ........ 0,0-288,288 #7f0800c9 app:id/pauseTextView}
06-05 10:25:12.794 D/com.myproject.activity.TradersActivityTest(22053): afterEach
06-05 10:25:12.794 I/MockWebServer(22053): MockWebServer[8081] done accepting connections: Socket closed
06-05 10:25:12.825 D/LifecycleMonitor(22053): Lifecycle status change: com.myproject.ui.activity.TradersActivity@2964795 in: PAUSED
06-05 10:25:12.825 D/LifecycleMonitor(22053): running callback: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558
06-05 10:25:12.825 D/LifecycleMonitor(22053): callback completes: androidx.test.rule.ActivityTestRule$LifecycleCallback@9705558

as you can see the object "view" has type androidx.appcompat.widget.AppCompatTextView. As we known AppCompatTextView is extends from View
But why it print
withBackgroundColorResId_incorrect_type, view = androidx.appcompat.widget.AppCompatTextView

?

A: In Kotlin's documentation is states:

checks that a value has a certain type

So according to Your code, You ask in a way

is my view instance of X?

Following this line You get:

*

*is view instanceof View? Answer is yes.

*is view instanceof ViewGroup? Answer is no.

Single views extends mainly by View class. ViewGroups are mostly used in more complex layouts like LinearLayout,FrameLayout, etc.
Concluding the results, You have:
true||false = true

A: The problem is with your if condition, as the view is not a ViewGroup the condition is always true thus will print the LOG.
if (view is View) {
     Log.w(TAG, "withBackgroundColorResId_incorrect_type, view = $view")
     return false
}

Please, try with this one and see the outcome.


text:
Q: How to use dll in view page in MVC? I am trying to import the dll files in view page but i have no idea how to import the dll files in view directly without using controller. Anyone have an idea about it please tell me. Thanks in advance.

A: I would assume your talking about Razor view in mvc.
Top Of Your View
@using Namespace.Reference.Of.Your.Library;

Also add your specific namespace reference within your web.config
<add namespace="here" />

Don't forget to set the Copy Local property to "True" in your dll.


text:
Q: TogglerBar Text Cuting Does anyone know how to prevent the text from cutting when using a Togglerbar?
I would like the text to wrap instead.
For instance:
TogglerBar[Dynamic[x], {a ->
   Text[Style[
     "a)   Early runs of the Turing test used individuals, who were \
easily fooled by the machines used.", "Roboto", 21]],
  b ->
   Text[Style[
     "b)   Turing, whose test examines machines\[CloseCurlyQuote] \
ability to behave in a way indistinguishable from human behavior, has \
a UK law named after him.", "Roboto", 21]]
  }, Appearance -> "Vertical"]


text:
Q: Problem setting API client authorization key in axios The API is developed using Laravel, I am currently implementing authorization logic using Laravel Passport. the client application is a Vuejs application, Http calls are done using axios.
Passport is perfectly returning a token (i'm using client credentials type of grants). axios offers a way to set default headers by setting axios.defaults.headers.common array. Here is my axios call (implemented in bootstrap.js)
async function a() {
    var ret = "";
    await axios
        .post("/oauth/token", {
            "client_id": 7,
            "client_secret": "2GmvfxQev7AnUyfq0Srz4jJaMQyWSt1iVZtukRR6",
            "grant_type": "client_credentials",
            "scope": "*"
        })
        .then((resp) => {
            ret =  resp.data.access_token;
        })
    return ret;
}
a().then((res) => {
    console.log(res) //this perfectly loggs the token to the console.
    axios.defaults.headers.common["Authorization"] = "Bearer " + res
})

However, all subsequent axios calls are missing the Bearer token header.

A: You may try to create an axios instance with custom config:
https://github.com/axios/axios#creating-an-instance
Example:
const axios = require('axios').create({
    headers: {
        'Authorization': 'Bearer: ' + token
    }
});

and use it just like you would normally do:
axios.get(url).then(resp => {
    //response handler
});

axios.post(url, data).then(resp => {
    //response handler
});


text:
Q: Setting a struct pointer to equal the address of another struct I'm trying to set ptr to point at the first element in an array of structs so that when I go back to my main function, I can mess with it (theres reasons why I can't use vArray[0] in the main).
With this code though, its only allowing me to access the structs members in the alg function. Once its return back to main, all of its elements are now null. (I'm thinking it has something to do with a pass-by-value/pass-by-reference problem). Any way to fix this?
void alg(struct vars v[], struct vars *ptr)
{
   ptr = &vars[0];
   printf("%s", ptr->value); //this works here
}

int main()
{
   struct vars vArray[100]; //this has been filled earlier in the code
   struct vars *ptr;
   alg(vArray, ptr);
   printf("%s", ptr->value); //but now this returns null here
}

A: You need "Need of Pointer to pointer" to reflect change in function alg() in main function.
Do it as:
void alg(struct vars v[], struct vars **ptr)
{
   (*ptr) = &vars[0];
   printf("%s", (*ptr)->value); //this works here
}

And call function main as:  alg(vArray, &ptr);
Note: both ptr in main and ptr in function alg() are two different variable.
Btw for learning purpose it is good to write function otherwise you can simply do it in one line as: struct vars *ptr = vArray;. Note array name decays into address of first element in this expression.

A: You have to read about pointer to pointer.
Check this code:
#include <stdio.h>
#include <stdlib.h>

struct vars {
    int data;
};

void alg(struct vars *v, struct vars **ptr);

int main()
{
   struct vars *ptr;
   struct vars vArray;
   vArray.data = 10;

   alg(&vArray, &ptr);
   printf("main : %d\n", ptr->data);
}

void alg(struct vars *v, struct vars **ptr)
{
   *ptr = v;
   printf("fun : %d\n", (*ptr)->data);
}

output :
fun : 10
main : 10

A: In short use double pointer it will solve your problem


text:
Q: Retrieving tweets from twitter I want to retrieve tweets from twitter and save it in CSV file. I use the following code but no result is showed and no errors. what is wrong?
import tweepy
import csv

consumer_key = 'xxx'
consumer_secret = 'xxx'
access_token = 'xxx'
access_token_secret = 'xxx'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

search = raw_input('Search :> ')
csvFile = open('result.csv', 'a')
csvWriter = csv.writer(csvFile)
for tweet in tweepy.Cursor(api.search,
                            q='{}'.format(search),
                            since = "2018-07-1",
                            until = "2018-07-4",
                            lang = "ar").items():
    csvWriter.writerow([tweet.created_at, tweet.text.encode('utf-8')])
    print tweet.created_at, tweet.text
csvFile.close()

A: The free API only returns tweets from the last 7 days (1 week). You are searching for tweets older than that :/


text:
Q: React native / redux - setState cannot update during an existing state transition I'm developing an app using React Native and redux. Express js for the Ajax requests.
The data from my Ajax request won't load and here is the warning I'm getting:

Warning: setState(...): Cannot update during an existing state
  transition (such as within render or another component's
  constructor). Render methods should be a pure function of props and
  state; constructor side-effects are an anti-pattern, but can be moved
  to componentWillMount.

Not entirely sure what I'm doing wrong?
index.ios.js
import React, { Component } from 'react'

import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  NavigatorIOS
} from 'react-native'

import { Provider } from 'react-redux'
import store from './src/store'

import CategoryView from './src/category-view'

class myApp extends Component {
  render() {
    return (
      <Provider store={store}>
        <NavigatorIOS
          initialRoute={{
            component: CategoryView,
            title: 'myApp',
            index: 0
          }}
        />
      </Provider>
    );
  }
}

store.js
import { combineReducers, createStore, applyMiddleware } from 'redux'
import thunkMiddleware from 'redux-thunk'
import category from './reducers/category'
import listings from './reducers/listings'

const reducers = combineReducers({
  category,
  listings
})

const initialState = {}

const store = createStore(
  reducers,
  initialState,
  applyMiddleware(
    thunkMiddleware
  )
)

export default store

Here is my view file:
import React from 'react'
import {
  View,
  ListView,
  ScrollView,
  StyleSheet,
  Image,
  TouchableHighlight
} from 'react-native'

import { connect } from 'react-redux'
import Listings from './listings'
import BetView from './bet-view'
import { getListings } from './actions/listings'

const getDataSource = (listings) =>
  (new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 != r2
  })).cloneWithRows(listings)

const _ListingsView = ({dataSource, navigator, onPress, onLoad}) => {
  onLoad()
  return(
    <ScrollView>
      <ListView
        dataSource={dataSource}
        renderRow={(row) =>
          <Listings
            teamOne={row.game[0]}
            teamTwo={row.game[1]}
            date={row.date}
            onPress={() => onPress(navigator, row.name)}
          />
        }
      />
    </ScrollView>
  )
}

const ListingsView = connect(
  (state) => {
    return {
      dataSource: getDataSource(state.listings.items || []),
      loading: state.listings.loading
    }
  },
  (dispatch) => {
    return {
      onPress: (navigator, name) =>
        navigator.push({
          title: 'test',
          component: BetView,
          passProps: {
            category: name
          }
        }),
      onLoad: () => dispatch(getListings())
    }
  }
)(_ListingsView)

export default ListingsView

Action file:
const URL = 'http://localhost:3000/listings'

export const REQUEST_LISTINGS = 'request-listings'
export const RECEIVE_LISTINGS = 'receive-listings'

const requestListings = () =>
({
  type: REQUEST_LISTINGS
})

const receiveListings = (items) =>
({
  type: RECEIVE_LISTINGS,
  items: items || []
})

const shouldFetch = (state) => {
  const res = (!state.listings.items || 0 == state.listings.items.length && !state.listings.loading)
  return res
}

export const getListings = () =>
  (dispatch, getState) =>
    shouldFetch(getState())
    && dispatch(requestListings())
    && fetch(URL)
      .then(res => res.json())
      .then(json => dispatch(receiveListings(json)))

Here is the reducer:
import { RECEIVE_LISTINGS, REQUEST_LISTINGS } from '../actions/listings'

export default (state = {}, action) => {
  switch (action.type) {
    case RECEIVE_LISTINGS:
      return {
        loading: false,
        items: action.items
      }
    case REQUEST_LISTINGS:
      return {
        loading: true,
        items: []
      }
  }
  return state
}

A: you could try something like this. I have not tested it. Not sure it is perfect. but that is the idea
import React, {Component} from 'react'
import {
  View,
  ListView,
  ScrollView,
  StyleSheet,
  Image,
  TouchableHighlight
} from 'react-native'

import { connect } from 'react-redux'
import Listings from './listings'
import BetView from './bet-view'
import { getListings } from './actions/listings'

const getDataSource = (listings) =>
  (new ListView.DataSource({
    rowHasChanged: (r1, r2) => r1 != r2
  })).cloneWithRows(listings)

class _ListingsView extends Component {

  componentWillMount() {
    this.props.onLoad();
  }

  render() {
    return(
      <ScrollView>
        <ListView
          dataSource={this.props.dataSource}
          renderRow={(row) =>
            <Listings
              teamOne={row.game[0]}
              teamTwo={row.game[1]}
              date={row.date}
              onPress={() => this.props.onPress(this.props.navigator, row.name)}
            />
          }
        />
      </ScrollView>
    )
  }
}

const ListingsView = connect(
  (state) => {
    return {
      dataSource: getDataSource(state.listings.items || []),
      loading: state.listings.loading
    }
  },
  (dispatch) => {
    return {
      onPress: (navigator, name) =>
        navigator.push({
          title: 'test',
          component: BetView,
          passProps: {
            category: name
          }
        }),
      onLoad: () => dispatch(getListings())
    }
  }
)(_ListingsView)

export default ListingsView

So you would be better following their example : https://facebook.github.io/react-native/docs/listview.html
Or this is how I manage ListViews in the application i am currently building:
https://github.com/kamiranoff/mythology/blob/master/src/components/HeroesList/HeroesList.js
(In that example it is a little different because the call to the api is made even before this component is render and on filtering the list, that is why I update the state of datasource in componentWillReceiveProps )


text:
Q: Angular, dynamic forRoot value (based on api) in app module I need to provide a dynamic value into ngModule of app module, fetched by an api (api fetches configuration lets say)
So I have the below module where I need to update the rootUrl based on configuration.
I need to call the /config api and get the result and then pass it in. However, I tried with multiple ways and it was not successful. Is there a solution to that?
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    BrowserAnimationsModule,
    HttpClientModule,
    AppRoutingModule,
    ApiModule.forRoot({rootUrl: config.url})   <-- HERE
  ],
  providers: [
    AppConfig,
    {
      provide: APP_INITIALIZER,
      useFactory: (config: AppConfig) => () => config.load(),
      deps: [AppConfig],
      multi: true
    },
  ],
  bootstrap: [AppComponent]
})
export class AppModule {
}

A: So I've found another way of doing what i needed. The purpose of this one was to initialise the base url of my endpoint based on the configuration. This can be also achieved using an interceptor to overwrite the request url


text:
Q: Proving a relation between 2 sets as antisymmetric Let $U = \{1,...,n\}$
And let $A$ and $B$ be partitions of the set $U$ such that $$\bigcup A = \bigcup B = U$$
and $|A|=s, |B|=t$
Let's define a relation between the sets $A$ and $B$ as follows: $$B \succ A \iff \forall_{1 \leq i \leq t}, \exists_{1 \leq j \leq s}: B_i \subseteq A_j$$
Now, we want to prove that $\succ$ is an antisymmetric relation. Thus, we want to prove that $$\forall_{A,B},A \succ B \land B \succ A \implies A=B$$
How would one prove this?
I'm pretty much stuck after laying out the conditions, and I don't have a clue on what assumptions I should make that will lead me anywhere.

A: First of all, for what you write to make sense, you're not picking two partitions and defining a relation between those particular two partitions. You're defining a single relation on the set of all partitions.
Second, I think you're overcomplicating things by considering a partition to be an indexed family of subsets of $U$. Indeed, if you consider the assignment of indices to be part of the partition, then what you want to prove is not true, because then the two partitions
$$ A_1 = \{1\}, A_2 = \{2,3,\ldots,n\} $$
and
$$ B_1 = \{2,3,\ldots,n\}, B_2 = \{1\} $$
would satisfy $A\succ B\succ A$, but $A\ne B$.
So we need to work with partitions being unordered collections of subsets of $U$, and your relation should then be defined as
$$ B\succ A \quad\iff  \forall b\in B\; \exists a\in A: b\subseteq a$$
In order to prove that this is antisymmetic, we assume $A\succ B\succ A$ and seek to prove that $A \subseteq B$. (Then, since $A$ and $B$ were arbitrary, and we also have $B\succ A\succ B$, the same argument shows $B\subseteq A$, so $A = B$).
In order to prove this, it is crucial that $A$ and $B$ are partitions, which requires among other things that (1) any two different members of $A$ must be disjoint, and (2) the empty set is not in $A$.
Now, we're assuming that $A\succ B\succ A$. To prove $A\subseteq B$ consider any $x\in A$. One of the $\succ$s gives us $y\in B$ such that $x\subseteq y$, and the other gives $z\in A$ sucht that $x\subseteq y\subseteq z$. But because $x$ and $z$ are both in $A$, they must be either equal or disjoint. Since $x$ is non-empty and $x\subseteq z$ they can't be disjoint, so $x=z$. But then $x\subseteq y \subseteq x$, and $y$ must equal $x$. Since $y$ was in $B$, we have proved $x\in B$.

A: The key to starting just about any proof is in the definition, so let's take a look:
$$\forall_{A,B},A \succ B \land B \succ A \implies A=B$$
We start with the quantifier; here it is $\forall_{A,B}$. So let's pick two arbitrary partitions $A$ and $B$.
Next we notice that we want to prove an implication. One proof strategy to use here is to assume the antecedant (the stuff on the left of the $\implies$) and try to prove the conclusion (the stuff on the right of the $\implies$).
Now we have reduced the problem to assuming that $A \succ B \land B \succ A$ and prove that $A = B$. How do you prove that two partitions are equal? I'll let you think about this for a little bit then come back and tell us what you come up with and where you get stuck.


text:
Q: What is the correct term to describe "An animal with the ability to fly"? After searching I couldn't find anything, with the closest depiction being a pilot.
"___ animals have a different form of locomotion to aquatic or terrestrial animals."

A: I would say they are flying animals.
Flying birds are by far the most common, but we also have flying mammals. We once had flying reptiles but these became extinct long ago. Flying fish are a family of marine fish that can fly short distances horizontally (see "gliding flight")

"flying" - adj -  moving or capable of moving in the air

A: Volant

(of an animal) able to fly or glide. [Google Dictionary]
A number of animals have evolved aerial locomotion, either by powered
  flight or by gliding. Flying and gliding animals (volant animals) have
  evolved separately many times, without any single ancestor. Flight has
  evolved at least four times, in the insects, pterosaurs, birds, and
  bats.

[https://en.wikipedia.org/wiki/Flying_and_gliding_animals ]


text:
Q: Multiple Client execute SQL at the same time I have a sample data (Slots = 1)
The system must provide 1 slot for a client. If the client A gets a slot, sample data will be Slots = 0.
What if Client A and Client B execute the SQL query at the same time?
The Sample data will be Slots = -1.
I tried to prevent it using PHP,
if($Slots > 0){
execute....
}

But clients still executing the SQL query.
How can I make ONLY ONE can get the slot even if they execute it at the same time?

A: To start, make sure your table engine is InnoDB, as MyISAM can only do table level locking instead of row locking.
Then you can use the SELECT .. FOR UPDATE command to get exclusive access to the row.
This answer on this thread on dba.stackexchange.com explains it perfectly: https://dba.stackexchange.com/a/15864
Once the row is locked, MySQL will throw an error to any other process that tries to lock or update that row. So to tell a user the slots are already taken, you'll need to catch any errors and alert the user accordingly.
Here's a simple example:
<?php
$db = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', 'password');

// Ask PDO to throw Exceptions on error
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

try
{
    $db->beginTransaction();

    // If the row is locked, mysql will wait for a time-out. By default the timeout is 50 seconds
    // so to make sure the flow of the script works, we set the time-out to 1
    $db->query('SET innodb_lock_wait_timeout = 1;');

    // Select the row we want to update and tell MySQL to lock it until we are done updating
    // by adding the "FOR UPDATE" command to the query.
    // Note that if the row is already locked by another process, this query will throw an error
    // which we'll catch below. It means that someone else already has the slot and is updating it.
    $result = $db->query('SELECT slots FROM table WHERE id = 1 FOR UPDATE');

    if ($result !== false)
    {
        $object = $result->fetchObject();

        if ($object->slots > 0)
        {
            $db->query('UPDATE table SET slots = slots - 1 WHERE id = 1');

            echo "You got the slot!";
        }
        else echo "Sorry, no more slots available.";
    }

    // Commit the transaction and release the lock, and move on.
    $db->commit();
}
catch (Exception $e)
{
    // An error was thrown, so rollback the transaction
    $db->rollback();

    // and tell the user he couldn't get the slot
    echo "Failed to reserve a slot for you: (" . $e->getMessage() . ")";
    exit();
}

It's easy to test this locally. Just open up a second MySQL session via command-line and execute these commands to set the lock:
{10:34}[5.4.36]/tmp ➭ mysql -uroot -p
Welcome to the MySQL monitor.  Commands end with ; or \g.

..

mysql> USE test;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A

Database changed
mysql> BEGIN;
Query OK, 0 rows affected (0.00 sec)

mysql> SELECT slots FROM table WHERE id = 1 FOR UPDATE;
+-------+
| slots |
+-------+
|    87 |
+-------+
1 row in set (0.00 sec)

..
the lock is set, if you now run the example script you should not be able to update the slots and get an error
..

mysql> COMMIT;

Take a look at the MySQL docs for more info: https://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html


text:
Q: how to use restfb java api to register new game achievement? I see that game achievements are not one of the supported object of the library. Is there a generic way to go about posting other unsupported object types?

A: Generic meaning using the supported SDK or using the API directly via HTTP calls?
The PHP SDK or a direct POST to /APP_ID/achievements with the App Access token will do this.
If all you're doing is registering achievements, you'll only need to do this once, so just do it via the Debug tool - you can get the app access token via the Access Token tool


text:
Q: How to make floating divs and equal height First of all, this is my code for the web page

@import url("reset.css");
@import url('https://fonts.googleapis.com/css?family=Raleway');
*
{
  box-sizing:border-box;
}

body
{
  background-color: #9E9E9E;
}

#wrapper
{
  width:95%;
  max-width:980px;
  margin: 0 auto;
  font-family: 'Raleway', sans-serif;
  line-height: 2rem;
}

.header
{
  padding:18px;
  background-color: #757575;

  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
}

.column_left
{
  float:left;
  padding:18px;
  width:70%   ;
  background-color:#607D8B;
  border-top-left-radius: 5px;
  border-bottom-left-radius:5px;
}

.column_right
{
  float:right;
  padding:18px;
  width:29.99%;
  background-color:#455A64;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;

}

/*For Screens 750 PX or less (width)*/
@media screen and (max-width:750px)
{
  .header
  {
    text-align:center;
  }

  .column_right
  {
    display:none;
  }

  .column_left
  {
    width:100%;
    border-radius:5px;
  }
}

h1
{
  font-size:1.8rem;
}

h2
{
  font-size: 1.4rem;

}

p
{

}

nav
{}
nav ul
{}
nav ul li
{
  width:100%;
  background-color:#607D8B;
  text-align:center;
  padding:2.5px;
  border-radius:5px;
  margin-bottom:5px;
}
nav ul li a
{
  color:#455A64;
}

footer
{
  padding:18px;
  background-color: #757575;
  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
  float:none;
  display:flex;
}
<meta name="viewport" content="width=device-width, user-scalable=no">

Lorem Ipsum

Welcome to Lorem Ipsum

Aenean nec vestibulum justo, ut aliquet ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Etiam viverra interdum neque, sed sagittis lectus sodales sit amet.

Maecenas posuere laoreet auctor. Integer vel nulla ut magna interdum consectetur.

Vestibulum non ligula sed diam luctus tincidunt in sit amet metus.

Navigation

Link

Link

Link

    © 2016 Ipsum Lorem

Basically I would like to have the column_left and column_right classes the same height, without using height=100%. The website will have more than one page, and the length on the others may not be the same as the example page. Here is an image of what I got so far:

Basically, I want the navigation div to be as tall as the one beside it.

A: If flexbox is an option, you can give:
display: flex;
flex-wrap: wrap;

to wrapper and that will fix the heights - see demo below:

@import url("reset.css");
@import url('https://fonts.googleapis.com/css?family=Raleway');
 * {
  box-sizing: border-box;
}
body {
  background-color: #9E9E9E;
}
#wrapper {
  width: 95%;
  max-width: 980px;
  margin: 0 auto;
  font-family: 'Raleway', sans-serif;
  line-height: 2rem;
  display: flex;
  flex-wrap: wrap;
}
.header {
  padding: 18px;
  background-color: #757575;
  border-radius: 5px;
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;
}
.column_left {
  float: left;
  padding: 18px;
  width: 70%;
  background-color: #607D8B;
  border-top-left-radius: 5px;
  border-bottom-left-radius: 5px;
}
.column_right {
  float: right;
  padding: 18px;
  width: 29.99%;
  background-color: #455A64;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}
/*For Screens 750 PX or less (width)*/

@media screen and (max-width: 750px) {
  .header {
    text-align: center;
  }
  .column_right {
    display: none;
  }
  .column_left {
    width: 100%;
    border-radius: 5px;
  }
}
h1 {
  font-size: 1.8rem;
}
h2 {
  font-size: 1.4rem;
}
p {} nav {} nav ul {} nav ul li {
  width: 100%;
  background-color: #607D8B;
  text-align: center;
  padding: 2.5px;
  border-radius: 5px;
  margin-bottom: 5px;
}
nav ul li a {
  color: #455A64;
}
footer {
  padding: 18px;
  background-color: #757575;
  border-radius: 5px;
  width: 100%;
  margin-top: 5px;
  margin-bottom: 5px;
  float: none;
  display: flex;
}

Lorem Ipsum

Welcome to Lorem Ipsum

Aenean nec vestibulum justo, ut aliquet ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Etiam viverra interdum neque, sed sagittis lectus sodales sit amet.

Maecenas posuere laoreet auctor. Integer vel nulla ut magna interdum consectetur.

Vestibulum non ligula sed diam luctus tincidunt in sit amet metus.

Navigation

Link

Link

Link

    © 2016 Ipsum Lorem

A: If you can't use flexbox, which is the recommended way, and you don't want script, here is 2 options:

*

*Since both float: right and position: absolute takes the element out of flow (in their own way), the latter will solve your problem if the left column is always higher. With an added wrapper (columns) it could look like this

@import url("reset.css");
@import url('https://fonts.googleapis.com/css?family=Raleway');
*
{
  box-sizing:border-box;
}

body
{
  background-color: #9E9E9E;
}

#wrapper
{
  width:95%;
  max-width:980px;
  margin: 0 auto;
  font-family: 'Raleway', sans-serif;
  line-height: 2rem;
}

.header
{
  padding:18px;
  background-color: #757575;

  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
}
.columns
{
  position: relative;
}
.columns::after
{
  content: '';
  display:block;
  clear:both;
}
.column_left
{
  float:left;
  padding:18px;
  width:70%   ;
  background-color:#607D8B;
  border-top-left-radius: 5px;
  border-bottom-left-radius:5px;
}

.column_right{
  position: absolute;
  top: 0;
  right: 0;
  padding:18px;
  width:30%;
  background-color:#455A64;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
  height: 100%;
}

/*For Screens 750 PX or less (width)*/
@media screen and (max-width:750px)
{
  .header
  {
    text-align:center;
  }

  .column_right
  {
    display:none;
  }

  .column_left
  {
    width:100%;
    border-radius:5px;
  }
}

h1
{
  font-size:1.8rem;
}

h2
{
  font-size: 1.4rem;

}

p
{

}

nav
{}
nav ul
{}
nav ul li
{
  width:100%;
  background-color:#607D8B;
  text-align:center;
  padding:2.5px;
  border-radius:5px;
  margin-bottom:5px;
}
nav ul li a
{
  color:#455A64;
}

footer
{
  padding:18px;
  background-color: #757575;
  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
  float:none;
  display:flex;
}
<meta name="viewport" content="width=device-width, user-scalable=no">

Lorem Ipsum

Welcome to Lorem Ipsum

Aenean nec vestibulum justo, ut aliquet ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Etiam viverra interdum neque, sed sagittis lectus sodales sit amet.

Maecenas posuere laoreet auctor. Integer vel nulla ut magna interdum consectetur.

Vestibulum non ligula sed diam luctus tincidunt in sit amet metus.

Navigation

Link

Link

Link

    © 2016 Ipsum Lorem

*Use display: table. With an added wrapper (columns) it could look like this:
(I favor this before the above as it is dynamic and keep both columns equal high regardless of which one is higher.)

@import url("reset.css");
@import url('https://fonts.googleapis.com/css?family=Raleway');
*
{
  box-sizing:border-box;
}

body
{
  background-color: #9E9E9E;
}

#wrapper
{
  width:95%;
  max-width:980px;
  margin: 0 auto;
  font-family: 'Raleway', sans-serif;
  line-height: 2rem;
}

.header
{
  padding:18px;
  background-color: #757575;

  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
}
.columns
{
  display: table;
  width: 100%;
}
.column_left
{
  display: table-cell;
  padding:18px;
  width:70%;
  background-color:#607D8B;
  border-top-left-radius: 5px;
  border-bottom-left-radius:5px;
}

.column_right{
  display: table-cell;
  padding:18px;
  width:30%;
  background-color:#455A64;
  border-top-right-radius: 5px;
  border-bottom-right-radius: 5px;
}

/*For Screens 750 PX or less (width)*/
@media screen and (max-width:750px)
{
  .header
  {
    text-align:center;
  }

  .column_right
  {
    display:none;
  }

  .column_left
  {
    width:100%;
    border-radius:5px;
  }
}

h1
{
  font-size:1.8rem;
}

h2
{
  font-size: 1.4rem;

}

p
{

}

nav
{}
nav ul
{}
nav ul li
{
  width:100%;
  background-color:#607D8B;
  text-align:center;
  padding:2.5px;
  border-radius:5px;
  margin-bottom:5px;
}
nav ul li a
{
  color:#455A64;
}

footer
{
  padding:18px;
  background-color: #757575;
  border-radius:5px;
  width:100%;
  margin-top:5px;
  margin-bottom:5px;
  float:none;
  display:flex;
}
<meta name="viewport" content="width=device-width, user-scalable=no">

Lorem Ipsum

Welcome to Lorem Ipsum

Aenean nec vestibulum justo, ut aliquet ante.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Etiam viverra interdum neque, sed sagittis lectus sodales sit amet.

Maecenas posuere laoreet auctor. Integer vel nulla ut magna interdum consectetur.

Vestibulum non ligula sed diam luctus tincidunt in sit amet metus.

Navigation

Link

Link

Link

    © 2016 Ipsum Lorem

A: Per this similar question, you can achieve this using JavaScript.
document.getElementsByClassName("column_left")[0].style.height = document.getElementsByClassName("column_right")[0].style.height;

This will set the left column's height to the right column's height. You can switch around the code, and use the question's answers too.


text:
Q: How to disable right clicking mathjax in shiny How to disable right clicking mathjax in shiny? For example, see
https://shiny.rstudio.com/gallery/mathjax.html
Ideally, I would like users not to be abe to interact with the mathjax text at all.

A: You can turn off the MathJax contextual menu by adding
<script type="tet/x-mathjax-config">
MathJax.Hub.Config({
  showMathMenu: false
});
</script>

to your page just before the script that loads MathJax.js itself.
I would encourage you not to do this, however.  There are important functions in the menu, including the controls for those using assistive technology like screen readers.  Those users may need access to those controls to set things appropriately for their assistive needs.  If you disable the menu, you may prevent them from being able to use your pages.

A: In case of MathJax 3 use the following syntax:
MathJax = {
  options: {
    renderActions: {
      addMenu: []
    }
  }
};

A: a little CSS rule
mjx-container.MathJax {
  pointer-events: none;
}


text:
Q: deleting document from cosmos db using C# and cosmos client I am new to Cosmos DB and after reading through the microsoft docs am attempting to delete records from a cosmos db. I have tried to follow the example as closely as possible. The record is being found and read but I am running into a not found error when attempting to delete.
The collection is partitioned, and I have mentioned partition key as mentioned in the examples, but still results in an error.
    private async Task QueryItemsAsync()
    {
        var sqlQueryText = "SELECT * FROM c WHERE c.tenantId = '5c6cb2d77c1c2edc001b9007' and c.id = 'abae8abf-5836-464f-8129-1f0e83a1f639'";

        QueryDefinition queryDefinition = new QueryDefinition(sqlQueryText);
        FeedIterator<Order> queryResultSetIterator = this.container.GetItemQueryIterator<Order>(queryDefinition);

        List<Order> orders = new List<Order>();

        while (queryResultSetIterator.HasMoreResults)
        {
            FeedResponse<Order> currentResultSet = await queryResultSetIterator.ReadNextAsync();
            foreach (Order o in currentResultSet)
            {
                orders.Add(o);
                Console.WriteLine("\tRead {0}\n", o);
            }
        }
    }
    private async Task DeleteFamilyItemAsync()
    {
        var partitionKeyValue = "tenantId";
        var orderId = "abae8abf-5836-464f-8129-1f0e83a1f639";

        // Delete an item. Note we must provide the partition key value and id of the item to delete
        ItemResponse<Order> orderResponse = await this.container.DeleteItemAsync<Order>(orderId, new PartitionKey(partitionKeyValue));
        Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, orderId);
    }

As seen below the record is being read so it is being found but when I attempt to delete it, it is not being deleted.
Read {"Id":null,"patientId":null,"orchestrationId":null,"preOrderId":"88557ec1-dccb-4397-9ce4-20b6aeb1d636","cartId":"adc463ef-7f38-4fa8-8f37-e505db3a5134","confirmationNum":"QDQ-9244014-14708","cartConfirmationNum":"IBM-8622967-14079","countryCode":null,"type":"order","cancelDate":null,"id":"abae8abf-5836-464f-8129-1f0e83a1f639"}
NotFound error occurred: CosmosRequestException;StatusCode=NotFound;SubStatusCode=0;ActivityId=6dd52d23-68c8-4e6d-b4ff-70cd2a6921cf;RequestCharge=1.24;Message=Response status code does not indicate success: 404 Substatus: 0 Reason: ().;
End of demo, press any key to exit.

A: The problem is with your partitionKeyValue. You are providing the partition key definition instead of the value. The value is the actual tenant id not the text tenantId.
Your delete code should then look like this:
private async Task DeleteFamilyItemAsync()
{
    var partitionKeyValue = "5c6cb2d77c1c2edc001b9007"; // <-- This is the change
    var orderId = "abae8abf-5836-464f-8129-1f0e83a1f639";

    // Delete an item. Note we must provide the partition key value and id of the item to delete
    ItemResponse<Order> orderResponse = await this.container.DeleteItemAsync<Order>(orderId, new PartitionKey(partitionKeyValue));
    Console.WriteLine("Deleted Family [{0},{1}]\n", partitionKeyValue, orderId);
}


text:
Q: Alpha blending in three.js I am trying to volume render the raw data using three.js. The raw data can be of any type. For rendering the data I have written code:
dims is an array of size of data in three axes:
One of the data dims is [256, 256 128] and data is uint8Array(8388608).

    var texture = new THREE.DataTexture3D(data, dims[0], dims[1], dims[2]);
    var texture = new THREE.DataTexture3D(data, dims[0], dims[1], dims[2]);
    texture.format = eval(format[1]);
    texture.type = eval(format[0]);
    texture.minFilter = texture.magFilter = THREE.LinearFilter;
    texture.unpackAlignment = 1;

    material = new THREE.ShaderMaterial({
        uniforms: uniforms,
        vertexShader: shader.vertexShader,
        fragmentShader: shader.fragmentShader,
        side: THREE.BackSide,
        transparent: true,
        blending: THREE.CustomBlending,
        blendEquation: THREE.AddEquation,
        blendSrc: THREE.SrcAlphaFactor,
        blendDst: THREE.OneMinusSrcAlphaFactor
     });

This format array is from a function that checks the format of the data.
    function findFormat(dtype) {
      console.log(dtype);
      let regex = /(u*)(int|float)(\d+)/ig;
      let format = regex.exec(dtype);
      if (format[3] == 8) {
        dtype = ["THREE.UnsignedByteType", "THREE.RedFormat"];
      }
      if (format[3] == 16) {
        dtype = ["THREE.UnsignedShort4444Type", "THREE.RGBAFormat"];
      }
      if (format[3] == 32) {
         dtype = ["THREE.UnsignedByteType", "THREE.RGBAFormat"];
      }

      return (dtype);
     }

I am just checking the data type if it is 8/16/32 bits.
This is the output I am getting :
This is iso type:

This is mip type output :

What I believe is that opacity is not active in these so all of the rendered layer or object is looking as an opaque object. This is a required output or looks like these :

I don't understand how to perform alpha blending in this.


text:
Q: Revealing class pattern vs prototype method? I've seen the revealing module pattern, as well as the prototype class pattern. I kind of adapted the two together into a revealing class pattern. I'm trying to figure out if there are any gotchas with this pattern, or things that wouldn't work. As long as the constructor for the object is typeof "function" I would think there wouldn't be any problems.
The only caveat I can come up with, is a high volume instantiated class, where the private functions are getting create every time a new class is created. This may cause memory problems for thousands of instantiations. For larger classes that don't build up in memory, though, my thinking is the easier code readability and security may be of benefit. By keeping functions private and revealing them, the obfuscator minimizes all of the internal functions, making it difficult for prying eyes. Granted, it is not foolproof, but just an extra layer of protection. Additionally, being able to work inside of the function privately, removes hundreds of occurrences of "this" within the class. Maybe it's a small advantage, but for complex code it kind of improves the readability. Anybody see any major problems with the pattern?
//standard pattern

var MyClass = function() {
    this.func1 = function() {
        //dostuff
    };
};
MyClass.prototype.func2 = function() {
    this.func1();
    //dostuff
};

-
//revealing class pattern

var MyClass = function() {
    function privateFunc() {
        //dostuff
    }

    function publicFunc() {
        privateFunc();
        //dostuff
    }

    this.publicFunc = publicFunc;
};

A:
I've seen the revealing module pattern, as well as the prototype class pattern. I kind of adapted the two together into a revealing class pattern.

You should have a look at the revealing prototype pattern which truly combines them to reveal a class. What you currently have should rather be called "revealing instance pattern".

Anybody see any major problems with the pattern?

You've stated the major caveat already, but if you consider it worth then go for it. Given that most classes are not instantiated in very large volumes this doesn't really make a difference any more.
However, you could improve your pattern. Given that you don't use the prototype any more, there's no reason to keep it. Drop the new operator, drop using the this keyword in the constructor, and return an object literal. Voilá, you've got a factory function!


text:
Q: Get multiple attributes with .attr() to get both "id" and ":checked" from element using "this" | jQuery my question is very simple and doesn't seem to be around as often as setting or applying value in multiple cases.
Using $(this) how can I achieve to get multiple attributes from a single element using as the title informs simply .attr().
$(this).attr('id', "checked") // Pseudo code

For the use to be stored in an array or variable for example. Thank you.

A: The syntax you used will set the value to the attribute. Hence, you can use
something like ['id', 'checked'].map(a => $el.attr(a)) as mentioned by lxe in the comment or you can create a jQuery wrapper attrs as below.
To get the value of checked property, you can use prop as below instead of attr.
Working snippet:

$(document).ready(function() {
  $.fn.attrs = function() {
    return Object.keys(arguments).map(k => $(this).prop(arguments[k]));
  };

  $('input[type="checkbox"]').click(function() {
     globalCallback($(this).attrs('id', 'checked'));
  });
});

function globalCallback(attrs) {
  console.log(attrs);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Click the checkbox and see the console:
<br/>
<input type="checkbox" id="checkbox1" /> Checkbox 1
<input type="checkbox" id="checkbox2" /> Checkbox 2
<input type="checkbox" id="checkbox3" /> Checkbox 3

A: You can't do this, according to jQuery documentation:

Get the value of an attribute for the first element in the set of matched elements.

Moreover your $(this).attr('id', "checked") code will set to the id attribute the checked value, since attr can be used to set values with exactly such syntax.
However you can create a helper methods like the one mentioned by lxe

A: You can get the attributes using Array#reduce on the Element.attributes to create an object of attributes:

// get all elements attributes, and convert them to array
var attributes = [].slice.call($('#v-box').get(0).attributes, 0);

// reduce the array to key value pairs
var object = attributes.reduce(function(r, attr) {
  r[attr.name] = attr.value;
  return r;
}, {});

console.log(object);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="v-box" type="checkbox" checked="checked">

A: You can easily extend the jQuery function to accommodate what your looking for.
If you aren't interested in extending you could create a new function/ plugin as well
Here's an example:
(function($)
{
  var oldAttr = $.fn.attr;
  $.fn.attr = function() {
    var args= arguments[0];
    if(Object.prototype.toString.call(args)=="[object Array]") {
      return [args.map((e=> oldAttr.apply(this, [e])))];
      //if you want to get a string you could just try `return args.map((e=> oldAttr.apply(this, [e])))`
    }
    return oldAttr.apply(this, arguments);
  };
})(jQuery);

Demo: https://jsfiddle.net/eztukwj9/


text:
Q: Transfer the authenticated user to a SPA without forcing them to re-enter their credentials This is my current setup:

*

*IdentityServer4

*API (Bearer authentication)

*SPA page (oidc-client implicit flow redirected to IdentityServer4 Quickstart UI)

*Native application (written i C#)

The native application already have the users credentials. I want to provide a web link to the SPA page from the native application, but I don't want to force the user to login again when navigating to the web. Instead I want to move their current session to the web page.
Is it possible to "inject" the access token into the oidc-client? (using a url fragment). Or is there any other flow or way to make this work?

A: In general the answer should be: you are on a wrong way.Look: you use resource owner password flow in your native app and that's wrong. It's not interactive, meaning not only IdP has access to the credentials. In general such flow is recommended for test purposes etc, not for general use. One huge limitation of the non-interactive flow is that it does not create a user session.  If you switch your native app to an interactive flow such as Code flow with PKCE extension, it will create the session. After that your other app will get authenticated automatically whenever the session cookie for Identity server is alive.NB: If you don't like to improve your architecture, you are free to do whatever you like, including providing a token in the link. That token will still be valid for calling the API. But that will be not the implicit flow, you will not have a session, nor the possibility to use silent refresh feature.


text:
Q: Lipschitz function where $f ^2$ is not Lipschitz I found this problem when going through Lipschitz functions, I wanted to solve it but could not come up with any such function. Help is appreciated.

Give an example of a Lipschitz function $f$ on $[0,∞)$ such that its square $f^2$ is not a Lipschitz function.

A: $f(x)=x$. $g(x)=x^2$ is not Lipschitz.


text:
Q: PyQT5: Grid layout inside horizontal layout Can someone help me figure out how to combine layouts?
Taking offset from the guides from: [https://pythonspot.com/en/pyqt5/]
I would rather not use Designer as the layout is going to be a part of several tabs that is determined based on the amount of tests and data sets from a specified data folder.
For example, I would like to switch out the Blue button in:
    import sys
    from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout
    from PyQt5.QtGui import QIcon
    from PyQt5.QtCore import pyqtSlot

    class App(QDialog):

        def __init__(self):
            super().__init__()
            self.title = 'PyQt5 layout - pythonspot.com'
            self.left = 10
            self.top = 10
            self.width = 320
            self.height = 100
            self.initUI()

        def initUI(self):
            self.setWindowTitle(self.title)
            self.setGeometry(self.left, self.top, self.width, self.height)

            self.createHorizontalLayout()

            windowLayout = QVBoxLayout()
            windowLayout.addWidget(self.horizontalGroupBox)
            self.setLayout(windowLayout)

            self.show()

        def createHorizontalLayout(self):
            self.horizontalGroupBox = QGroupBox("What is your favorite color?")
            layout = QHBoxLayout()

            buttonBlue = QPushButton('Blue', self)
            buttonBlue.clicked.connect(self.on_click)
            layout.addWidget(buttonBlue)

            buttonRed = QPushButton('Red', self)
            buttonRed.clicked.connect(self.on_click)
            layout.addWidget(buttonRed)

            buttonGreen = QPushButton('Green', self)
            buttonGreen.clicked.connect(self.on_click)
            layout.addWidget(buttonGreen)

            self.horizontalGroupBox.setLayout(layout)

        @pyqtSlot()
        def on_click(self):
            print('PyQt5 button click')

    if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = App()
        sys.exit(app.exec_())

with the grid layout from:
    import sys
    from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QHBoxLayout, QGroupBox, QDialog, QVBoxLayout, QGridLayout
    from PyQt5.QtGui import QIcon
    from PyQt5.QtCore import pyqtSlot

    class App(QDialog):

        def __init__(self):
            super().__init__()
            self.title = 'PyQt5 layout - pythonspot.com'
            self.left = 10
            self.top = 10
            self.width = 320
            self.height = 100
            self.initUI()

        def initUI(self):
            self.setWindowTitle(self.title)
            self.setGeometry(self.left, self.top, self.width, self.height)

            self.createGridLayout()

            windowLayout = QVBoxLayout()
            windowLayout.addWidget(self.horizontalGroupBox)
            self.setLayout(windowLayout)

            self.show()

        def createGridLayout(self):
    self.horizontalGroupBox = QGroupBox("Grid")
    layout = QGridLayout()
    layout.setColumnStretch(1, 4)
    layout.setColumnStretch(2, 4)

    layout.addWidget(QPushButton('1'),0,0)
    layout.addWidget(QPushButton('2'),0,1)
    layout.addWidget(QPushButton('3'),0,2)
    layout.addWidget(QPushButton('4'),1,0)
    layout.addWidget(QPushButton('5'),1,1)
    layout.addWidget(QPushButton('6'),1,2)
    layout.addWidget(QPushButton('7'),2,0)
    layout.addWidget(QPushButton('8'),2,1)
    layout.addWidget(QPushButton('9'),2,2)

    self.horizontalGroupBox.setLayout(layout)

    if __name__ == '__main__':
        app = QApplication(sys.argv)
        ex = App()
        sys.exit(app.exec_())

A: You can add a layout as an element of another layout in a similar fashion to adding a widget by using addLayout()
layout = QtWidgets.QHBoxLayout()
sublayout = QtWidgets.QGridLayout()
layout.addLayout(sublayout)


text:
Q: Firefox is using too much memory and is freezing my machine I have some 40 machines in our company. They are running Ubuntu 14.04 with 4Gigs of RAM. Very recently I noticed that almost on all machines Firefox browser is using around 1.2 to 1.5 GB of RAM and making my computer freeze.
Can someone help me in resolving the issue?

A: From experience, I would recommend installing Chromium Browser and comparing the memory usage. It's hard to say whether the amount of RAM your system is consuming for Firefox is normal or not as it all depends on what your browsers are doing and what sites they are visiting.
Speaking out of personal experience, I've found chromium browser to be less resource intensive than FireFox. Others may have had differing experiences. If I were in your shoes, I'd get FireFox uninstalled and stick with Chromium.


text:
Q: PHP strings have same encoding (UTF8) and appear as identical in browser but are not equal so I need to compare to strings (1 is a result from a CURL call to a remote URL, using charset UTF8) and the other is hardcoded in my script (utf8 as well).
The strings look the same but when I compare them using strcmp(), the result is -44.
I tried to trim() both of them, but still same result.
I double checked their encoding us mb_detect_encoding() and they appear to be both in UTF8 (as I expect them to be).
I also double check them with preg_match('!!u', $string) which seems to be an accurate way to detect if they are in UTF8 as well. result is 1, so they both are.
bin2hex(string1)
hps://graph.facebook.com/v2.3/?id=hp://www.topito.com/top-images-monde-chats-connards-de-felins

68747470733a2f2f67726170682e66616365626f6f6b2e636f6d2f76322e332f3f69643d3c6c696e6b3e687474703a2f2f7777772e746f7069746f2e636f6d2f746f702d696d616765732d6d6f6e64652d63686174732d636f6e6e617264732d64652d66656c696e733c2f6c696e6b3e

bin2hex(string2)
hps://graph.facebook.com/v2.3/?id=hp://www.topito.com/top-images-monde-chats-connards-de-felins

68747470733a2f2f67726170682e66616365626f6f6b2e636f6d2f76322e332f3f69643d687474703a2f2f7777772e746f7069746f2e636f6d2f746f702d696d616765732d6d6f6e64652d63686174732d636f6e6e617264732d64652d66656c696e73

How can I make them equal ? I tried to convert them both to utf8 (from utf8 ^^) using mb_convert_encoding(), but still they are not equal....
Thank you
EDIT
i'm extracting my string(which are URL) using cURL from this feed: h**p://www.topito.com/feed
my curl function is:
  $header[] = "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5";
  $header[] = "Cache-Control: max-age=0";
  $header[] = "Connection: keep-alive";
  $header[] = "Keep-Alive: timeout=5, max=100";
  $header[] = "Accept-Charset: utf-8;q=0.7,*;q=0.7"; // Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7
  $header[] = "Accept-Language: en-us,en;q=0.5";
  $header[] = "";

  $curl = curl_init ();
  curl_setopt($curl, CURLOPT_URL, $url);
  curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
  curl_setopt($curl, CURLOPT_USERAGENT, $useragent);
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate');
  curl_setopt($curl, CURLOPT_REFERER, "http://www.google.fr");
  curl_setopt($curl, CURLOPT_HEADER, 0);
  curl_setopt($curl, CURLINFO_HEADER_OUT, 1);
  curl_setopt($curl, CURLOPT_COOKIEFILE, getcwd().'/cookies.txt');
  curl_setopt($curl, CURLOPT_COOKIEJAR, getcwd().'/cookies.txt');
  curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET');
  curl_setopt($curl, CURLOPT_TIMEOUT, 30);
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  $html = curl_exec($curl);
  curl_close ( $curl );

A: If you look at the HTML source code of what you copy pasted here, they are not the same. The second string  has an additional entities & # 8203 ; (check the second `')
http://pasteboard.co/wBd2Ea4.png


text:
Q: Using case statement with Left OUter Join in SQL I've following 2 tables
table1
Id Name deptId
==============
1  a     d1
--------------
2  b     d2
--------------
3  c     null
--------------
4  d     d1
--------------

table2
deptId   d_name
==================
d1       accounts
------------------
d2       services
------------------

I'm working on a SP where I can pass any one of 3 values for DeptName ( 'account', 'Services', 'All')
If I pass 'All' the I should be getting all records from table1 (using Left Outer Join with table2 which means I should see record 3 c null too)
For any of the other two values I should get only those records from table1 for which there exists a corresponding record in table1
I'm using following query but its not working in case of specific values for d_name ('accounts', 'services')
Select
======
t1.Id, t1.name, t2.d_name
-------------------------
from
====
table1 t1
----------
Left Outer Join
===============
table2 t2
----------
On t1.deptId = t2.deptId
------------------------
and table2.d_name =
-----------------
CASE WHEN @dname = 'All'
------------------------
    Then table2.d_name
----------------------
    Else @dname
------------------

@dname is the parameter value that Pass to the SP. currently it works for 'All' parameter but does not work for specific values('accounts' or 'services'). Not sure where am I going wrong with this


text:
Q: Force select * in postgres materialized view definition I have a Postgres database and a family of materialised views defined as clones of tables, used for testing and analysis of data so the data won't change during the testing/analysis process like:
create materialized view cloneschema.records_table as
select * from dataschema.records_table;

I would like to force the view definition to retain the select * columns, so that if the underlying schema of dataschema.records_table changes to gain additional columns then those columns also appear in cloneschema.records_table when the materialised view is refreshed.
The current state of affairs is that pg_matviews lists the SQL with only the columns present at time of materialised view creation, so if the materialised view is refreshed it holds only data for those columns.
The main goal is to ensure that additional columns are picked up in testing and analysis depending on these materialised views so they remain full copies of the tables when refreshed. A side advantage would be not needing to consciously DROP CASCADE and rebuild as in this answer.
My Postgres version is PostgreSQL 11.6 on x86_64-pc-linux-gnu, compiled by gcc (GCC) 4.9.3, 64-bit. I have consulted all questions tagged postgresql and materialized-view on Stack Overflow and DBA and haven't found a related question. I don't in fact find much discussion on the wider Internet of select * constructions in materialised view definitions in Postgres.


text:
Q: How to control WordPress image metadata (using Imagick)? In short, I'm having trouble with the WordPress Media Library image editor and how it handles metadata.
I use the Imagick PHP extension (but also tested with GD for comparison), and in all environments (localhost/dev/staging/prod), and with no other plugins installed/enabled, the below table shows what happened to image metadata (JPG & PNG/resized & original) post image upload. Photo's with native camera metadata and images processed with metadata set by Gimp and ExifTool were tested. Given the consistent results, I don't believe any metadata gremlins were a factor.
GD performed as I'd expected (I understand the filters do not work for GD).
Imagick however: 1. stripped all resized .png metadata by default. & 2. Did not change it's behavior with any of the below filters (set to either true/false - NONE of them worked).
So:
1. Why does Imagick handle PNG's differently to JPG's?
2. Why didn't any of the filter/s work? &
3. How can I make this happen? -
I specifically set XMP rights metadata (per this) on all images (.jpg/.png). When I upload them to WordPress, I would like that metadata to persist across all resized images.
Thanks in advance!
Results

Processor
JPG EXIF
JPG IPTC
JPG XMP
JPG ORIG
PNG EXIF
PNG IPTC
PNG XMP
PNG ORIG

GD Only
Stripped
Stripped
Stripped
All Kept
Stripped
Stripped
Stripped
All Kept

GD + Any Filter
Stripped
Stripped
Stripped
All Kept
Stripped
Stripped
Stripped
All Kept

Imagick Only
Kept
Kept
Kept
All Kept
Stripped
Stripped
Stripped
All Kept

Imagick + Any Filter
Kept
Kept
Kept
All Kept
Stripped
Stripped
Stripped
All Kept

Attempted Filters
// Fake variable to represent a true or false value. Not actually used in the functions.php file. Each filter attempted separately.
$value = 'true' || 'false'

// Filter 1
add_filter ('image_strip_meta', $value);

// Filter 2
add_filter ('image_strip_meta', '__return_$value');

// Filter 3
add_filter( 'image_strip_meta', function( $arg ) {
    return $value;
} );

Tested Hosts
Localhost XAMPP (LAMPP)
&
Live Web Server
WordPress 5.8
PHP 7.4.22
GD Extension
| GD Support | enabled |
| :------------: | :-----: |
| GD Version | bundled (2.1.0 compatible) |
| FreeType Support | enabled |
| FreeType Linkage | with freetype |
| FreeType Version | 2.4.8 |
| GIF Read Support | enabled |
| GIF Create Support | enabled |
| JPEG Support | enabled |
| libJPEG Version | 9 compatible |
| PNG Support | enabled |
| libPNG Version | 1.6.37 |
| WBMP Support | enabled |
| XBM Support | enabled |
| BMP Support | enabled |
| TGA Read Support | enabled  |
Imagick Extension
| imagick module | enabled |
| :------------: | :-----: |
| imagick module version | 3.5.1 |
| imagick classes | Imagick, ImagickDraw, ImagickPixel, ImagickPixelIterator, ImagickKernel |
| Imagick compiled with ImageMagick version | ImageMagick 6.9.11-60 Q16 x86_64 2021-01-25 https://imagemagick.org |
| Imagick using ImageMagick library version | ImageMagick 6.9.11-60 Q16 x86_64 2021-01-25 https://imagemagick.org |
| ImageMagick copyright | (C) 1999-2021 ImageMagick Studio LLC |
| ImageMagick release date | 2021-01-25 |
| ImageMagick number of supported formats: | 242 |
| ImageMagick supported formats | 3FR, 3G2, 3GP, AAI, AI, APNG, ART, ARW, AVI, AVS, BGR, BGRA, BGRO, BIE, BMP, BMP2, BMP3, BRF, CAL, CALS, CANVAS, CAPTION, CIN, CIP, CLIP, CMYK, CMYKA, CR2, CR3, CRW, CUR, CUT, DATA, DCM, DCR, DCX, DDS, DFONT, DNG, DOT, DPX, DXT1, DXT5, EPDF, EPI, EPS, EPS2, EPS3, EPSF, EPSI, EPT, EPT2, EPT3, ERF, FAX, FILE, FITS, FRACTAL, FTP, FTS, G3, G4, GIF, GIF87, GRADIENT, GRAY, GRAYA, GROUP4, GV, H, HALD, HDR, HISTOGRAM, HRZ, HTM, HTML, HTTP, HTTPS, ICB, ICO, ICON, IIQ, INFO, INLINE, IPL, ISOBRL, ISOBRL6, J2C, J2K, JBG, JBIG, JNG, JNX, JP2, JPC, JPE, JPEG, JPG, JPM, JPS, JPT, JSON, K25, KDC, LABEL, M2V, M4V, MAC, MAGICK, MAP, MASK, MAT, MATTE, MEF, MIFF, MKV, MNG, MONO, MOV, MP4, MPC, MPG, MRW, MSL, MSVG, MTV, MVG, NEF, NRW, NULL, ORF, OTB, OTF, PAL, PALM, PAM, PATTERN, PBM, PCD, PCDS, PCL, PCT, PCX, PDB, PDF, PDFA, PEF, PES, PFA, PFB, PFM, PGM, PGX, PICON, PICT, PIX, PJPEG, PLASMA, PNG, PNG00, PNG24, PNG32, PNG48, PNG64, PNG8, PNM, POCKETMOD, PPM, PREVIEW, PS, PS2, PS3, PSB, PSD, PTIF, PWP, RADIAL-GRADIENT, RAF, RAS, RAW, RGB, RGBA, RGBO, RGF, RLA, RLE, RMF, RW2, SCR, SCT, SFW, SGI, SHTML, SIX, SIXEL, SPARSE-COLOR, SR2, SRF, STEGANO, SUN, SVG, SVGZ, TEXT, TGA, THUMBNAIL, TIFF, TIFF64, TILE, TIM, TTC, TTF, TXT, UBRL, UBRL6, UIL, UYVY, VDA, VICAR, VID, VIDEO, VIFF, VIPS, VST, WBMP, WEBM, WEBP, WMF, WMV, WMZ, WPG, X, X3F, XBM, XC, XCF, XPM, XPS, XV, XWD, YCbCr, YCbCrA, YUV |


text:
Q: Matplotlib FuncAnimation not working in windowed application using PyQT5 I have a windowed application that, when a button is pressed, is supposed to trigger an animation of a 3d scatter plot using matplotlib. Here's my code:
from __future__ import print_function
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget, QListWidget, QPushButton, QMainWindow
from PyQt5.QtCore import QObject
from matplotlib.animation import FuncAnimation
from matplotlib import pyplot as plt

import platform
import sys
import six
import numpy as np
import mpl_toolkits.mplot3d.axes3d as p3

i = 1

def main():
    global device_app, device_listbox, device_win_conf_button, device_win
    device_app = QApplication(sys.argv)     # Initialize QApp
    device_win = QWidget()

    device_win_layout = QVBoxLayout()    # Layout

    device_win_conf_button = QPushButton("Proceed")

    device_app.aboutToQuit.connect(quit)

    device_win_conf_button.clicked.connect(plotAnimator)

    device_win_layout.addWidget(device_win_conf_button)
    device_win.setLayout(device_win_layout) # Assign layout to window and resize
    device_win.resize(500, 500)

    device_win.show()
    device_app.exec_()  # Enter loop

def plotAnimator():
    global sc_plot, x, y, z
    fig = plt.figure()  # Create matplotlib fig

    ax = fig.add_subplot(111, projection='3d')  # Add plot
    ax.set_title("Example")
    ax.set_xlim3d(-10, 10) # Set bounds
    ax.set_ylim3d(-10, 10)
    ax.set_zlim3d(-10, 10)

    x = [0]
    y = [0]
    z = [0]
    sc_plot = ax.scatter(x,y,z) # Start at 0, 0, 0
    print(2)
    animation = FuncAnimation(fig, updatePlot, frames=2, interval=100)

    plt.show()

def updatePlot(frame):
    global i

    x.append(i)
    y.append(i)
    z.append(i)
    sc_plot._offsets3d = (x, y, z)
    i += 1

main()

So when I run this and click the button, the scatter plot shows up with the single point I've initialized it with at (0, 0, 0). I can interact with the plot, rotating it around and zooming in and out, yet there's no animation. Further, the following is printed to the console when I click the "Proceed" button:
QCoreApplication::exec: The event loop is already running.
I've researched this error and from what I understand it comes from trying to execute a QApplication that's already being executed. I don't see that happening in my code. The only thing I can think of is that maybe matplotlib uses PyQT to create its windows? Even if that was the case, though, I'm having trouble thinking about how I would fix it.
Any help is greatly appreciated, thanks!


text:
Q: Storing an XML element in a string I am using the SWXMLHash to parse a XML webpage
let xml = SWXMLHash.parse(data)
println(xml["root"]["schedule"]["date"].element?.text)

This successfully prints out the element I want. However, I cannot seem to store it in a string.
I declare the string
var getXmlItem: String

And I try to set it equal to the XML element I want:
getXmlItem = xml["root"]["schedule"]["date"].element?.text

But this gives me the error:

Value of optional type 'String?' not unwrapped; did you mean to use '!' or '?'?

Is this not the way to set it equal to the XML? I am still learning Swift so this is confusing to me.

A: Swift takes a hardline between values that can be null and values that cannot be null. I thinktext is optional within the SWXMLHash framrwork. Try this:
getXmlItem = xml["root"]["schedule"]["date"].element?.text!

You need to be sure that text isn't a nil though.
An alternative is to declare getXmlItem as an optional string:
var getXmlItem : String?

What I prefer is for Swift to infer type automatically:
var getXmlItem = xml["root"]["schedule"]["date"].element?.text
// getXmlItem is now String?


text:
Q: Getting FR_3085 ERROR when working in Informatica In a lot of the task flow jobs I'm running, I constantly am getting the

FR_3085 ERROR: Row [1]: 2-th character is a null character, which is
  not allowed in a text input file

error. These occur usually in data synchronization tasks but I sometimes see this in mapping configurations as well. How do I resolve this error?

A: This error occurs when you have NULL characters in your flat file.
One way for doing this is using the OS utilities for removing the NULL characters from your flat file automatically and this will depend on what OS you're using.


text:
Q: My windows services read different registry path from a application I wrote a ConsoleApplication with C#, all its work was just call some function of dll(Dynamic Link Libarary), and Init() was one of these funcations, it will read registry path as HKEY_CURRENT_USER\Software\CompanyName\ConfigFolder, well, this ConsoleApplication run well at the moment.
However, I was told to write a same function program but in a form of windows services. OK, C#.NET writes Windows Services project conveniently. I just copied my ConsoleApplication's code and modified a litte. But the problem is that I found it would not read the former register path (HKEY_CURRENT_USER\Software\CompanyName\ConfigFolder),so  that Init() funcation doesn't work now. I want to know what is the correct registry path that a Windows Services will read.
PS: The first time my ConsoleApplication run, the registry path HKEY_CURRENT_USER\Software\CompanyName\ConfigFolder did not exist, so this Init() funcation would search a configuration file named "config.ini"  under the current path, after that, it would write that configuration into registry (HKEY_CURRENT_USER\Software\CompanyName\ConfigFolder). Howerver, when I turned my application into a Windows Services, not matter I put the config.ini into project current path or C:\Windows\System32, it all didn't work. My Operation System is Windows 7.

A: What's the error it gives? Or does it not give an error? if its about read/write access right to the registry, make sure you're running the service under LOCALSYSTEM or Administrator


text: Q: What is error when my query has an anonymous object and iteration on this in HTML What is error when my query has an anonymous object and iteration on this in HTML page by model Microsoft.CSharp.RuntimeBinder.RuntimeBinderException: ''object' does not contain a definition for 'st''


text:
Q: how to see highlighted rows that have been edited I used to see which rows are edited (compared to last commit) in visual code studio, but on my new mac, it's not there anymore. Although I have git in the folder. How do I switch this on?
UPDATE: I found out it was the extension Gitlens!

A: I don't know if you're talking about gutter highlight.
Check: Changed lines highlight in VS Code
Without a good image to show what you are talking about it's hard to know.
If it's not that, try Gitlens. If still not that, try to reinstall the Git Client. There are reports of this failing sometimes.


text:
Q: Python (rospy) to C++ (roscpp) struct.unpack I am currently translating a rospy IMU-driver to roscpp and have difficulites figuring out what this piece of code does and how I can translate it.
def ReqConfiguration(self):
    """Ask for the current configuration of the MT device.
    Assume the device is in Config state."""
    try:
        masterID, period, skipfactor, _, _, _, date, time, num, deviceID,\
                length, mode, settings =\
                struct.unpack('!IHHHHI8s8s32x32xHIHHI8x', config)
    except struct.error:
        raise MTException("could not parse configuration.")
    conf = {'output-mode': mode,
            'output-settings': settings,
            'length': length,
            'period': period,
            'skipfactor': skipfactor,
            'Master device ID': masterID,
            'date': date,
            'time': time,
            'number of devices': num,
            'device ID': deviceID}
    return conf

I have to admit that I never ever worked with neither ros nor python before.
This is no 1:1 code from the source, I removed the lines I think I know what they do, but especially the try-block is what I don't understand. I would really appreciate help, because I am under great preasure of time.
If someone is curious(context reasons): The files I have to translate are mtdevice.py , mtnode.py and mtdef.py and can be found googleing for the filesnames + the keyword ROS IMU Driver
Thanks a lot in advance.

A: This piece of code unpacks the fields of a C structure, namely  masterID, period, skipfactor, _, _, _, date, time, num, deviceID, length, mode, settings, stores those in a Python dictionary and returns that dictionary as call result. The underscores are placeholders for the parts of the struct that aren't used.
See also: https://docs.python.org/2/library/struct.html, e.g. for a description of the format string ('!IHHHHI8s8s32x32xHIHHI8x') that tells the unpack function what the struct looks like.
The syntax a, b, c, d = f () means that the function returns a thing called a tuple in Python. By assigning a tuple to multiple variables, it's split into its fields.
Example:
 t = (1, 2, 3, 4)

 a, b, c, d = t

 # At this point a == 1, b == 2, c == 3, d == 4

To replace this piece of code by C++ should not be too hard, since C++ has structs much like C. So the simplest C++ implementation of requestConfiguration would be to just return that struct. If you want to stay closer to the Python functionality, your function could put the fields of the struct into a C++ STL map and return that. The format string + the docs that the link points to, tell you what data types are in your struct and where.
Note that it's the second parameter of unpack that holds your data, the first parameter just contains information on the layout (format) of the second parameter, as explained in the link. The second parameter looks to Python as if it's a string, but it's actually a C struct. The first parameter tells Python where to find what in that struct.
So if you read the docs on format strings, you can find out the layout of your second parameter (C struct). But maybe you don't need to. It depends on the caller of your function. It may just expect the plain C struct.
From your added comments I understand that there's more code in your function than you show. The fields of the structs are assigned to attributes of a class.
If you know the field names of your C struct (config) then you can assign them directly to the attributes of your C++ class.
// Pointer 'this' isn't needed but inserted for clarity

this->mode = config.mode;
this->settings = config.settings;
this->length = config.length;

I've assumed that the field names of the config struct are indeed mode, settings, length etc. but you'd have to verify that. Probably the layout of this struct is declared in some C header file (or in the docs).

A: To do the same thing with C++, you'd declare a struct with the various parameters:
struct DeviceRecord {
    uint32_t masterId;
    uint16_t period, skipfactor, _a, _b;
    uint32_t _c;
    char date[8];
    char time[8];
    char padding[64];
    uint16_t num;
    uint32_t deviceID;
    uint16_t length, mode;
    uint32_t settings;
    char padding[8];
};

(It's possible this struct is already declared somewhere; it might also use "unsigned int" instead of "uint32_t" and "unsigned short" instead of "uint16_t", and _a, _b, _c would probably have real names.)
Once you have your struct, the question is how to get the data. That depends on where the data is. If it's in a file, you'd do something like this:
DeviceRecord rec; // An instance of the struct, whatever it's called
std::ifstream fin("yourfile.txt", std::ios::binary);
fin.read(reinterpret_cast<char*>(&rec), sizeof(rec));
// Now you can access rec.masterID etc

On the other hand, if it's somewhere in memory (ie, you have a char* or void* to it), then you just need to cast it:
void* data_source = get_data(...); // You'd get this from somewhere
DeviceRecord* rec_ptr = reinterpret_cast<DeviceRecord*>(stat_source);
// Now you can access rec_ptr->masterID etc

If you have a std::vector, you can easily get such a pointer:
std::vector<uint8_t> data_source = get_data(...); // As above
DeviceRecord* rec_ptr = reinterpret_cast<DeviceRecord*>(data_source.data());
// Now you can access rec_ptr->masterID etc, provided data_source remains in scope. You should probably also avoid modifying data_source.

There's one more issue here. The data you've received is in big-endian, but unless you have a PowerPC or other unusual processor, you're probably on a little-endian machine. So you need to do a little byte-swapping before you access the data. You can use the following function to do this.
template<typename Int>
Int swap_int(Int n) {
    if(sizeof(Int) == 2) {
        union {char c[2]; Int i;} swapper;
        swapper.i = n;
        std::swap(swapper.c[0], swapper.c[1]);
        n = swapper.i;
    } else if(sizeof(Int) == 4) {
        union {char c[4]; Int i;} swapper;
        swapper.i = n;
        std::swap(swapper.c[0], swapper.c[3]);
        std::swap(swapper.c[1], swapper.c[2]);
        n = swapper.i;
    }
    return n;
}

These return the swapped value rather than changing it in-place, so now you'd access your data with something like swap_int(rec->num). NB: The above byte-swapping code is untested; I'll try compiling it a bit later and fix it if necessary.
Without more information, I can't give you a definitive way of doing this, but perhaps this will be enough to help you work it out on your own.


text:
Q: xv-like image viewer that lets me annotate/mark images? When I'm viewing many images w/ xv (sometimes in "visual schnauzer"
mode), I sometimes want to "bookmark" or annotate a given image.
I don't think xv can do this, but is there another xv-like image
viewer that can?
Is it possible to add "programmable hot-keys" to xv so that typing
certain letters lets you call external commands (eg, "emacs (filename
of picture you are viewing)")?
I think that xv has a 'mark' feature, but that's more internal, and
the marks go away after I close xv.
I realize I could just open a text editor and make notes myself
(typing in the filename by hand or maybe using xv's "info" window),
but is there an easier way to do this?

A: I think sxiv will let you do what you want. You can modify the configuration relatively easily, including adding bindings that will execute a shell command. In particular, you might look at this fork for an example that could do what you're talking about.
I don't know, though, of any application as simple as xv that will do what you want out of the box.


text:
Q: Simple SQL question I'm try to resolve this but I don't understand?
My query
Select FirstName, City
FROM Customer
WHERE City NOT IN ('Paris')

Error

Your answer does not contain the expression <>

A: Not sure what you are using for this, but apparently it is looking for a very specific answer.  Your answer will work, but it looks like they are expecting
WHERE City <> 'Paris'

This would also be valid:
WHERE City != 'Paris'

but you would probably get the same error.


text:
Q: Is there a way to search a String of lyrics then substring out the matching phrases I need to search lyrics for a matching phrase.
For example:
I have song lyrics like these.
"She is the one that I love, I know it something something something something something she loves you and me something something something."

Given this search term below, search the lyrics for the closest match and count the characters in the sub string. My issue is finding the closest match using indexOf returns the first SHE. I need the to be able to sub string out the closes matching phrase.
The results should print :
The closest matching search for 'she loves me' is "she loves you and me".
Index Length: 20

A: I know its not the most optimized or the efficient one. But, the following code will work for most keywords.
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class KeywordSearch {

    public static void main(String[] args) {
        System.out.println(getMatchingLyrics("She is the one that I love, "
                + "I know it something something something something something "
                + "she loves you and me something something something.",
                Arrays.asList("she you".toLowerCase().split(" "))));
    }

    private static String getMatchingLyrics(String lyrics, List<String> keywords) {
        String[] lyricWords = lyrics.split(" ");

        // Split and get the word index for keyword matches
        Map<Integer, String> lyricEngine = new TreeMap<>();
        for(int i = 0; i < lyricWords.length; i++) {
            String search = lyricWords[i].toLowerCase().replaceAll("[^a-zA-Z0-9]", "");
            if (keywords.contains(search) && !lyricEngine.values().contains(lyricWords[i])) {
                lyricEngine.put(i, lyricWords[i]);
            }
        }

        Integer min = null;
        Integer max = null;
        if (lyricEngine.size() == 1) {
            return lyricEngine.values().iterator().next();
        } else if (lyricEngine.size() <= keywords.size()) {
            List<Integer> coll = new ArrayList<>(lyricEngine.keySet());
            min = coll.get(0);
            max = coll.get(lyricEngine.size() - 1);
        } else {
            // Prepare the difference between the indexes
            Map<Integer, String> set = new TreeMap<>();
            List<Integer> keys = new ArrayList<>(lyricEngine.keySet());
            for(int i=0; i <= lyricEngine.size() - keywords.size(); i++) {
                int j = i + keywords.size() - 1;
                int diff = keys.get(j);
                StringBuilder str = new StringBuilder(keys.get(j) + "");
                for (j = j - 1; j >= i; j--) {
                    diff -= keys.get(j);
                    str.append(',');
                    str.append(keys.get(j));
                }
                set.put(diff, str.toString());
            }

            // Get the value with minimum difference
            for(String s:set.get(set.keySet().toArray()[0]).split(",")) {
                int x = Integer.parseInt(s);
                if (min == null && max == null) {
                    max = x;
                    min = x;
                } else {
                    if (x > max) {
                        max = x;
                    } else if (x < min) {
                        min = x;
                    }
                }
            }
        }

        // Build the string from indexes
        StringBuilder s = new StringBuilder();
        for (int i = min; i <= max; i++) {
            s.append(lyricWords[i]);
            if (i < max) {
                s.append(" ");
            }
        }
        return s.toString();
    }
}

You can build and optimize it as per your need. Explanations are given as comments. If you have any doubt, feel free to ask me in DM or comments.
For different keywords,
Keyword: she loves me
Output: she loves you and me

Keyword: I love it
Output: I love, I know it

Keyword: she is one love
Output: She is the one that I love,

A: You could implement your own sophisticated algorithm in Java because in JDK we don't have an appropriate solution out of the box. But in Java world are a lot of suitable solution you could try to solve your issue by using Apache Lucene.


text:
Q: How to set field to null on doctrine migrations using addSql? I'm updating an entity in one of my doctrine migrations with Doctrine\DBAL\Migrations\AbstractMigration::addSql($sql, array $params = array(), array $types = array()), I have to set up a column as null.
I have already debugged it and I tried to set up the type as \PDO::PARAM_NULL but I'm getting the same issue.
SQL:
    $sql="INSERT INTO sme_task_template (status_change_final_status) VALUES (:finalStatus)";
    $params=array(
        'finalStatus' => null
    );
    $types=array(
        'finalStatus' => \PDO::PARAM_NULL
    );
    $this->addSql($sql, $params, $types);

Exception:
  [Doctrine\DBAL\DBALException]
  An exception occurred while executing 'INSERT INTO sme_task_template (statu
  s_change_final_status) VALUES (:finalStatus)' with params [null]:
  Value for :finalStatus not found in params array. Params array key should b
  e "finalStatus"

Does anyone know how to solve this?
Thanks

A: I can't get it working with named parameters but it seems to work with question mark parameters.
    $sql="INSERT INTO sme_task_template_trigger (status_change_final_status) VALUES (?)";
    $params=array(
        null
    );
    $types=array(
        \PDO::PARAM_NULL
    );
    $this->addSql($sql, $params, $types);


text:
Q: Displaying JSON data on front-end using fetch So really new to React here, and I want to make a simple search box, where the user submits a "question" and the JSON returns the values of "results".
The request goes through and I get a response, only thing I can't find is taking the results from it and displaying them on the front end.
class Search extends Component {
    state = {
      searchValue: "",
      searchSection: "",
      results: [],
      // section: []
    };

    handleOnChange = event => {
      this.setState({ searchValue: event.target.value });
    };

    handleSearch = () => {
      this.makeApiCall(this.state.searchValue);
    };

    makeApiCall() {
      fetch("http://example.com/json", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: (this.state.searchValue),
            section: (this.state.searchSection),
        })
    })

        .then((response) => response.json())

        .then((responseData) => {
          console.log(
            "POST Response",
            "Response Body -> " + JSON.stringify(responseData)
          )
            return responseData
        })
      .then(results => this.setState({results: results.value}))
    };

    render() {
      return (

              Ask a question

          <input
            name="text"
            type="text"
            placeholder=""
            onChange={event => this.handleOnChange(event)}
            value={this.state.searchValue}
            className="shadow-sm appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline"
          />
          <button onClick={this.handleSearch} className="cursor-pointer mt-5 bg-white hover:bg-gray-100 text-gray-800 font-semibold py-2 px-4 border border-gray-400 rounded-full shadow">Search</button>

          // DISPLAYING THEM ON THE FRONT HERE
          {this.state.results ? (

              {this.state.results.map((result) => (

{result.title}

{result.sentences}

              ))}

          ) : (

Can't find results for your question

          )}

      );
    }
  }

  export default Search;

My JSON is like:
{
  "request": {
    "date_from": "",
    "date_to": "",
    "question": "User question here",
    "section": null
  },
  "results": {
    "docs": [
      {
      "title": " "
      "section": " "
   }
  ]
 }
}

And I need to display multiple questions from the JSON

A: In makeApiCall, change results.value to results.docs as your JSON has docs property which has all the data you want to display.
makeApiCall() {
      fetch("http://example.com/json", {
        method: 'POST',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            question: (this.state.searchValue),
            section: (this.state.searchSection),
        })
    })

        .then((response) => response.json())
        .then((responseData) => {
          console.log(
            "POST Response",
            "Response Body -> " + JSON.stringify(responseData)
          )
            return responseData
        })
      .then(results => {
          this.setState({
           results: results.docs
          },()=>console.log(this.state))
      })
    };

A: So, with the help of Sarthak Aggarwal and Bamuleseyo Gideon (thanks Gideon) I found the solution to this.
The actual problem was that I was not targeting the correct property Sarthak said. But also results.docswas wrong.
So, instead of
.then(results => this.setState({results: results.value}))
I changed it to
  .then(jsonData => {
    this.setState({ docs: jsonData.results.docs });
  });
``

and it works like a charm :)


text:
Q: Behavior of lower_bound in cpp on unsorted array I wanted to ask how lower_bound in cpp ( C++ )  behaves when it is applied on unsorted array.
I mean when I ran the following program.
#include <iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
    int arr[]={8,9,10,1,2,3};
    auto itr= lower_bound(arr,arr+6,7);
    cout<<*itr<<endl;
}

it gave the output as '2'. But according to definition of lower_bound, it gives the iterator to first element which fails '<' with 'val'. So according to this definition, shouldn't the answer be '8', because "8 is not less than 7". I know it works on sorted array, but I want to know whether or not, there is a logic behind this value or is it a junk.
Thanks.

A: Since the precondition of supplying a sorted array has been violated, the behavior is undefined. Your code demonstrates undefined behavior twice: first, when you pass an unordered array to lower_bound, and second, when you dereference iter without comparing it to arr+6 first.
It is easy to see what is going on, though: the algorithm behind lower_bound is a basic binary search. You give the algorithm an array, it divides them in two halves, and checks the item in the middle. You supplied an even number of items, there are two numbers that can be considered "being in the middle" - 10 and 1. It looks like the algorithm picked 1, compared it to your search item 7, and continued search in the upper half of the array, checks 2 and 3, and finally returns the pointer pointing past the end of the array.
When you dereference that pointer, you get junk; unfortunately, it happens to match one of the elements of your array, i.e. 2, leading you to a wrong conclusion.
Change your code as follows to see what is actually returned:
int arr[]={8,9,10,1,2,3, -1};

Now dereferencing the element at index 6 is valid; your code should probably print -1 (although this is an exploit of undefined behavior specific to your particular system, and it is not guaranteed to produce the same results on other systems).


text:
Q: What is the difference between the Java Associate exam and the Java Programmer exam In the next 6 months I will have to take one of the above exams to pass part of my course and I have been studying Java for the last 2 years in school and was wondering is there a huge difference between the 2 exams, Would I be better to just do the programmer exam and bypass the associate exam or is there a huge step up in skill from the associate exam.
Thanks

A: The Java Associate exam is more broad. It is targeted towards new developers coming out college, or developers switching languages. The Java Programmer exam goes more in depth. You need to know more of the finer points of the language and the language specification. It is targeted toward people with some experience.
I recommend taking a look at the following threads in the Java Ranch certification sub-forums. They go into some detail about the difference between the exams.

*

*Which certification to start with: SCJA or SCJP?

*Some questions about Java SE 7 OCA and OCP
Given your situation, the Associates exam is probably the better place to start.


text:
Q: How to export Firestore when offline persistence is activated? I have been using Firebase in a ReactJS framework. I have setup a config.js where I initialize Firebase and export my firestore instance and all works fine now:
export const store = firebase.firestore();

I'm trying to enable offline persistence but how should I export my store variable now?
firebase.firestore().enablePersistence()
  .then(function() {
      // Initialize Cloud Firestore through firebase
      var store = firebase.firestore();
  })
  .catch(function(err) {
      if (err.code == 'failed-precondition') {
          // Multiple tabs open, persistence can only be enabled
          // in one tab at a a time.
          // ...
      } else if (err.code == 'unimplemented') {
          // The current browser does not support all of the
          // features required to enable persistence
          // ...
      }
  });

I was trying to export the promise but it does not work. Any recommendations?

A: since they changed the behavior and there is no correct way told to us, i did this:
firestore.js:
import firebase from 'firebase'
import 'firebase/firestore'

export var db = firebase.firestore()
const settings = { timestampsInSnapshots: true }
db.settings(settings)

export function initializeDatabase() {
    return new Promise((resolve, _) => {
        firebase.firestore().enablePersistence({experimentalTabSynchronization:true})
        .then(function() {

            //update the database variable to reflect the one with persistenceEnabled
            db = firebase.firestore();

            resolve()
          })
          .catch(function(err) {
            if (err.code == 'failed-precondition') {
                // Multiple tabs open, persistence can only be enabled
                // in one tab at a a time.
                // ...
            } else if (err.code == 'unimplemented') {
                // The current browser does not support all of the
                // features required to enable persistence
                // ...
            }

            //Nothing to do, it was previsoly initilaized in the var db
            resolve()
          });
})
}

now in the main.js, you should call the method that initialize the database
main.js:
let app;

initializeDatabase().then(function() {
  initializeSecureApp()
})

function initializeSecureApp() {
  if(!app) {
    app = new Vue({
      router,
      store,
      render: h => h(App)
    }).$mount('#app');

    // defaultListeners()
  }
}

ps: im kind of noob, but thats the only way i found that is working to only start the app after the persistence database is setted
ps: sorry if the question is old, but i had this problem today and had to search for it
ps: you can implement reject instead of _ and update the call to the initializeDatabase to handle the error
if someone has a better way, please post here


text:
Q: Restore site collection permission setting In my SharePoint site collection (SharePoint Online), i mistakenly executed below code and it has messed up all the permissions, how to restore default set of permissions ?
   var web = context.get_web();
   if (!web.get_hasUniqueRoleAssignments()) {
         web.breakRoleInheritance(true, false);
    }

A: You can reset the role inheritance by using this code below :
var web = context.get_web();
   if (web.get_hasUniqueRoleAssignments()) {
         web.resetRoleInheritance();
    }


text:
Q: Cannot build atmel studio 6.2 project with printf command I am new to Atmel Studio. I created new GCC C Execute project with ATSAMV71Q21 device. In main.c file added printf then run build and got bunch of "undefined reference to (_write, _fsta, etc) error. I tried Atmel "getting-started" example and it worked fine. How can I fix this problem? Below are the code and error message. Thanks for help.
#include "sam.h"
#include <stdio.h>
#include <stdbool.h>

int main(void)
{
    /* Initialize the SAM system */
    SystemInit();

    while (1)
    {
        printf("abc");
        //TODO:: Please write your application code
    }
}

d:/atmel/atmel toolchain/arm gcc/native/4.8.1443/arm-gnu-toolchain/bin/../lib/gcc/arm-none-eabi/4.8.4/../../../../arm-none-eabi/lib/armv7e-m\libc.a(lib_a-sbrkr.o): In function '_sbrk_r':
  D:\Atmel\samv71_softpack_1.4_for_astudio_6_2\studio\Atmel\samv71_Xplained_Ultra\examples\test\test\Debug\sbrkr.c(1,1): error: undefined reference to '_sbrk'

A: I don't yet know how to do what you want with a bare-bones C-program (#include "sam.h"), but I can help you if you are willing to use the ASF API.
You have to generate a C-ASF-project first. Then you add Standard Serial I/O to your project using the ASF wizard. Configure properly, and printf, puts, ... will print to a terminal program that is connected to the controller.
#include <asf.h>
#include "stdio_serial.h"

static void configure_console(void)
{
    const usart_serial_options_t uart_serial_options = {
        .baudrate = CONF_UART_BAUDRATE,
        .paritytype = CONF_UART_PARIT
    };

    /* Configure console UART. */
    sysclk_enable_peripheral_clock(CONSOLE_UART_ID);
    stdio_serial_init(CONF_UART, &uart_serial_options);
}

int main(void)
{
    /* Insert system clock initialization code here (sysclk_init()). */
    sysclk_init();
    board_init();

    configure_console();

    while (1) {
        printf("abc");
    }

    return 0;
}

This works on an Arduino Due which has a SAM3X8E controller.

A: If you just want to fix that link error, then you can add Standard serial I/O by going to the Project->ASF Wizard and scrolling down to Standard serial I/O and clicking add.
While this will fix the linker error, it probably is not going to do what you expect.  Where are you trying to print to?  Is there a display connected to your embedded device?  Then you'll need to use a specific driver for that display and its associated api.
If you're just using printf() for debugging purposes while connected to your pc, then I recommend using the atmel debugger to follow the code execution, inspect variables, etc.


text:
Q: Correspondence between summands of a module and primitive idempotents of the endomorphism ring of the module I am reading this paper and have the following questions.
Let $A$ be a finite-dimensional algebra over a fixed field $k$.
Let the finitely-generated $A$-module $M$ be a generator–cogenerator for $A$, which means that all projective indecomposable $A$-modules and all injective indecomposable $A$-modules occur
as direct summands of $M$.
On page 3 in the paper it says
"The identity of $End_A(M)$ is the sum of the "identity maps" on the indecomposable direct
summands of $M$. Hence we have primitive idempotents of $End_A(M)$ corresponding
to the summands of $M$. For any indecomposable summand $T$ of $M$ we denote the corresponding
simple $End_A(M)$-module by $E_T$".
My questions are:

*

*How can I prove this correspondence and

*Why is $E_T$ simple?.

I would be grateful for references concerning literature or every other kinds of hints.
Thank you very much.