text:
Q: Get response stream convert it to ASCII This code snippet is sending some values to an SMS gateway.  Then the SMS gateway gives us some values.  I need to catch that value and write it to a file.
When I send a SMS this value shown:

b6c56c74-03b0-11e2-b28c-00145e7e986e

WebRequest request = WebRequest.Create(
    "http://base.mygateway.com/api/mt?msisdn=" + mobileNo
    + "&body=" + msgOut
    + "&sender=" + shortcode
    + "&key=abcdefghi&product_id=10023&operator="
    + oppp + "&country=UnitedStates");
WebResponse response = request.GetResponse();
byte[] ary = new byte[1000];
response.GetResponseStream().Read(ary, 0, (int) response.ContentLength);

I wanted to convert to ASCII value that comes from GetResponseStream(). I have no idea how to do that. In the above code I take the values... how do I convert them?

A: Use the Encoding class to convert a byte[] to the wanted encoding.
Encoding.ASCII.GetString(ary);

You will want to ensure that the values returned from the WebRequest are correctly encoded as well. For this purpose you may want to use WebClient instead, as it has an Encoding property.

A: var content = new StreamReader(response.GetResponseStream(),Encoding.UTF8)
                 .ReadToEnd();


text:
Q: Crawlspider SgmlLinkExtractor allow parameter The allow parameter in the SgmlLinkExtractor method accepts a regex string correct?
I'm trying to follow html links with "/insertsomephrase/" in the address, which then follows a link with "/insertsomeotherphrase/" to be parsed. How does one do this in regex?
I'm confused as to how regex would do this since it seems the regex code acts on a string instead of an html element.
Thanks for your help.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Ms Access: How can I take the average of a column but ignore the rows where another column is 0? I have 2 columns, qty_req and qty_issued in a report. I need to find the average of the values in the qty_issued column. The problem is that sometimes the corresponding value of qty_req is 0. I need to take the average of the qty_issued column for only the rows where qty_req is NOT 0. How do I do this?
Spun off from my other question here: MS Access: How can I average a list of quantities on a report where the quantities are not zero?

A: If you want to do that in the Control Source of a text box on your report, you can take advantage of the fact that Avg() ignores Null values.
So, when qty_req <> 0, include qty_issued among the values which are averaged.  Otherwise use Null instead of the qty_issued value.
=Avg(IIf(qty_req <> 0, qty_issued, Null))

If you want to do it in a query instead ...
SELECT Avg(IIf(qty_req <> 0, qty_issued, Null)) FROM YourTable;

A: You would set the criteria in the query to not look at the qty_req that is 0:
SELECT Avg(MyTable.qty_issued) AS Avg_Issued
FROM MyTable
GROUP BY MyTable.qty_req
HAVING MyTable.qty_req <> 0;


text:
Q: Como consigo disparar o onclick clique nessa função com firebase? Preciso disparar a verificação no DB por um input. Alguém consegue me ajudar?
Vi algumas duvidas parecidas aqui mas não consegui resolver.

var firebaseConfig = {
    apiKey: "AIzaSyBd-oV4iz3VnEL41DnNQrXcaQAKT4hPRU0",
    authDomain: "suvs-e02e4.firebaseapp.com",
    databaseURL: "https://suvs-e02e4.firebaseio.com",
    projectId: "suvs-e02e4",
    storageBucket: "suvs-e02e4.appspot.com",
    messagingSenderId: "156256669497",
    appId: "1:156256669497:web:a618f3f479291792e1a2e8"
};

document.getElementById('disp').onclick = () => {
  firebase.initializeApp(firebaseConfig);

  let SSO = document.getElementById('inputSso').value
  let db = firebase.firestore();
  let docRef = db.collection("SSOs").doc("NvZDEAmhG2Usyu2UW4Om")

  docRef.get().then((doc) => {
    let SSOs = doc.data().Ssos;
    let Arsso = SSOs;
    Arsso.includes(SSO) ? alert ("TEM") : alert("não tem")
  })
}

  <input type="text" class="form-control" id="inputSso" placeholder="SSO">

<button type="submit" class="btn btn-primary mb-2" id="disp">Checar</button>

A: Aparentemente só é necessário colocar o initializeApp do firebase FORA do onclick. Como você não incluiu mensagens de erro ou mais informações, presumo que o resto esteja correto e o firebase tenha sido adicionado à sua página. Segue código com as alterações (e funcionando).

var firebaseConfig = {
    apiKey: "AIzaSyBd-oV4iz3VnEL41DnNQrXcaQAKT4hPRU0",
    authDomain: "suvs-e02e4.firebaseapp.com",
    databaseURL: "https://suvs-e02e4.firebaseio.com",
    projectId: "suvs-e02e4",
    storageBucket: "suvs-e02e4.appspot.com",
    messagingSenderId: "156256669497",
    appId: "1:156256669497:web:a618f3f479291792e1a2e8"
};

firebase.initializeApp(firebaseConfig);

document.getElementById('disp').onclick = () => {
  let SSO = document.getElementById('inputSso').value

  let db = firebase.firestore();
  let docRef = db.collection("SSOs").doc("NvZDEAmhG2Usyu2UW4Om");
  docRef.get()
    .then((doc) =>
    {
      let SSOs = doc.data().Ssos;
      document.getElementById('resultado').innerHTML = SSOs;
      SSOs.includes(SSO) ? alert("TEM") : alert("não tem");
    });
}

  <input type="text" class="form-control" id="inputSso" placeholder="SSO">

<button type="submit" class="btn btn-primary mb-2" id="disp">Checar</button>

PS: note que a linha let Arsso =SSOs; foi removida, uma vez que era desnecessária.


text:
Q: JavaScript - ReferenceError: event is not defined on addEventListener() I keep getting this error when I try to load an HTML doc I'm working on: ReferenceError: event is not defined. It points to the addEventListener() line in the javascript of the document. I am trying to AVOID jQuery if at all possible. Hence my use of document.getElementsByClassName().addEventListener() instead of $(".className").click().
Furthermore, I would also like confirmation to this question:

*

*Is addEventListener() a valid method to call from getElementsByClassName(), or...

*Will I need to use the forEach() method to attach the addEventListener() method to each element object one at a time?

Relevant Javascript (very incomplete because it is supposed to make some major divs appear/disappear, and I'm implementing that functionality dead last after all content has been added to the page):
document.getElementsByClassName("NavbarButton").addEventListener(
    "click",
    JumpToSection(event.target.innerHTML)
);

function JumpToSection(Section)
{
    /*
        TO DO:
        Figure out how to toggle visibility of main sections
        The selected section needs to have visibility turned on & all others turned off
        May be doable with a loop and an if-else statement
    */

    // Set the URL to include the viewed section ONLY IF the function's input parameter is NOT BLANK
    // EXTREMELY optimized solution found here:
    // http://stackoverflow.com/questions/154059/how-do-you-check-for-an-empty-string-in-javascript
    if(!!Section) location.hash = Section;

    // Make sure the page is scrolled to the top
    window.scrollTo(0,0);

    // To be used a bit later on for looping through the sections & toggling visibility
    var AllSections = document.getElementsByClassName("Section");
}

And the bit of HTML where I'm trying to add the event listeners (right now, I'm testing on only one of the Navbar buttons; once it works I can remove the onclick="" attributes from the others):

Calyo Delphi

IMAGES

DETAILS

FORMS

STATS

I have searched other questions similar to this here on SO, but it seems like I've already passed the event into the called function like I should be doing...? So I don't know what I've missed...

A: In javascript you have to attach event to every node return by getElementsByClassName
Like this
var classes=document.getElementsByClassName("NavbarButton");

for(var i=0;i<classes.length;i++)
    classes[i].addEventListener('click', JumpToSection);

function JumpToSection(event){
  console.log(event.target.innerHTML);
}


text:
Q: Apply infinite scroll to JSON array in ionic-3 app How can I implement infinite scroll to my JSON array? I want to display only 5 items initially.
data:[
0: Object { id: 123, title: "New family member Khjkjh has joined mymily", mm_family_id: 122, … }
1: Object { id: 124, title: "New family member Hey Dau has joined mymily", mm_family_id: 122, … }
2: Object { id: 125, title: "New family member Hey Dau has joined mymily", mm_family_id: 122, … }
3: Object { id: 126, title: "New family member New Dau has joined mymily", mm_family_id: 122, … }
4: Object { id: 127, title: "New family member New Dau has joined mymily", mm_family_id: 122, … }
5: Object { id: 128, title: "New family member New Dau has joined mymily", mm_family_id: 122, … }
6: Object { id: 129, title: "New family member New Dau has joined mymily", mm_family_id: 122, … }
7: Object { id: 130, title: "Abhishek Pandey has commented on post", mm_family_id: 122, … }
8: Object { id: 131, title: "Abhishek Pandey has commented on post", mm_family_id: 122, … }
]

Ionic info
@ionic/cli-utils  : 1.19.1
ionic (Ionic CLI) : 3.19.1

global packages:
cordova (Cordova CLI) : not installed

local packages:
@ionic/app-scripts : 3.1.8
Cordova Platforms  : android 7.0.0 browser 5.0.3
Ionic Framework    : ionic-angular 3.9.2

System:
Node : v8.7.0
npm  : 5.6.0
OS   : Windows 10

A: You can use the slice pipe with your ngFor. (Credits to https://forum.ionicframework.com/t/how-to-implement-ionic-infinite-scroll-to-show-my-array-data/96860/5)
<ion-list>
  <ion-item *ngFor="let i of items  | slice:0:slice">
    your code here
  </ion-item>
</ion-list>

<ion-infinite-scroll threshold="100px" (ionInfinite)="doInfinite($event)">
  <ion-infinite-scroll-content loadingSpinner="bubbles" loadingText="Loading more data...">
  </ion-infinite-scroll-content>
</ion-infinite-scroll>

in your .ts file:
slice: number = 5;
doInfinite(infiniteScroll) {
 setTimeout(() => {
  this.slice += 5;
  infiniteScroll.complete();
 }, 300);
}

In the first iteration, you will show the first 5 items (slice = 5). When doInfinite is called, your slice increases its value in 5, so you will show 10 items.
Hope it helps you!

A: You can implement infinite scroll feature of ionic and can initialize your items array inside constructor with the number of items you want to display at first in your case 5 items at start so you can do this:
your html:
<ion-content>
 <ion-list>
   <ion-item *ngFor="let i of items">{{i}}</ion-item>
 </ion-list>

 <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
   <ion-infinite-scroll-content></ion-infinite-scroll-content>
 </ion-infinite-scroll>
</ion-content>

in your ts:
items = [];
count: number = 0;

constructor() {
  for (let i = 0; i < 5; i++) {  // here you can limit the items according to your needs.
    this.items.push(data[this.count]);   // your JSON data which you want to display
    this.count++ //i am using a count variable to keep track of inserted records to avoid inserting duplicate records on infinite scroll
  }
}

doInfinite(infiniteScroll) {
  setTimeout(() => {
    for (let i = 0; i < 5; i++) {
      this.items.push(data[this.count]); // this will start pushing next 5 items
      this.count++
    }

    infiniteScroll.complete();
  }, 500);
}


text:
Q: Editing detail entities via redux-form: multiple forms or re-use same form? Given that I am using redux-form, consider this rather basic CRUD example. I have a list of Customers on a page. There is an edit button on each entry in the list. Clicking on the edit button navigates to a new page (via react router) which has a form in it to edit and submit updates to the server.
Given the above example, should I have a single form and keep reinitializing values to the new customer each time it is navigated to (via  different customer ID prop) ? Or, should there be multiple redux-forms (ie: multiple redux-form states) for each potential customer id?
So my state could look like if it were to re-use the same form state. It would keep reseting to latest values each time the component which shows the form mounts. So they click to edit customer 2, load customer 2 into this form state. They later click to edit customer 3, overwrite customer 2 with customer 3's intitialValues:
 {
  ...
  customerForm: {...redux-form-stuff...}
 }

... Or, I suppose it could create a new form state for each customer id. With no overwriting. But it would have to dynamically create new form states on the fly (not even sure how to do that, I'm new to reactjs). But it would allow it to keep the original values between page navigation.
 {
  ...
  customerForm2: {...redux-form-stuff...}
  customerForm3: {...redux-form-stuff...}
  customerForm4: {...redux-form-stuff...}
  customerForm5: {...redux-form-stuff...}
  ...and so on...
 }

A: The best practice here is to only have one form type as far as redux-form is concerned. So you would have your CustomerForm component that is connected to redux-form and then like you said each time it is loaded you pipe-in the initial values from the state tree.
Since you will only ever be showing one form at a time, there isn't really reason to keep around all the different form states in memory, especially if the initial values are just values derived from state.


text:
Q: Does colour/reflectivity affect equilibrium temperature in a vacuum? I take two objects, identical save for their surface colour, and place them in orbit around the sun (at equal radius of orbit). One has a very shiny/reflective surface, while one has a very matt/dark surface.
Can I say that these two objects will end up at the same temperature? My gut says yes, but I can't quite work out how to extend the reasoning from the situation of two objects in thermal equilibrium with each other (where colour/reflectivity cannot matter as they must reach the same temperature by 2nd law) to this scenario where they are emitting and absorbing at different wavelengths.
Thanks in advance.

A: The objects can equilibrate at different temperatures because the environment that you describe is not a uniform temperature.
While orbiting the sun, the object can "see" in one direction something that is ~3K and in another direction can see something that is ~3000K.
The object will exchange radiation with each, coming to an equilibrium temperature that is somewhere between the two.  By changing the efficiency of the exchange with one or the other, it can shift where the equilibrium point falls.
If you instead place it in an oven with a uniform temperature, then it will equilibrate at that temperature, regardless of the materials.

A: For any surface, the absorption and emission coefficient is the same at a given wavelength. You didn't specify whether your two surfaces were "equally grey" (that is, the reflectivity was constant for all wavelengths, just a different value) or "colored" (that is, one might be blue, and have low emissivity in the IR, while the other is white).
I believe that difference matters. In atmospheric science, we recognize albedo (the fraction of incident light reflected) and emissivity (the fraction of black body radiation emitted). When you have zero albedo and 100% emissivity, the equilibrium temperature of the object will be that of a black body in space. But if the albedo is high the object will be cooler than that; and if the emissivity is low, the object may be hotter. The equation (see this answer to see the derivation) is
$$T_o = T_S \sqrt{ \frac{ R_S \sqrt{\frac{1-\alpha}{\overline{\epsilon}}} }{2 D_{o-s} } }$$
Where I use the subscript $_o$ for the object and $_s$ for the sun.
 $R_s$ is the radius of the sun, $D$ is the distance from the (center of the) sun, $\alpha$ is the albedo (properly averaged over the wavelengths of incident light),  $\epsilon$ the emissivity (again, properly averaged over the wavelengths of the emitted light - by the Wien displacement law we know the emitted wavelength will be longer because the object is cooler than the sun; so in general $(1-\alpha) \ne \epsilon$ and the object's equilibrium temperature depends on both of these.
Now if the object is "uniformly gray" (whether $(1-\alpha)=\epsilon=0.9$ or $(1-\alpha)=\epsilon=0.1$), the result will be the same. So a black body, a grey body, and a white body, will all reach the same equilibrium temperature. But a "blue body" might not.


text:
Q: Apollo breaks when a client is stated in a mutation I am using this recent feature of adding multiple clients and it is working well so far, but only in this case, the following code breaks when I state the client explicitly in the options of my mutation. I have followed this exact pattern with other components and haven't had any issue.
import { gql } from 'react-apollo';
const networkInterfaceAccounts = createNetworkInterface({
  uri: ACCOUNTS_CLIENT_URL,
});

networkInterfaceAccounts.use([authMiddleware]);

const apolloClientAccounts = new ApolloClient({
  networkInterface: networkInterfaceAccounts,
  reduxRootSelector: state => state.apolloAccounts,
});

export const signupRequestMutation = gql`
  mutation signupRequest($username: String!, $fname: String!, $lname: String!) {
    signupRequest(username: $username, firstName: $fname, lastName: $lname) {
      _id
    }
  }
`;

export const signupRequestOptions = {
  options: () => ({
    client: apolloClientAccounts,
  }),
  props: ({ mutate }) => ({
    signupRequest: ({ username, fname, lname }) => {
      return mutate({
        variables: {
          username,
          fname,
          lname,
        },
      });
    },
  }),
};

And the react component looks like this:
export default compose(
  graphql(signupRequestMutation, signupRequestOptions),
  withRouter,
  reduxForm({
    form: 'signup',
    validate,
  }),
)(SignupForm);

Intended outcome:
As with other components, I expect that the mutation works whether I pass client as an option or not.
  options: () => ({
    client: apolloClientAccounts,
  }),

Actual outcome:
I am getting this error:
Uncaught Error: The operation 'signupRequest' wrapping 'withRouter(ReduxForm)' is expecting a variable: 'username' but it was not found in the props passed to 'Apollo(withRouter(ReduxForm))'

After that, I can submit the form.
Version
apollo-client@1.9.1
react-apollo@1.4.15


text:
Q: Parsing json array with sub objects I want to parse this jason into java code for an android app:
{
"name":"London",
"coord":{"lon":-0.12574,"lat":51.50853},
"country":"GB",
"cnt":6,
"list":[{
         "dt":1377345600,
         "temp":{
                   "min":290.42,
                   "max":294.3,
                   "weather":[{
                                 "id":501,
                                 "main":"Rain",
                                 "icon":"10d"}],
        {
         "dt":1377432000,
         "temp":{
                   "min":289.81,
                   "max":296.92,
                   "weather":[{
                                 "id":800,
                                 "main":"Clear",
                                 "icon":"01d"}],}

How can i do this? i know how to parse single object arrays, but how do subobjects work?
Here is the Complete json file.
Validated in jsonlint.com
{
"cod": "200",
"message": 0.012,
"city": {
    "id": 2643743,
    "name": "London",
    "coord": {
        "lon": -0.12574,
        "lat": 51.50853
    },
    "country": "GB",
    "population": 1000000
},
"cnt": 6,
"list": [
    {
        "dt": 1377345600,
        "temp": {
            "day": 293.39,
            "min": 290.42,
            "max": 294.3,
            "night": 290.67,
            "eve": 292.47,
            "morn": 290.42
        },
        "pressure": 1013.85,
        "humidity": 83,
        "weather": [
            {
                "id": 501,
                "main": "Rain",
                "description": "moderate rain",
                "icon": "10d"
            }
        ],
        "speed": 1.36,
        "deg": 276,
        "clouds": 100,
        "rain": 4
    },
    {
        "dt": 1377432000,
        "temp": {
            "day": 295.53,
            "min": 289.81,
            "max": 296.92,
            "night": 289.81,
            "eve": 295.44,
            "morn": 289.83
        },
        "pressure": 1019.06,
        "humidity": 73,
        "weather": [
            {
                "id": 800,
                "main": "Clear",
                "description": "sky is clear",
                "icon": "01d"
            }
        ],
        "speed": 3.36,
        "deg": 342,
        "clouds": 0
    },
    {
        "dt": 1377518400,
        "temp": {
            "day": 296.03,
            "min": 286.39,
            "max": 296.64,
            "night": 286.85,
            "eve": 295.04,
            "morn": 286.39
        },
        "pressure": 1024.06,
        "humidity": 65,
        "weather": [
            {
                "id": 800,
                "main": "Clear",
                "description": "sky is clear",
                "icon": "01d"
            }
        ],
        "speed": 2.06,
        "deg": 32,
        "clouds": 0
    },
    {
        "dt": 1377604800,
        "temp": {
            "day": 296.46,
            "min": 284.3,
            "max": 296.82,
            "night": 289.19,
            "eve": 293.97,
            "morn": 284.3
        },
        "pressure": 1026.11,
        "humidity": 57,
        "weather": [
            {
                "id": 500,
                "main": "Rain",
                "description": "light rain",
                "icon": "10d"
            }
        ],
        "speed": 1.5,
        "deg": 226,
        "clouds": 12,
        "rain": 2
    },
    {
        "dt": 1377691200,
        "temp": {
            "day": 293.48,
            "min": 287.45,
            "max": 294.79,
            "night": 291.74,
            "eve": 293.88,
            "morn": 287.45
        },
        "pressure": 1031.75,
        "humidity": 70,
        "weather": [
            {
                "id": 802,
                "main": "Clouds",
                "description": "scattered clouds",
                "icon": "03d"
            }
        ],
        "speed": 2,
        "deg": 40,
        "clouds": 32
    },
    {
        "dt": 1377777600,
        "temp": {
            "day": 295.06,
            "min": 282.71,
            "max": 295.06,
            "night": 291.28,
            "eve": 295.06,
            "morn": 282.71
        },
        "pressure": 1030.87,
        "humidity": 0,
        "weather": [
            {
                "id": 500,
                "main": "Rain",
                "description": "light rain",
                "icon": "10d"
            }
        ],
        "speed": 6.03,
        "deg": 315,
        "clouds": 62
    }
]

}

A: User this method to iterate json dynamically
private void parseJson(JSONObject data) {

        if (data != null) {
            Iterator<String> it = data.keys();
            while (it.hasNext()) {
                String key = it.next();

                try {
                    if (data.get(key) instanceof JSONArray) {
                        JSONArray arry = data.getJSONArray(key);
                        int size = arry.length();
                        for (int i = 0; i < size; i++) {
                            parseJson(arry.getJSONObject(i));
                        }
                    } else if (data.get(key) instanceof JSONObject) {
                        parseJson(data.getJSONObject(key));
                    } else {
                        System.out.println("" + key + " : " + data.optString(key));
                    }
                } catch (Throwable e) {
                    System.out.println("" + key + " : " + data.optString(key));
                    e.printStackTrace();

                }
            }
        }
    }

A: It should be like this
 {
   "name":"London",
   "coord":{"lon":-0.12574,"lat":51.50853},
   "country":"GB",
   "cnt":6,
   "list":[{
     "dt":1377345600,
     "temp":{
               "min":290.42,
               "max":294.3,
               "weather":[{
                             "id":501,
                             "main":"Rain",
                             "icon":"10d"}]
            }
    },
    {
     "dt":1377432000,
     "temp":{
               "min":289.81,
               "max":296.92,
               "weather":[{
                             "id":800,
                             "main":"Clear",
                             "icon":"01d"}]
    }
 }]
}

You forget to add parenthesis and commas.
You can refer this
http://json.parser.online.fr/

A: You can use json-simple. Refer to http://code.google.com/p/json-simple/


text:
Q: UNET Confusion with Authority and NetworkIdentity I have developed a game in unity it is a Carrom game (similar to snooker). I am trying to make it multiplayer using UNET HLAPI but I am stuck. I cant understand what should be the correct way to do this I am using a server authoritative model and used the striker as the player prefab but Whenever I strike the pieces move at the client side but not the server side. I tried sending a command to the server but than it does't collide with the pieces nor does it update on the client. So I wanted to know what should the the way to go?
Do I keep the striker as a player  prefab? and if not how does a player move it to take strike and what should i do at the pieces. Current all of them have a networkidentity and transform. I thought of assigning client authority on each turn but it does not remain server authoritative.


text:
Q: Как постоянно менять значение переменной в функции при нажатии кнопки? python tkinter переменная fond прибавляет к себе единицу в функции Ircutsk.
fond = 0

def Ircutsk(fond):
    fond += 1
    print(fond)

sled = Button(text='Следующий день', command=lambda : Ircutsk(fond))
sled.place(y=335, x=140)

Эта функция включается при нажатии на кнопку. Но в консоли при нажатии каждый раз выводится 1 хотя по идее должно быть 0 + 1 =1 значит после второго нажатия 1 + 1 = 2 и т.д. но так не происходит.

A: Сделайте переменную глобальной:
fond = 0

def Ircutsk():
    global fond #Обьявляем переменную глобальной

    fond += 1
    print(fond)

sled = Button(text='Следующий день', command=Ircutsk)
sled.place(y=335, x=140)


text:
Q: When equal products imply equal factors? Under which additional conditions $a\times b = c\times d \Rightarrow a=c\wedge b=d$ (where $\times$ is a categorical product)?
For example, in the case of Cartesian product, for this is enough when the factors are non-empty. Can this be generalized?
I'm also interested about the similar construction with infinite product.

A: The question as stated is a little bit ambiguous, but it's not Porton's fault. The truth is the expression  $a\times b$ may be interpreted either as a product object (which is defined only up to isomorphism) or as the result of a product bifunctor applied to objects $a$ and $b$, defined on a category with binary products. Ponton's question only makes sense if we consider the second interpretation.
In this sense the OP's question is roughly: under what circumstances/limitations is a product bifunctor injective on objects?
Crucial point to note: if you are given a category with binary products, you can define many products bifunctors. Any two of these bifunctors, $\times'$ and $\times''$, are related by natural isomorphisms.
Suppose you can state the following result for product $\times'$:
$\forall(a,b,c,d): P(a,b,c,d)\implies ((a\times' b=c\times'd)\implies (a=c\wedge b=d))$
Where $P(a,b,c,d)$ means that $a,b,c,d$ satisfy predicate $P$ (eg. in $\mathcal{Set}$, $P(a,b,c,d)$ might be "a,b,c,d not empty" )
Can you conclude that the same statement holds for another product $\times''$?
$\forall(a,b): P(a,b)\implies ((a\times'' b=c\times''d)\implies (a=c\wedge b=d))$
In general no (although I cannot present a concrete example).
So whatever conclusion you may arrive at, it would depend not only on your particular category, but also on the particular product bifunctor you have decided to use in that particular category. This is not likely to be very useful/meaningful.

A: Apparently, for you $a \times b$ is the set of ordered pairs $\{(x,y) : x \in a, y \in b\}$. Now if $a \times b \subseteq c \times d$ and $b$ is non-empty, then indeed one finds $a \subseteq c$ using the definitions. Similarly, if $d$ is non-empty, the other inclusion will also give the other inclusion $c \subseteq a$. So equality as sets means $a=c$.
Now assume $a \times b$ is understood as the categorical product, i.e. it just some set equipped with projections $p_a : a \times b \to a$ and $p_b : a \times b \to b$ satisfying the universal property. In particular, $a \times b$ is also a version of $b \times a$ (with the projections swapped), and we cannot hope for any cancellation. On the other hand, equality of objects of a category is not an interesting notion; instead the notion of equivalence (see nlab) is more natural and important. But first we have to agree which objects we are talking about. Just the underlying objects $a \times b$ , $c \times d$ yields very boring counterexamples, for example $\{1\} \times \{1,2,3,4\}$ is isomorphic to $\{1,2\} \times \{1,2\}$. Instead, we should also include our projections and take into account the whole product diagram. Then, an isomorphism $(a \times b,p_a,p_b) \to (c \times d,p_c,p_d)$ should be an isomorphism of diagrams $(p_a,p_b) \to (p_c,p_d)$ which induces an isomorphism on the limit (but this is automatic), i.e. just a pair of isomorphisms $a \to c$ and $b \to d$. In this sense we have cancellation, but it is a very trivial result.
Remark that cancellation for underlying objects of products is a quite hard problem in general. For example, in affine algebraic geometry, $X \times \mathbb{A}^1 \cong \mathbb{A}^2 \Rightarrow X \cong \mathbb{A}^1$ and $X \times \mathbb{A}^1 \cong \mathbb{A}^3 \Rightarrow X \cong \mathbb{A}^2$ are well-known, but the corresponding problem in higher dimensions is widely open.


text:
Q: jQuery jScrollPane does not appear (Wordpress) i try to use jScrollPane on my own WordPress Theme. But it does not appear. i dont know, what the problem is... i see only the old grey standard scrollbar
functions.php
//Register jScrollPane
///////////////////////////////////////////////////////////

add_action( 'wp_enqueue_scripts', 'jscrollpane_libs' );
function jscrollpane_libs()
{
    // Register each script, setting appropriate dependencies
    wp_register_script('jscrollpane', get_template_directory_uri() . '/scroll/jquery.jscrollpane.min.js');
    wp_register_script('mousewheel', get_template_directory_uri() . '/scroll/jquery.mousewheel.js');

    // Register each style, setting appropriate dependencies
    wp_register_style('jscrollcss',   get_template_directory_uri() . '/scroll/jquery.jscrollpane.css');
}

//Register jQuery 1.8
///////////////////////////////////////////////////////////

wp_deregister_script('jquery');
if(!is_admin()) {
     wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js');
     wp_enqueue_script('jquery');
}

header.php

A: Are you calling wp_enqueue_script() also in your header? Try replacing wp_register_script() with wp_enqueue_script() in your functions.php file to check and see if it is working.
Update: it now appears that the scripts are being included properly, perhaps the issue may be that the content in your caption box is dynamic. jScrollPane has an option to reinitialize the content box once something has changed. Perhaps your code would look similar to the following.
$(function() {
    var pane = $('.nivo-caption');
    pane.jScrollPane();
    var api = pane.data('jsp');
    $('.nivo-control').click(function(){
        api.reinitialise();
    });
});

A: First of all, don't dequeue WordPress bundled jQuery.
In functions.php it should go like:
add_action( 'wp_enqueue_scripts', 'jscrollpane_libs' );

function jscrollpane_libs()
{
    $js = get_template_directory_uri() . '/js';
    $css = get_template_directory_uri() . '/css';

    wp_register_script( 'jsp-lib', "$js/jquery.jscrollpane.min.js" );
    wp_register_script( 'jsp-mouse', "$js/jquery.mousewheel.js" );
    wp_register_script(
        'jsp-main',
        "$js/demo.js",
        array( 'jquery', 'jsp-lib', 'jsp-mouse' ), // <--- Dependencies
        false,
        true // <--- In footer
    );

    wp_register_style( 'jsp-css', "$css/jquery.jscrollpane.css" );

    wp_enqueue_script( 'jsp-main' );
    wp_enqueue_style( 'jsp-css' );
}

And the file demo.js:
jQuery(document).ready(function($) // <---- Proper enclosure to use in WordPress
{
   $('.scroll-pane').jScrollPane();
});

And our post has this HTML:

        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec in ligula id sem tristique ultrices
        eget id neque. Duis enim turpis, tempus at accumsan vitae, lobortis id sapien. Pellentesque nec orci
        mi, in pharetra ligula. Nulla facilisi. Nulla facilisi. Mauris convallis venenatis massa, quis
        consectetur felis ornare quis. Sed aliquet nunc ac ante molestie ultricies. Nam pulvinar ultricies
        bibendum. Vivamus diam leo, faucibus et vehicula eu, molestie sit amet dui. Proin nec orci et elit
        semper ultrices. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus
        mus. Sed quis urna mi, ac dignissim mauris. Quisque mollis ornare mauris, sed laoreet diam malesuada
        quis. Proin vel elementum ante. Donec hendrerit arcu ac odio tincidunt posuere. Vestibulum nec risus
        eu lacus semper viverra.


text:
Q: how do I remain the changed value in clojure reframe Suppose I have a group of buttons and if user clicked a button I want it to change the value from "not clicked" to "clicked" so I have wrote this code
(rf/reg-sub
 ::clicked-sub
 (fn [db _]
   (:clicked db)))

(rf/reg-event-db
 ::clicked-event
 (fn [db [_ clicked-numb]]
   (assoc db :clicked clicked-numb)))

(defn button-group [numbers]
  [:div
   (for [number numbers]
     ^{:key number}
     [:button
      {
       :value (if (= number @(rf/subscribe [::clicked-sub])) "clicked" "not clicked")
       :on-click (fn [e] (rf/dispatch [::clicked-event number]))
       }
      ]
     )
   ]
  )

The problem is, after the user clicked another button the previous clicked button is changed value from "clicked" to "not clicked". I want it to remain the clicked value for each clicked button how to do that

A: The issue is that your data handling in db is too simplistic. Your event is always overwriting the value of clicked with the current number, hence the lookup / subcription is always only returning the latest clicked number.
What you instead could do is store a hash-map of numbers / boolean as a value to the :clicked key in the db. Your event would then update (assoc-in) the number to true. Of course, you then also need to change your check on the subscription to see if the current number is set to true.


text:
Q: How to replace a character in a string with NULL in ANSI C? I want to replace all 'a' characters from a string in ANSI C. Here's my code:
#include <stdio.h>
#include <stdlib.h>

void sos(char *dst){
    while(*dst){
        if(*dst == 'a')
        *dst = '\0';
        dst++;
        }
}

int main(void){
    char str[20] = "pasternak";
    sos(str);
    printf("str2 = %s \n", str);
    return 0;
}

When I run it, result is:
str2 = p

But it should be
str2 = psternk

It works fine with other characters like 'b' etc. I tried to assign NULL to *dst, but I got error during compile.
How can I remove 'a' characters now?

A: In C, strings are zero-terminated, it means that when there's a '\0' in the string it is the end of the string.
So what you're doing is spliting the string in 3 different ones:
p
stern
k

If you want to delete the a you must move all the characters after the a one position.

A: What printf does is: read bytes until a '\0' is found.
You transformed "pasternak" to "p\0astern\0k", so printf prints p.
This convention is used on the string functions of the stdlib so that you don't have to pass string length as an argument.
This is why it is said that in C strings are null terminated: it is just a convention followed by the C stdlib.
The downside, as you discovered, is that strings cannot contain \0.
If you really want to print a given number of bytes, use something like fwrite, which counts the number of bytes to be printed, so it can print a \0.

A: The answers previously provided are perfect to explain why your code does not work. But you can try to use strtok to split the string based on the 'a' characters, to then join the parts together or simply print them appart. Check this example: http://www.tutorialspoint.com/c_standard_library/c_function_strtok.htm

A: '\0' is how the C language tools recognize the end of the string. In order to actually remove a character, you'll need to shift all of the subsequent characters forward.
void sos(char *dst) {
  int offset = 0;
  do {
    while (dst[offset] == 'a') ++offset;
    *dst = dst[offset];
  } while (*dst++);
}


text:
Q: Prevent API call based on a timer in vue.js In a scenario, the GET API call takes around 1 minute to fetch the updated data, updated by INSERT/UPDATE API calls.
So user updates some fields in the UI, and a UPDATE call has been made, the UPDATE call returns the updated fields value. However if the user refreshes the page with 1 minute of updating, the GET call will be made and which returns the OLD data.
How can I prevent the GET CALL within 1 minute of updating data?

A: *

*Get  data

*Save data in localStorage, and note timeStamp i localStorage

*Get data from localStorage if current time is less than 1 minute after timeStamp

*Else get new data


text:
Q: how to get doctrine2 entitymanager in slmqueue job? I'm going to use SlmQueue (https://github.com/juriansluiman/SlmQueueDoctrine).
How can I get doctrine2 entitymanager inside job class?

A: I've managed to make this like this:
        class DistributeNewsJob extends AbstractJob implements QueueAwareInterface, ServiceLocatorAwareInterface
        {
            use QueueAwareTrait;

            public function execute()
            {
                 // job code

            }

            private $entityManager;
            private function getEntityManager()
            {
                if (null === $this->entityManager) {
                    $this->entityManager = $this->getServiceLocator()->get('Doctrine\ORM\EntityManager');
                }
                return $this->entityManager;
            }

            private $services;

            public function setServiceLocator(ServiceLocatorInterface $serviceLocator)
            {
                $this->services = $serviceLocator->getServiceLocator();
            }

            public function getServiceLocator()
            {
                return $this->services;
            }

            public function dispatch(Request $request, Response $response = null)
            {
            }
        }

A: We can also do this :
You can use ObjectManagerAwareInterface from doctrine module
use DoctrineModule\Persistence\ObjectManagerAwareInterface;
use DoctrineModule\Persistence\ProvidesObjectManager as ProvidesObjectManagerTrait;

class EmailJob extends AbstractJob implements ObjectManagerAwareInterface
{
    use ProvidesObjectManagerTrait;
}

That way you have ObjectManager in your job.


text:
Q: laravel 5 hash check and redirect not working In a quite strange situation, I am trying to Hash::Check my password from database and user input, however it work.
$user = User::where('email', $request->username)->get()->first();

if(Hash::check($request->password, $user->password)) {
    return Redirect::to('secondpage')->with('user', $user);
}

Strangely, if I change my password in database to plain text and use Hash::check with it, it works.
Any idea? thanks in advance.

A: I'm not sure but there might be a typo in your code, you might want to fetch your user like so :
$user = User::whereEmail($request->email)->first();


text:
Q: How to set a particular range so that it takes the value of that range and run in python have this python code that has a link present
driver.get('https://simpletire.com/catalog?select=1&brand=1')

in the place of brand=55 there should be forloop range so that it takes values from (1-500) and run the code .
code :
#Importing packages
from selenium import webdriver
import pandas as pd
import time

driver = webdriver.Chrome('/Users/1/chromedriver.exe')

driver.get('https://simpletire.com/catalog?select=1&brand=1')

try:

    click_more = True

    while click_more:

        time.sleep(5)
        element = driver.find_element_by_css_selector(".btn.btn-primary.btn-lg").click()

except :
....

how to add for loop so that it loops in range from (1-500).
like
driver.get('https://simpletire.com/catalog?select=1&brand=1')
driver.get('https://simpletire.com/catalog?select=1&brand=2')
driver.get('https://simpletire.com/catalog?select=1&brand=3')
driver.get('https://simpletire.com/catalog?select=1&brand=4')
driver.get('https://simpletire.com/catalog?select=1&brand=5')
driver.get('https://simpletire.com/catalog?select=1&brand=6')

......
   ......
   .....
   .....
    driver.get('https://simpletire.com/catalog?select=1&brand=500')

A: If you are in python version 3.5+, you can use an f-string:
for i in range(1, 501):
    site = f'https://simpletire.com/catalog?select1&brand={i}'
    driver.get(site)
    # rest of code

Otherwise, you can use % formatting syntax:
for i in range(1, 501):
    site = 'https://simpletire.com/catalog?select1&brand=%d' % i
    driver.get(site)
    # rest of code

Or the str.format syntax
for i in range(1, 501):
    site = 'https://simpletire.com/catalog?select1&brand={}'.format(i)
    driver.get(site)
    # rest of code


text:
Q: Sticky header not working Angular5 Hi guys having trouble with implemting a a sticky navbar in my Angular application.
This is my app component:

        <app-online-header></app-online-header>

                <app-navigation></app-navigation>

            <router-outlet></router-outlet>

My goal is to have the <app-navigation> component sticky. Here is how it looks like:

What I tried so far is in my app-component CSS file:
.sticky{
    position: sticky;
    top: 0;
}

Question:
Why doesn't this make my <app-navigation> component sticky?

A: The problem is the class is defined in the
 tag. The class="sticky" needs to be defined inside the  or
 tag that's placed inside the <app-navigation> component
Example:
HTML code:

Monte

Concept

Fusion

Home

CSS code:
.sticky {
  width: 100%;
  height:72px;
  margin:0;
  left:0;
  right:0;
  top:0;
  background-color: white;
  overflow: hidden;
  display: block;
  position: sticky;
  position: -webkit-sticky;
  z-index: 5;
}

Angular ts file

<app-navigation-bar></app-navigation-bar>

<router-outlet></router-outlet>


text:
Q: Turning an array into array of objects but cannot run function Alright, I must be missing something here.  I have an object:
export class Country {
    id: number = 0
    name: string = ''

    getNamePlusBob() {
        return this.name + 'bob'
    }

}

And I get the data from an API in an array, then pass it to the browser.
Once i have the data I want to turn the array into an array of objects of type 'Country'.
So I made this function (not sure if Hydrate is the correct term here?):
function hydrateArray(data, entity) {
    let returnArray = []
    console.log(data)
    data.forEach((row) => {
        const object = entity;
        for (const [key, value] of Object.entries(row)) {
            if(Object.hasOwn(object, key)) {
                object[key] = value
            } else {
                console.log('Key not found in entity', key)
            }
        }
        console.log(object.getNamePlusBob())
        returnArray.push({...object})
    })
    return returnArray
}

const countries = hydrateArray(countryData, new Country())

In the console.log in the function, I can run the getNamePlusBob() and it returns the name plus bob.  However, on the returned array countries, I cannot:
console.log(countries[0].getNamePlusBob())
TypeError: countries[0].getNamePlusBob is not a function
Why not? It was inside the hydrateArray function, why cant I run it outside?


text:
Q: XML and DataContractSerializer I have classes like this
[DataContract(Namespace = "")]
public class Foo
{
    [DataMember(Order = 0)]
    Bar bar;
}

[DataContract(Namespace = "")]
public class Bar
{
    Baz baz;

    [DataMember(Order = 0)]
    string TheBaz
    {
        get { baz.ToString(); }
        set { SomeOtherCode(value); }
    }
}

I want this to generate XML like this
<Foo>
    <Bar>String from baz.ToString()</Bar>
</Foo>

but am getting something more like:
<Foo>
    <Bar><TheBaz>String from baz.ToString()</TheBaz></Bar>
</Foo>

is it possible to fix this? This artical says that one of the disadvantages of DataContractSerializer is:

*

*No control over how the object is serialized outside of setting the name and the order

leading me to wonder is this is not a solvable problem.

I known this can be done with IXmlSerializable and ReadXml/WriteXml because I'm supposed to be removing code that does just that.

A: Implement IXmlSerializable on the Bar class, and then have it output <Bar>String from baz.ToString()</Bar> when serialized.
You can leave the Foo class as is, and the DataContractSerializer will take care of the rest.

A: I realized my first answer was completely bogus - but you can cheat with properties:
[DataContract(Namespace = "")]
public class Foo
{
    [DataMember(Order = 0, Name="Bar")]
    private string BazString {
        get {
            return bar == null ? null : bar.TheBaz.ToString();
        }
        set {
            if(value == null) {
                bar = null;
            }
            else {
                if(bar == null) bar = new Bar();
                bar.TheBaz = value;
            }
        }
    }

    Bar bar;
}


text:
Q: Парсинг сайта ip адрессов с веб страниц python Стоит задача пройтись по ссылкам сайта
http://www.zone-h.org/archive
открывать ссылки вида
http://www.zone-h.org/mirror/id/22714269
и копировать поле с IP адрессом в единый текстовый файл.
Как посоветуете реализовать на Питоне? Какие посоветуете библиотеки/примеры использовать?
Спасибо за советы.
A: С содержимым сайта очень удобно работать используя Grab, а Browser из mechanize позволяет почувствовать себя настоящим браузером :) кстати, grab тоже умеет обрабатывать редиректы, куки, выбирать случайный юзерагент из своего списка или пользовательского, а также прокси и все необходимое...

Эта статья мне когда-то очень помогла - позволяет быстро вникнуть в то, как нужно парсить, что для этого использовать (стоит взглянуть на дату публикации) и все в этом духе.


text:
Q: Why don't we consider centripetal force while making FBD (free body diagram)?
Consider a situation where a block is kept on a wedge which is further kept on a surface which rotates with $\omega$ the FBD for the same

My question is why dont we consider centripetal force in fbd? Is it because we are drawing it from a frame such that it cancels?

Edit :My simple definition of fbd tells me that it is a diagram representing all the forces acting on the body when viewed from  a particular frame which ensures that centripetal force must be acting only in a certain frame

A: From an inertial frame
You are considering the centripetal force. In fact you have already included it if you are using an inertial frame.
The centripetal force is not a new force. It is just a name we give to whichever force that pulls centripetally (towards the centre in circular motion).
In your case there is a component from the normal force which pulls centripetally (horizontally leftwards). So that is called the centripetal force.
From the non-inertial frame
This above explanation is from an inertial frame, as if standing on the ground and watching the scenario. If you want to look at this from a non-inertial frame, by imagining that you are sitting on the block that is in rotation, which might be the case judging from your sketch, then from that frame the block doesn't seem to rotate. Rather it looks like the surroundings are "rotating".
Thus from that frame there seems to be no (resultant) centripetal force acting on the block. This means that the horizontal component of the normal force must be balanced out by something. That "something" is what we invent with the name centrifugal force, pointing opposite in the outwards direction.
This centrifugal force is a so-called pseudo-force in that it doesn't really "exist" - but we invent it mathematically in order to make Newton's laws hold true even in non-inertial frames.

A:
My question is why dont we consider centripetal force in fbd ? Is it because we are drawing it from a frame such that it cancels?

Centripetal force and centrifugal force never act together. You are working in non-inertial frame and have shown centrifugal force , hence no need to show centripetal force.

I am attaching a picture from my notes to clarify what i meant so that my answer is interpreted correctly. The situation is quite similar to your question.
Consider a case of banking when viewed from 2 different frames :

In ground frame , you don't show any centrifugal force.

From inside car, which is a non inertial frame ,$F_{centrifugal}$ is balanced by $Nsin\theta$.
No doubt $Nsin\theta$ will act in both frame , and is equal to $mv^2/r$ regardless of the frame but since car is at rest in non inertial frame , I wouldn't call it a centripetal force.

Edit 2 :
Why would i call $Nsin\theta$ a centripetal force in the car's frame
According to Wikipedia a centripetal force is defined as :  a force that makes a body follow a curved path.
Since the body is at rest in it's own frame , $Nsin\theta$ is  is not a cause of the centripetal force in the rotating frame.

A: The reason we don't include the "centripetal force" in the FBD is the same reason we don't include the "vertical force" or the "horizontal force" in the FBD. Centripetal is just a direction, just like vertical and horizontal are directions. Just like how forces can be vertical or horizontal, forces can also be centripetal or tangential.
For example, including "centripetal force" on a FBD would just be like including the gravitational force as well as a second "vertical force" on the FBD for an object in free fall. In your case, there is a component of the force of the wedge on the block. This force points in the centripetal direction, so it is a centripetal force. But you wouldn't put an explicit "centripetal force" on the diagram; you already did that.

A:
why dont we consider centripetal force in fbd ?

Indeed, we should include pseudo forces too, consider this :

Due to different position of wedge and block COM from rotational axis and they difference in mass- there will arise subtle tidal forces (differences in centrifugal forces of that within block and wedge). So in the end normal force upon block will be :
$$ N = mg \cdot \cos \alpha + m\,\omega^2r \cdot \sin\alpha - M\omega^2R
\cdot \sin\alpha$$
Where $m$ block mass, $M$ - wedge mass, $r$ block distance from rotational axis, $R$ - wedge distance from rotational axis, $\omega$ - angular speed.

A: The descriptions of circular motion often make it sound like centripetal and/or centrifugal force result from circular motion. But it's the opposite: circular motion results from centripetal force. There is nothing specifically exerting a centripetal force on the object. Centripetal force is an "output" force, not an "input" force. Gravity and the normal force are the "input" force; they are distinct forces from distinct physical sources. When we add those two forces together, we get the net force. Since this force is toward the center of the circle, it is a centripetal force. "Centripetal force" is just what we're calling the sum of all the input forces. It's not a force we start with when we're drawing the FBD, it's what we use the FBD to find.

A: We do not consider the centripetal force to only be acting on the block, as it is also acting on the wedge. You have to consider the entire wedge-block system while calculating the centripetal force, so the centripetal force would act on the wedge-block system as a whole, not only on the block.
Edit:
Even if you do consider the centripetal force, then you have to consider a horizontal component of reaction from the wedge which correctly cancels out the centripetal force, so it won't make any difference.
I hope this helps!


text:
Q: Can't use cyg-apt on cygwin 1.7 I've got an issue with the cyg-apt command (on cygwin 1.7 running on a Windows 7 64bits virtual machine)
I've followed these step in order to install cyg-apt correctly :
Install cygwin
Install wget and python
wget http://www.lilypond.org/~janneke/software/cyg-apt 1.1
Edit the cygapt file: Change the default server to other than the one in it. (I find   ftp://ftp.cise.ufl.edu/pub/mirrors/cygwin/ to be good)
chmod a+rx cyg-apt
mv cyg-apt /bin
cyg-apt setup
cyg-apt update

And no matter what I try with cyg-apt (cyg-apt install package-name, cyg-apt man, even cyg-apt ...), this error appear everytime :
to rely on a native Windows version of Bonjour's mDNSResponder service.
Traceback (most recent call last):
File "/usr/bin/cyg-apt", line 658, in (module) get_setup_ini()
File "/usr/bin/cyg-apt", line 184, in get_setup_ini raise 'URG'
TypeError: exceptions must be old-style classes or derived form BaseException, not str

I've made some researchs and it could be link to an incompatibility with the 1.7 version of cygwin but nothing more helpfull.

A: You can do this using Cygwin's setup.exe from Windows command line. Example:
cd c:\cygwin
setup.exe -q -P wget,tar,qawk,bzip2,subversion,vim

For a more convenient installer, you may want to use apt-cyg as your package
manager. Its syntax similar to apt-get, which is a plus. For this, follow the
above steps and then use Cygwin Bash for the following steps:
wget rawgit.com/transcode-open/apt-cyg/master/apt-cyg
install apt-cyg /bin

Now that apt-cyg is installed. Here are few examples of installing some
packages:
apt-cyg install nano
apt-cyg install git
apt-cyg install ca-certificates

A: Possibly not exactly what you're looking for, but perhaps abandon cyg-apt in
favor of apt-cyg. cyg-apt hasn't been updated since 2009. Personally,
whenever I try cyg-apt update I get an error like this:
cyg-apt: bad URL http://www.gtlib.gatech.edu/setup-2.ini, exiting.

the apparent solution to which is to instead use apt-cyg.
apt-get for cygwin?


text:
Q: Keycloak - is it ready for production? I spent time testing out Keycloak Identity server for handling microservice authentication using OpenID connect. I was able to fully customise the freemarker theme to what I want.
It's got nice features too but somehow I still find it buggy, most annoying error is getting

"An error occurred, please login again through your application"

because the one time code is not valid on browser refresh.

I'm wondering if anyone is actually using it in production or it's just an Alpha release not ready for production yet ?
Current version: 2.5.0.Final


text:
Q: Read IP Address using SQLDataReader Working with an ASP.Net application where I would like to pull IPv4 information from a SQL database using SQLDataReader. When reading an IP from SQL the data type is binary and I am not sure the best way to handle this.
Since there is no method for SQLDataReader.GetIPAddress() it seems that I would need to use SQLDataReader.GetBytes()? Many examples online around how to do this however since getstring is very simple I am hoping there is another simpler way to use getbyte() or another method to bring in the IP.
    Do While SQLReader.Read()
        Dim lastcom As System.DateTime = SQLReader.GetDateTime(0)
        Debug.WriteLine(lastcom.ToString("MM/dd/yyyy HH:mm:ss.fff"))
        Debug.WriteLine(SQLReader.GetString(1))
        Debug.WriteLine(SQLReader.GetBoolean(2))
        Debug.WriteLine(SQLReader.GetString(3))
        Debug.WriteLine(SQLReader.GetString(4))
        Label_IP = SQLReader.GetString(1)
        Label_Model.Text = SQLReader.GetString(4)
   Loop

A: I am making some assumptions about how the IP address is stored in the database (and only supporting IPv4 addresses), but you could try something like this:
Dim ipAddr(3) As Byte
' Assuming that column #1 is your IP address column
Dim byteCount = SQLReader.GetBytes(1, 0, ipAddr, 0, 4)
If byteCount = 4 Then
    Label_IP.Text = New IPAddress(ipAddr).ToString()
Else
    Console.WriteLine("Expected 4 bytes for IP address")
End If


text:
Q: How do I fix these misplacements? My team and I are working in Microsoft's TNT program and we've built a web app that deals with battling misinformation. A component of it deals with rating news articles on various criteria. The problem is I want the stars to align horizontally and the stars to be colored when clicked upon as opposed to the buttons (frankly, I'm not sure why the buttons are even there). Also, for the Objective part, the stars are out of the tile (again not sure how that happened). I'd appreciate anyone helping with making the stars horizontal, getting rid of the buttons and instead it should be the stars getting colored when clicked on, and for the 'Objective' part having the stars within the tile. I've included images, css, and tsx files to help visualize these misplacements. (I'm very new to TypeScript+React so I have limited knowledge on this)
Tsx file:
import React, { useState } from "react";
import { FaStar } from "react-icons/fa";

const StarRating = () => {
 const [rating, setRating] = useState(0);

 return (

 <div>
 {[ ... Array(5)].map((star, i) => {
 const ratingValue = i + 1;

 return(

 <label>
 <input
 type="radio"
 name="rating"
 value={ratingValue}
 onClick={() => setRating(ratingValue)}

 />
 <FaStar className="star"
 color={ratingValue <= rating ? "#ffc107" : "#e4e5e9"}
 size={20} />
 </label>
 )

 })}
 </div>
 );
};

export default StarRating;

Css file:
.StarRating {
 display: flex;
 justify-content: center;
 align-items: center;
 min-height: 100vh;
 flex-direction: row;

}

input[type = "radio"]{
 display: none;
}

.star {
 display: flex;
 cursor: pointer;
 transition: color 200ms;
}

Images:
Stars vertical
Stars out of tile


text:
Q: Set Windows IP from Qt application I'm exploring the possibility of setting windows ip from a Qt5 application and the following seems to work
#include <QApplication>
#include <QDebug>
#include <QThread>
#include <QProcess>
#include <QFile>
#include <QDir>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    QString filename = "file";

    auto preparescript = [](QString cmd, QString filename) {
        QFile f(filename+".bat");
        if (!f.open(QIODevice::WriteOnly | QIODevice::Text)) return;
        QTextStream out(&f);

        out << QString("cd \"%1\"\n").arg(QDir::toNativeSeparators(QDir::currentPath()));
        out << cmd;
    };

    auto name  = "Ethernet";
    auto ip  = "192.168.1.7";
    auto mask  = "255.255.255.0";
    auto gateway  = "192.168.1.1";
    auto cmd = QString("netsh interface ip set address name=\"%1\" static %2 %3\n").arg(name,
                                                                                ip,
                                                                                mask,
                                                                                gateway);

    preparescript(cmd, filename);

    QProcess p;
    p.start("cmd.exe", {"/C", QString("Powershell Start %1 -Verb Runas").arg(filename+".bat")});

    if (!p.waitForFinished())
        return -1;

    return a.exec();
}

However the terminal window where the script gets executed pops up for a split of a second which dims the elegance of this solution.

*

*How can I hide the terminal?

*How to do it without creating the .bat file?

*Are there other, more elegant, solutions for setting windows ip from a Qt application?

A: Instead of launching cmd.exe in order to invoke Powershell in order to invoke netsh.exe with the supplied arguments. Just invoke netsh.exe directly. If you do that, you can even check the process return code to see if the command succeeded.


text:
Q: How to dump Parse tree and token info from GCC? I want to dump token information (list of all tokens for a c file) and parse tree from GCC compiler. I went through the gcc documentation but it was not clear on how to do it.
How can I get this information from GCC?


text:
Q: What exactly is 'super' doing in my apps? Ok, this is going to be a really embarrassing question, but I looked like mad in my beginner's books (especially those usually helpful indices) and behold, I did not find a down-to-earth explanation of what 'super' does in my applications.
I had a look at this here, but I'm afraid that's well beyond me. Can anyone offer a very simply explanation of what 'super' does in my apps and why I should become friends with it? E.g.:
- (void)viewDidLoad {
[super viewDidLoad];}

Thanks!!

A: super calls the superclass's implementation of the method. So if your class inherits UIViewController, then [super viewDidLoad]; will call the UITableViewController class's viewDidLoad method. You should usually do this because the super class may do important things that need to happen. In the case of viewDidLoad, I'm not sure it actually does anything currently, but it always could in a future version of the framework.

A: at the low level, self contains a pointer to the set methods it responds to. this is a basic mechanism for the implementation of dynamic dispatch. each class is given a unique set. if you're familiar with c++, this is similar in concept to a virtual table. you can think of an objc method as being like a C function with 2 hidden arguments (self,_cmd).
super is a dynamically created representation of self, with a pointer to the next-in-line methods implemented by the instance's superclasses. this representation is based on self, and just directs to another set of implemented methods.
@interface MONTypeA : NSObject
- (void)monMethod;
@end

@interface MONTypeB : MONTypeA
- (void)monMethod;
@end

@implementation MONTypeA

- (void)monMethod {
    printf("i am MonTypeA\n");
}

@end

@implementation MONTypeB

- (void)monMethod {
    [super monMethod]; /* << will call -[MONTypeA monMethod], which will print "i am MonTypeA\n" */
    printf("i am MonTypeB\n");
}

@end

if you create an instance of MONTypeA, then it will respond to monMethod:
MONTypeA * a = [MONTypeA new];
[a monMethod];
[a release], a = 0;

// outputs: "i am MonTypeA\n"

MONTypeB * b = [MONTypeB new];
[b monMethod];
[b release], b = 0;

// outputs: "i am MonTypeA\n""i am MonTypeB\n" because -[MONTypeB monMethod] calls through super

therefore, calling super performs the implementation of the method of the superclass in this specific case.
it is important to remember: the set of methods super refers to is always those of the previous implementation of the method in the hierarchy, it is not the same set as the set of instance methods which an instance of the superclass would be given (unless your class were to override every method).


text:
Q: android: when i connect my listview to database i lost the styling when i connect my listview to database i lost the listview style.
and when i add the style i see same data on all of the listview.
public void update_list(String NN) {
        //HashMap<String,String> item = new HashMap<String,String>();

       db_results = new ArrayList<String>();
       Cursor cursor = db.rawQuery(NN, null);
        while(cursor.moveToNext()) {
            //item.put( "line1",String.valueOf(cursor.getString(cursor.getColumnIndex("A"))));
              //item.put( "line2",String.valueOf(cursor.getString(cursor.getColumnIndex("B"))));
              //item.put( "line3",String.valueOf(cursor.getString(cursor.getColumnIndex("C"))));
              //list.add( item );
             db_results.add(String.valueOf(cursor.getString(cursor.getColumnIndex("A"))) + "\n" +cursor.getString(cursor.getColumnIndex("B")) + "\n" +cursor.getString(cursor.getColumnIndex("C")));
         }
        cursor.close();
               setListAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,db_results));

option1: like this code i see the data on my list but i lost the styling.
option2: i un remark the remarked code and i see the styling but same data on all of the list

A: You'd be much better off to create a custom layout and use a SimpleCursorAdapter to populate it.
threelinelayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:orientation="vertical" >
    <TextView
            android:id="@+id/ListItem1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    <TextView
            android:id="@+id/ListItem2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    <TextView
            android:id="@+id/ListItem3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
</LinearLayout>

adapter code
Cursor mCursor = db.rawQuery(NN, null);
this.startManagingCursor(cursor);

String[] from = new String[] { "A", "B", "C" };
int[] to = new int[] { R.id.ListItem1, R.id.ListItem2, R.id.ListItem3 };
SimpleCursorAdapter mAdapter = new SimpleCursorAdapter(getActivity(),
            R.layout.threelinelayout, mCursor, from, to);
setListAdapter(mAdapter);


text:
Q: Invariant dimension property and a ring epimorphism In Hungerford's Algebra, p. 186, the Proposition 2.11 says
Let $f:R\to S$ be a nonzero epimorphism of rings with identity. If $S$ has the invariant dimension property (IDP), then so does $R$.
It is true, and the proof is logical. However, my problem is about the converse;

if $R$ has the IDP, then does $S$ have the IDP too?

We do not need to handle infinite basis cases or commutative ring cases, because that is true... (Theorem 2.6 Corollary 2.12).

A: Let $S$ be any ring without IBN, and let $T$ be any ring with IBN.
There is a projection $S\times T \to T$, so $S\times T$ has $IBN$.  But then the projection $S\times T \to S$ is a counterexample.


text:
Q: If we are willing to accept tachyonic string modes, are there valid projections other than the GSO projections? One reason superstring theory has often been touted as being an improvement over bosonic string theory is that we can impose GSO projections to remove the tachyonic mode. If we insist upon the no tachyon condition, we are left with only five superstring theories.
But what if we don't mind tachyonic modes? After all, they only signify the background we are expanding about is unstable. Can we have more string models then? Type 0 string theories are one example, but are there others? I realize we can't have supersymmetry in target space if we have negative energies, but there's no theorem stating that string theories have to be supersymmetric.

A: First, a disclaimer: expanding around an unstable background is... problematic. The actual dynamics of an unstable background dictates a disappearance of the space within a string time. Spacetime supersymmetry at some level is almost certainly needed for some basic consistency.
Now, if you care about theories similar to type 0 string theories, we need to focus on the maximally dimensional ones because there are way too many vacua, even the supersymmetric ones, when some dimensions are compactified (the "landscape").
As far as closed string possibilities go, there is a bosonic string theory in $D=26$. Open strings may be allowed by various D-branes in those theories - the classification of possible D-branes is another step in the classification of backgrounds. And strings may be constrained to be unoriented by the additional of orientifold planes - which are classified analogously to D-branes.
Now, for $D=10$ string theories with the world sheet supersymmetry, type 0A and 0B string theories are the only consistent non-supersymmetric theories that use the superstring both for left-movers and right-movers. It's not hard to see why in the RNS formalism. You always absolutely need the "overall" or "diagonal" GSO projection for all the fermions. Type II theories have separate ones for left-movers and right-movers. Type 0 theories only have the shared one and one may distinguish how the GSO operator acts in the PP sector (odd or even forms, again). Type 0 theories are covered as standard material in chapter 10 of Polchinski's book.
If you consider heterotic string theories, $D=26$ on one side and $D=10$ on the other, there are extra 10-dimensional theories. The extra left-movers may be fermionized and the actions on the supersymmetric fermions and the left-moving $\lambda$ fields may be coupled in various ways. As explained in section 11.3 of Polchinski's book, you may get seven tachyonic heterotic string theories with $SO(16)\times SO(16)$, $SO(16)\times E_8$, $SO(24)\times SO(8)$, $E_7\times E_7\times SO(4)$, $SU(16)\times SO(2)$, single $E_8$, and $SO(32)$ (without SUSY!) gauge groups.

A: In ten dimensions this question was answered long ago in the three papers listed below.
The first one found several new possibilities using orbifold projections including a theory without spacetime supersymmetry and with no tree-level tachyon, the latter two papers classified modular invariant spin structures in a fermionic formulation. Below ten dimensions there are many more possibilities.
1) String Theories in Ten-Dimensions Without Space-Time Supersymmetry.
Lance J. Dixon, Jeffrey A. Harvey, (Princeton U.) . PRINT-86-0244 (PRINCETON), Feb 1986. 18pp.
Published in Nucl.Phys.B274:93-105,1986.
2) Spin Structures in String Theory.
N. Seiberg, (Weizmann Inst. & Princeton, Inst. Advanced Study) , Edward Witten, (Princeton U.) . Print-86-0218 (PRINCETON), Feb 1986. 28pp.
Published in Nucl.Phys.B276:272,1986.
3) An O(16) x O(16) Heterotic String.
Luis Alvarez-Gaume, Paul H. Ginsparg, Gregory W. Moore, C. Vafa, (Harvard U.) . HUTP-86/A013, Feb 1986. 15pp.
Published in Phys.Lett.B171:155,1986.


text:
Q: Most efficient way to work with large lists in python I was wondering what is the best way to work with 3 lists of objects in python.
Let's say I have a list of products - each product is a dict.
Additionally I have 2 more lists one with variants of products  (each variant is a dict) and second list with let's say retailers (each retailer is a dict).
What I want to do is: I want to map over the product, retailers and variants list and combine them together so in the end I will have list of products and each product will have variants and retailers.
Products = [{"id": 1,
             "name": "cheese"},…]

Variants = [{"product_id": 1, "additional_info":…},
            {"product_id": 3, "additional_info":…},
            {"product_id": 1, "additional_info":…},…]

Retailers = [{"product_id": 1, …},…]

Let's say I have 3k of products, 4K of variants and 2k of retailers. I need to map over these lists and assign each retailer and variant to the product.

A: Using a proper database is probably the right idea if you need to query this data, but combining the three lists into one data structure is relatively simple. The key is to recognize that Products should not be a list, but a dict whose keys are product IDs.
# Assuming the id uniquely identifies a product, rather than
# the id/name pair.
products = {p["id"]: p for p in Products}

Then it's a relatively simple O(n) algorithm to update each product in products with the variant and retails. (I'm using lists to accumulate variant and retail information when multiple values are associated with a single product.)
for v in Variants:
    p_id = v["product_id"]
    info = v["additional_info"]
    products[p_id].setdefault("additional_info", []).append(info)

for r in Retailers:
    p_id = r["product_id"]
    other_data = r["other_stuff"]
    products[p_pid].setdefault("other_stuff", []).append(other_data))

A: Here I'mjust extending @Austin LaShure using pandas's only
Data
import pandas as pd

products = [{'id':1, 'name':'cheese'},
            {'id':2, 'name':'ham'},
            {'id':3, 'name':'bread'}]

variants = [
    {'product_id':1, 'additional_info':'has lactose'},
    {'product_id':2, 'additional_info':'not vegan'},
    {'product_id':3, 'additional_info':'has gluten'}
]

retailers = [
    {'product_id':1, 'retailer':'WalMart'},
    {'product_id':2, 'retailer':'Sams'},
    {'product_id':3, 'retailer':'Target'}
    ]

Load data as dataframe
df1 = pd.DataFrame(products)
df2 = pd.DataFrame(variants)
df3 = pd.DataFrame(retailers)

Merge them
df = pd.merge(
    df1,
    df2,
    left_on=["id"],
    right_on=["product_id"],
    how="outer")

df = pd.merge(
    df,
    df3,
    left_on=["id"],
    right_on=["product_id"],
    how="outer")
print(df)

   id    name  product_id_x additional_info  product_id_y retailer
0   1  cheese             1     has lactose             1  WalMart
1   2     ham             2       not vegan             2     Sams
2   3   bread             3      has gluten             3   Target

Here I'm taking the most general case using outer join if you want an inner you can specify it and eventually drop the product_id after each merge.

A: I am still pretty new with pandas, but big lists and dicts are much easier to manipulate with pandas.
this code:
import pandas as pd

products = [{'id':1, 'name':'cheese'}, {'id':2, 'name':'ham'}, {'id':3, 'name':'bread'}]

variants = [
    {'product_id':1, 'additional_info':'has lactose'},
    {'product_id':2, 'additional_info':'not vegan'},
    {'product_id':3, 'additional_info':'has gluten'}
]

retailers = [
    {'product_id':1, 'retailer':'WalMart'},
    {'product_id':2, 'retailer':'Sams'},
    {'product_id':3, 'retailer':'Target'}
    ]

list_of_data = []
for p in products:
    id = p['id']
    name = p['name']
    for i in retailers:
        if i['product_id'] == id:
            seller = i['retailer']
    for j in variants:
        if j['product_id'] == id:
            additional_info = j['additional_info']

    data = pd.Series(data=[id, name, seller, additional_info],
    index=['product_id', 'name', 'retailer', 'additonal info'])
    list_of_data.append(data)

frame = pd.DataFrame(list_of_data)

takes the data you have in your current code and put it into a dataframe. The dataframe object has a lot of useful properties and functions.  If you aren't going to use a database, pandas is going to be your best bet.

A: Instead of lists of dictionaries, try to use dictionaries that have unique keys.  Once you have that, updating one of the dictionaries with the others can be done with the .update() method.
products = [{"id": 1, "name": "cheese"}, {"id": 2, "name": "milk"}]
variants = [
    {"product_id": 1, "additional_info": "blah blah blah"},
    {"product_id": 3, "additional_info": "blah"},
    {"product_id": 1, "additionalinfo": "blorgh"},
]
retailers = [
    {"product_id": 1, "retail_name": "name:"},
    {"product_id": 2, "retail_name": "name2"},
]

product_dict = {
    product["id"]: {k: v for k, v in product.items() if k != "id"}
    for product in products
}
variant_dict = {
    variant["product_id"]: {k: v for k, v in variant.items() if k != "product_id"}
    for variant in variants
}
retailer_dict = {
    retailer["product_id"]: {k: v for k, v in retailer.items() if k != "product_id"}
    for retailer in retailers
}

for product_id, product in product_dict.items():
    product.update(variant_dict.get(product_id, {}))
    product.update(retailer_dict.get(product_id, {}))

print(product_dict)

# Prints
# {1: {'additionalinfo': 'blorgh', 'name': 'cheese', 'retail_name': 'name:'},
#  2: {'name': 'milk', 'retail_name': 'name2'}}

A: If you don't want to use a relational database, the MongoDB would be your best bet.
Python has PyMongo :

*

*https://pymongo.readthedocs.io/en/stable/
snapshot of MongoDB database & collections
[enter image description here]
The above image represents a MongoDB database : python_inventory_dict
with collections ("tables") as per requirements
Combining collections:
https://docs.mongodb.com/manual/reference/operator/aggregation/merge/


text:
Q: Trouble when importing a maven project into eclipse kepler (swagger for jersey rest) I have created a rest webservice with jersey. I like to add swagger to my project to create documentation for the rest interface. As an example i downloaded a rest project with swagger. It is a maven project.
I installed maven on ubuntu & installed maven plugin into eclipse,

After a Maven clean, maven install & maven build on the project.
i get a few errors in console:

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.

In stackoverflow i see that someone has added manually this jar file?
Is it not a job for maven, because the dependency is in the pom?

--------------------------------------

...

2013-12-25 20:32:55.209:INFO:oejs.Server:jetty-8.1.11.v20130520
2013-12-25 20:32:56.168:WARN:oejw.WebAppContext:Failed startup of context o.m.j.p.JettyWebAppContext{/api,file:/home/scorpio/Downloads/swagger-core-swagger-project_2.9.1-1.3.0-RC1/samples/java-jaxrs/target/swagger-java-sample-app_2.9.1-1.3.0-RC1/},file:/home/scorpio/Downloads/swagger-core-swagger-project_2.9.1-1.3.0-RC1/samples/java-jaxrs/target/swagger-java-sample-app_2.9.1-1.3.0-RC1/
java.util.zip.ZipException: invalid entry size (expected 6164 but got 4968 bytes)
    at java.util.zip.ZipInputStream.readEnd(ZipInputStream.java:386)
    at java.util.zip.ZipInputStream.read(ZipInputStream.java:156)
    at java.util.jar.JarInputStream.read(JarInputStream.java:195)
    at java.util.zip.ZipInputStream.closeEntry(ZipInputStream.java:100)
    at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:78)
    at java.util.jar.JarInputStream.getNextEntry(JarInputStream.java:130)
    at java.util.jar.JarInputStream.getNextJarEntry(JarInputStream.java:167)
    at org.eclipse.jetty.webapp.JarScanner.matched(JarScanner.java:162)
    at org.eclipse.jetty.util.PatternMatcher.matchPatterns(PatternMatcher.java:100)
    at org.eclipse.jetty.util.PatternMatcher.match(PatternMatcher.java:82)
    at org.eclipse.jetty.webapp.JarScanner.scan(JarScanner.java:84)

.....

INFO] Started Jetty Server
[INFO]
[INFO] --- maven-failsafe-plugin:2.6:integration-test (default) @ swagger-java-sample-app_2.9.1 ---
[INFO] No tests to run.
[INFO]
[INFO] --- jetty-maven-plugin:8.1.11.v20130520:stop (stop-jetty) @ swagger-java-sample-app_2.9.1 ---
[INFO]
[INFO] --- maven-source-plugin:2.1.2:jar-no-fork (attach-sources) @ swagger-java-sample-app_2.9.1 ---
[INFO]
[INFO] --- maven-javadoc-plugin:2.7:jar (attach-javadocs) @ swagger-java-sample-app_2.9.1 ---
2013-12-25 20:32:56.778:INFO:oejsh.ContextHandler:stopped o.m.j.p.JettyWebAppContext{/api,file:/home/scorpio/Downloads/swagger-core-swagger-project_2.9.1-1.3.0-RC1/samples

....

I get also this errors in Problems tab:

'/home/scorpio/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.1.5/jackson-databind-2.1.5.jar' in project 'swagger-java-sample-app_2.9.1' cannot be read or is not a valid ZIP file    swagger-java-sample-app_2.9.1       Build path  Build Path Problem

maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e.  pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

Plugin execution not covered by lifecycle configuration: net.alchim31.maven:scala-maven-plugin:3.1.0:add-source (execution: default, phase: initialize) pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

Plugin execution not covered by lifecycle configuration: net.alchim31.maven:scala-maven-plugin:3.1.0:testCompile (execution: default, phase: test-compile)  pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

-------

pom file:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <parent>
    <groupId>com.wordnik</groupId>
    <artifactId>swagger-project_2.9.1</artifactId>
    <version>1.3.0-RC1</version>
    <relativePath>../..</relativePath>
  </parent>
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.wordnik</groupId>
  <artifactId>swagger-java-sample-app_2.9.1</artifactId>
  <packaging>war</packaging>
  <name>swagger-java-jaxrs-app</name>
  <version>1.3.0-RC1</version>
  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-war-plugin</artifactId>
        <version>2.1.1</version>
      </plugin>
      <plugin>
        <artifactId>maven-failsafe-plugin</artifactId>
        <version>2.6</version>
        <executions>
          <execution>
            <goals>
              <goal>integration-test</goal>
              <goal>verify</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
      <plugin>
        <groupId>org.mortbay.jetty</groupId>
        <artifactId>jetty-maven-plugin</artifactId>
        <version>${jetty-version}</version>
        <configuration>
          <webAppConfig>
            <contextPath>/api</contextPath>
          </webAppConfig>
          <webAppSourceDirectory>target/${project.artifactId}-${project.version}</webAppSourceDirectory>
          <webDefaultXml>${project.basedir}/conf/jetty/webdefault.xml</webDefaultXml>
          <stopPort>8079</stopPort>
          <stopKey>stopit</stopKey>
          <connectors>
            <connector implementation="org.eclipse.jetty.server.nio.SelectChannelConnector">
              <port>8002</port>
              <maxIdleTime>60000</maxIdleTime>
              <confidentialPort>8443</confidentialPort>
            </connector>
          </connectors>
        </configuration>
        <executions>
          <execution>
            <id>start-jetty</id>
            <phase>pre-integration-test</phase>
            <goals>
              <goal>run</goal>
            </goals>
            <configuration>
              <scanIntervalSeconds>0</scanIntervalSeconds>
              <daemon>true</daemon>
            </configuration>
          </execution>
          <execution>
            <id>stop-jetty</id>
            <phase>post-integration-test</phase>
            <goals>
              <goal>stop</goal>
            </goals>
          </execution>
        </executions>
      </plugin>
    </plugins>
  </build>
  <dependencies>
    <dependency>
      <groupId>com.wordnik</groupId>
      <artifactId>swagger-jaxrs_2.9.1</artifactId>
      <scope>compile</scope>
    </dependency>
    <dependency>
      <groupId>org.slf4j</groupId>
      <artifactId>slf4j-log4j12</artifactId>
    </dependency>
    <dependency>
      <groupId>org.scalatest</groupId>
      <artifactId>scalatest_2.9.1</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
    </dependency>
  </dependencies>
</project>

Could someone give some extra info so that i can go on?
Thx

A: There are multiple issues according to your logs
2013-12-25 20:32:56.168:WARN:oejw.WebAppContext:Failed startup of context o.m.j.p.JettyWebAppContext{/api,file:/home/scorpio/Downloads/swagger-core-swagger-project_2.9.1-1.3.0-RC1/samples/java-jaxrs/target/swagger-java-sample-app_2.9.1-1.3.0-RC1/},file:/home/scorpio/Downloads/swagger-core-swagger-project_2.9.1-1.3.0-RC1/samples/java-jaxrs/target/swagger-java-sample-app_2.9.1-1.3.0-RC1/
      java.util.zip.ZipException: invalid entry size (expected 6164 but got 4968 bytes)

This simply means that th ZIP file is invalid/improper. Either it was not creates properly or an inturrupt occured during download. I would recommend deleting the file and re-creating/re-donwloading it
'/home/scorpio/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.1.5/jackson-databind-2.1.5.jar' in project 'swagger-java-sample-app_2.9.1' cannot be read or is not a valid ZIP file    swagger-java-sample-app_2.9.1       Build path  Build Path Problem

Delete this file and re-acquire it
maven-dependency-plugin (goals "copy-dependencies", "unpack") is not supported by m2e.  pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

Plugin execution not covered by lifecycle configuration: net.alchim31.maven:scala-maven-plugin:3.1.0:add-source (execution: default, phase: initialize) pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

Plugin execution not covered by lifecycle configuration: net.alchim31.maven:scala-maven-plugin:3.1.0:testCompile (execution: default, phase: test-compile)  pom.xml /swagger-java-sample-app_2.9.1  line 2  Maven Project Build Lifecycle Mapping Problem

All these errors points to one things, the limitation of the m2e eclipse plugin. There are certain plugin goals that are not covered by m2e plugin. THeres nothing much that you can do about it except make sure to verify that the wars are made properly with each build.


text:
Q: ¿Se puede redireccionar a CreateView y mandar argumentos a la vez? Muy buenas, tengo la siguiente duda
Si en una vista DetaiView de algún modelo A, quiero redireccionar a un vista CreateView pero de un medelo B
¿Cómo puedo pasar argumentos de una vista a otra?
Por ejemplo, dada las siguientes rutas
path('persona/<int:pk>/', PersonaDetailView.as_view(), name='persona-detail'),

necesito redireccionar a
path('create_paciente/', PacienteCreateView.as_view(), name='create-paciente')

¿Cómo puedo pasar el valores de los algunos campos de Objeto Persona (cualquiera sea el campo que se pueda necesitar) para que el formulario de la vista PacienteCreateView muestre información de la persona?
Por el momento, solo se me ocurre obtener el id del objeto de la vista DetaiView a través del método post
def post(self, request, *args, **kwargs):
    self.object = self.get_object()
    if "id" in request.POST:
        id = request.POST.get('id')
        return redirect('core:create-paciente')
    return self.get(request, *args, **kwargs)

Gracias.

A: te puedo sugerir esta solución:
Si tienes tu botón en el path 'persona-detail' que te lleva a la url 'create-paciente' podrías agregar un parámetro get en tu botón, por ejemplo:
Crear

Así estarías pasando el pk de la persona que estas viendo, posteriormente en tu PacienteCreateView para obtener ese parámetro seria:
def get(self, request, *args, **kwargs):
    persona_id = self.request.GET.get('persona_id', None) if self.request.method == 'GET' else None
    return super(PacienteCreateView).get(request, *args, **kwargs)

Con esto ya obtendrías el pk de la persona, ya dependiendo de lo que quieras hacer con ese id es el método que tendrías que utilizar o sobrescribir (get_context_data, get_initial, etc.)


text:
Q: "ELF: not found" and "syntax error: unexepected \"(\"" in Docker container I am trying to build a Docker image for beanstalkd-cli. The image builds successfully, but when I run docker run -it myimage, it fails with:
/usr/local/bin/beanstalkd-cli: line 1: ELF: not found
/usr/local/bin/beanstalkd-cli: line 2: syntax error: unexpected "("

Does this mean the build is bad? Or do I need to tweak ENTRYPOINT and/or CMD?
Here is my Dockerfile:
FROM alpine:3.5

LABEL maintainer="Coby Tamayo <ctamayo@sitecrafting.com"

# Install openssl, beanstalkd-cli
RUN apk add --update openssl && \
  wget https://github.com/schickling/beanstalkd-cli/releases/download/0.3.0/beanstalkd-cli-linux.tar.gz && \
  tar -xvzf beanstalkd-cli-linux.tar.gz && \
  chmod +x beanstalkd-cli && \
  mv beanstalkd-cli /usr/local/bin/beanstalkd-cli && \
  rm beanstalkd-cli-linux.tar.gz

ENTRYPOINT ["/bin/sh"]
CMD ["/usr/local/bin/beanstalkd-cli"]

Update 1
When I remove the ENTRYPOINT and CMD completely, running the container drops me into a shell, where I can verify that beanstalkd-cli has execute permissions set:
$ docker run -it myimage
/ # which beanstalkd-cli
/usr/local/bin/beanstalkd-cli
/ # ls -la /usr/local/bin/beanstalkd-cli
-rwxrwxr-x    1 1000     1000       3020529 Feb 23  2015 /usr/local/bin/beanstalkd-cli

Just "for fun," I also tried setting only ENTRYPOINT, with no command, since I really don't care about running anything except beanstalkd-cli commands in this container:
ENTRYPOINT ["/usr/local/bin/beanstalkd-cli"]
# no more CMD

When I docker run this, I get:
standard_init_linux.go:185: exec user process caused "no such file or directory"

Same result if I add the original CMD back in. Huh?
Update 2
# file /usr/local/bin/beanstalkd-cli
/usr/local/bin/beanstalkd-cli: ELF 64-bit LSB shared object, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.24, BuildID[sha1]=63a19b18574643c1da5bafd5bd56fc26af22ab05, not stripped

# uname -a
Linux 6882ec36481d 4.10.0-40-generic #44~16.04.1-Ubuntu SMP Thu Nov 9 15:37:44 UTC 2017 x86_64 Linux

# /usr/local/bin/beanstalkd-cli
/bin/sh: /usr/local/bin/beanstalkd-cli: not found

A: Diagnosing The Problem
Using your Dockerfile:
docker run 04d32bac400e '-xlic' 'ldd /usr/local/bin/beanstalkd-cli'

...emits:
+ ldd /usr/local/bin/beanstalkd-cli
    /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
    libdl.so.2 => /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
    libpthread.so.0 => /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
    librt.so.1 => /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
    libc.so.6 => /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
    libm.so.6 => /lib64/ld-linux-x86-64.so.2 (0x7f9044206000)
Error loading shared library libgcc_s.so.1: No such file or directory (needed by /usr/local/bin/beanstalkd-cli)
Error loading shared library ld-linux-x86-64.so.2: No such file or directory (needed by /usr/local/bin/beanstalkd-cli)
Error relocating /usr/local/bin/beanstalkd-cli: __gcc_personality_v0: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: __register_atfork: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: __rawmemchr: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_DeleteException: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_RaiseException: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_FindEnclosingFunction: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_GetIP: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_Backtrace: symbol not found
Error relocating /usr/local/bin/beanstalkd-cli: _Unwind_Resume: symbol not found

So -- the beanstalkd libraries you're using are linked against libgcc_s.so.1 and ld-linux-x86-64.so.2, neither of which is provided by the Alpine 3.5 base image; hence, "no such file or directory" when trying to run the executable.

The Easy Solution
Consider a heavier-weight base image; the following, for example, works properly:
FROM ubuntu:16.04

LABEL maintainer="Coby Tamayo <ctamayo@sitecrafting.com>"

# Install openssl, beanstalkd-cli
RUN apt-get update
RUN apt-get install -y wget
RUN wget https://github.com/schickling/beanstalkd-cli/releases/download/0.3.0/beanstalkd-cli-linux.tar.gz && \
  tar -xvzf beanstalkd-cli-linux.tar.gz && \
  chmod +x beanstalkd-cli && \
  mv beanstalkd-cli /usr/local/bin/beanstalkd-cli && \
  rm beanstalkd-cli-linux.tar.gz

CMD ["/usr/local/bin/beanstalkd-cli"]


text:
Q: Why does the member variable change after invoking the assignment operator in rapidjson? The source codes shown below is a part of checking members of an object of the Document class.
We tried to create an object of the Value Class that is 'memberObject' and to store the object reference into '_value' Value reference private member variable.
Looking at the outputs, we can see type of the object is 3 (Object).
However, after assigning _value reference variable with memberObject, the output shows the type changed to 0 (NULL).
We expect that type change like this should not happen.
Could you explain why this happens?

  for (Value::MemberIterator itr = _document.MemberBegin(); itr != _document.MemberEnd(); itr++)
  {
        _itr = itr;

        _name = itr->name.GetString();
        _objectTypeID = (int)itr->value.GetType();

        cout << "Member [" << _name << "] - type is [" << _objectTypeID << "]" << endl;

        _typeID = _objectTypeID;

        if (itr->value.IsObject())
        {
              Value& memberObject = _document[_name.c_str()];
              cout << "Value type(1): " << memberObject.GetType() << endl;

              _value = (Value&)memberObject;
              cout << "Value type(2): " << memberObject.GetType() << endl;
        }

        _st.push(_itr);

        parseValue();

        _itr = _st.top();  // returns the next element in the stack
        _st.pop();         // removes an element from the stack
  }

"firmwareSettings": {
    "manageFirmware": false,
    "firmwareBaselineUri": ""
},

Member [firmwareSettings] - type is [3]
Value type(1): 3
Value type(2): 0

A: This behavior is expected as the assignment operator for GenericValue uses move semantics.
Here is the assignment operator for GenericValue in rapidjson:
 //! Assignment with move semantics.
    /*! \param rhs Source of the assignment. It will become a null value after assignment.
    */
    GenericValue& operator=(GenericValue& rhs) {
        RAPIDJSON_ASSERT(this != &rhs);
        this->~GenericValue();
        memcpy(this, &rhs, sizeof(GenericValue));
        rhs.flags_ = kNullFlag;
        return *this;
    }

When memberObject is assigned to _value, the assignment operator kicks in changing the flags_ member which is the value returned by the GetType() method of the rvalue object.
For more details on move semantics, please see What are move semantics?


text:
Q: How do I add a citation to a URL in lyx and zotero Hi have created a bibtek file with my citations. All is well, but now I want to cite a web page. In use the Zotero add-on of firefox. I am on the web page, and I right click on the down-arrow 2 positions right of the Z (for Zotero, on the toolbar.) Then I click "Save to Zotero using Embedded metadata". Sure enough, the web page appears in Zotero at the bottom half of the screen. Now rightclick on my collection, and export it to bibtex. I can see the .bib file in the editor, and there it is:
@misc{lewis_stephen_????,
title = {Stephen {Hawking}: {Artificial} {Intelligence} {Could} {End} {Human} {Race}},
shorttitle = {Stephen {Hawking}},
url = {http://www.livescience.com/48972-stephen-hawking-artificial-   intelligence-threat.html},
abstract = {Famed British physicist Stephen Hawking warned that artificial intelligence could be a threat to mankind.},
urldate = {2016-05-23},
journal = {Live Science},
author = {Lewis, Tanya and 2, Staff Writer {\textbar} December and ET, 2014 11:48am},
note = {00000},
file = {Snapshot:/home/michel/.mozilla/firefox/pongdlp4.default/zotero/storage/F72MJHIK/48972-stephen-hawking-artificial-intelligence-threat.html:text/html}
}

That is looking good.
Now to lyx. I do
Add Citation. I can choose lewis_stephen_????. These 4 question marks do not look auspicious, but nevertheless, I add the citation. Then I preview my pdf, and I see the citation in the bibliography, BUT not the url.
I did put
\usepackage{url}

in the latex preamble, but this does not help. I have read this post
 http://tex.stackexchange.com/questions/35977/how-to-add-a-url-to-a-latex-bibtex-file

but I do not see anything that works for me. This suggestion works for me (the url in in the pdf)
 howpublished={\url{http://my.url.com/}}

But I do not want to edit the bibtek file manually, because it would get overwritten. And besides (curiously) it prints the "="  sign before the url in the output.
Any suggestions much appreciated.
Michel


text:
Q: Regex with capturing groups I'm trying to extract file names from a long text.

*

*The filenames are all in a path

*The path is always prefixed with the text Page source

*They can appear anywhere on a line

*The text contains multiple lines

*All filenames end with .html
Given the following text:
Page source file:///somedir/subdir/subdir/mysource.html lorem ipsum more text
Lorem Ipsum ...
Lorem Ipsum Page source file:///anotherdir/sub/dir/anothersource.html

I want a list of all the file names:
mysource.html
anothersource.html

I've been trying to get it with the following regular expressions:
// this only gets the last one (because of the greedy .*)
Page source.*\/(.*\.html)

// This gets all occurrences, but the value in my capture group is the
// complete path starting after the first occurrence of /
Page source.*?\/(.*?\.html)

How can I tell the regex engine to be non-greedy for the outside expression, but still greedy enough to go to the last / before the .html part?

A: Page source.*?([^\/]+?\.html)

Demo: https://regex101.com/r/uX6fY2/2


text:
Q: redirect from checking password I have a very basic website with the idea of a quick and easy way to quickly send to a page and I don't know how to do that.
so I have:
<form class="passform" action="" onsubmit="return passcheck()">
    password: <input type="password" required id="pass1">
    <input type="submit">
    </form>

in the HTML with the flowing in js
var password = "%Password%";
const submit = document.getElementById("pass1")

function passcheck () {
    if(submit.value != password) {
        alert('Wrong Password, Try Again.')
        return false
    }
}

function passcheck () {
    if(submit.value == password) {

    alert('Correct Pasword, lets go')
    window.location.href="/pic/index.html";
}}

A: You don't need to return nothing, just redirect if is equal and print message if not, like:

var password = "%Password%";
const submit = document.getElementById("pass1");
function passcheck() {
  if (submit.value == password) {
    alert('Correct Pasword, lets go')
    window.location.href = "/pic/index.html";
  } else {
    alert('Wrong Password, Try Again.')
  }
}
<form class="passform" action="" onsubmit="event.preventDefault();passcheck()">
  password: <input type="password" required id="pass1">
  <input type="submit">
</form>

I simple add event.preventDefault() (i change inline method with EventListener) for prevent submit and check if password is equal continue else print message
The real question is, Are you sure of this method? is insecure.