text:
Q: Debug iPad app with SSL in VS through Fiddler/IIS Express - Breakpoints not being hit I have an iOS device connected to my computer via proxy with Fiddler set to allow remote computers to connect.
Fiddler Hosts is set up to remap the original target host to my localhost on ssl:
127.0.0.1:443
As per Hansellman's article I've opened the correct port and have configured the bindings for ssl.
I can see from Fiddler that my code is being hit and is responding as expected however, I have been unable to get the breakpoints to hit so that I can step through (which is what I'm trying to achieve).  I have checked that the debugger is attached to IIS Express, and it all looks fine.
I believe this is something to do with IISExpress/VS as when the site was set completely in IIS (not express) the breakpoints were hit which leads me to suspect it's something to do with the extra legwork to make IISExpress work with ssl on port 443.
Is there some way to get the debugger to work with this?
Thankyou in advance!


text:
Q: Fire an action after all actions in redux-observable epic I want to fire an action after all actions happened. Here is my code:
 public fetchCategories(action$: Observable<ICategoryAction>, store: Store<IAppState>) {
    return action$.pipe(
      ofType(CategoryActionType.FETCH_CATEGORIES),
      switchMap((action) => {
         return this._categoryService.list(action.payload)
      }),
      flatMap(data => [
        this._categoryAction.addCategories(new Categories(data)),
      ])
    ).catch((error) => {
      return Observable.of(this._commonAction.showError(error));
    })
    .concat(Observable.of(this._commonAction.hideLoading())); // <<== Doesn't work
   }

I want to hide loading after success or error in catch. But it doesn't concat with last actions. I can see everything work well until addCategories().
However it doesn't call concat.

A: What you have won't work because concat subscribes to its inner Observable only after the source Observable completes. action$ is in fact a Subject that never completes (this would mean it can't emit any more actions). The same case is with the catch you have.
This largely depends on what the structure of your actions is but you can do something as the following:
action$.pipe(
  ofType(CategoryActionType.FETCH_CATEGORIES),
    switchMap((action) => this._categoryService.list(action.payload)
      .pipe(
        catchError(() => of(this._commonAction.showError(error)))
      ),
    }),
    mergeMap(data => [
      this._categoryAction.addCategories(new Categories(data)),
      of(this._commonAction.hideLoading()),
    ])

I'm actually guessing what your code should do because I don't know what .addCategories returns. mergeMap on an array will just flattens it which is probably wanted to do (but with one array item you could use just map)?
Btw be aware that you're mixing pipable and prototype operators: https://github.com/ReactiveX/rxjs/blob/master/doc/pipeable-operators.md

redpajama_set_name: RedPajamaStackExchange


text:
Q: react native: there is way to handle an input text and save it into the NOTE var of the postData function? there is way to handle an input text from "Modal2" component and send it into the "NOTE" var of the "postData" function ?
 my mission is when i will press on "Cancel" in "OrderInformationScreen" screen so it will open the "Modal2" and when i will press ok inside this modal so it will send the input text of the "Modal2" into the "NOTE" var that inside the "OrderInformationScreen" screen .
this is the "OrderInformationScreen" screen:
export default class OrderInformationScreen extends Component {
  constructor(props) {
    super(props);
    const { state } = props.navigation;
    this.state = {
      title: state.params.data, //navprops.params.data.SHORT_TEXT
      list: [],
      currentIndex: state.params.itemIndex || 0,
      initialIndex: state.params.itemIndex
    };
    // console.log(JSON.stringify(state.params));
  }

  componentDidMount() {
    const list = InfoStore.getList;
    // console.log("InfoStore getList", list.slice(), this.state.currentIndex);
    this.setState({ list });
  }

  postData = key => {
    const { list, currentIndex } = this.state;
    const ACTOR_ID = list[currentIndex]["ACTOR_ID"];
    const WORK_ITEM_ID = list[currentIndex]["WI_ID"].toString();
    // console.log("ACTOR_ID", currentIndex, ACTOR_ID, WORK_ITEM_ID);
    var REPORT_KEY = key == "Cancel" ? "002" : "001"; //לשתול כסטרינג 001 לאישור ו 002 לדחיה - לבצע עם תנאי
    var NOTE = key == "Cancel" ? this.state.cancelInput : "";
    const pre =
      "https://harigotphat1.mekorot.co.il/ConfirmPackaotWS/OrderApprove/OrderApp_Save_Approvement/ACTOR_ID%2C%20REPORT_KEY%2C%20WORK_ITEM_ID%2C%20NOTE?";
    let params =
      "ACTOR_ID=" +
      ACTOR_ID +
      "&REPORT_KEY=" +
      REPORT_KEY +
      "&WORK_ITEM_ID=" +
      WORK_ITEM_ID +
      "&NOTE=" +
      NOTE;
    const url = pre + params;
    // console.log("THE URL IS>>>>>>>>>", params);
    const axios = require("axios");
    axios.get(url).then(response => {
    //   console.log("roei response======>>>>", response);
      const newList = list.slice();
      newList.splice(currentIndex, 1);

      InfoStore.setList(newList);
    //   console.log("newList", newList);
      this.props.navigation.goBack();
    });
  };

  onSwiperIndexChanged = index => {
    // console.log("onSwiperIndex", index);
    this.setState({ currentIndex: index });
  };

  render() {
    // console.log("render this.state.currentIndex", this.state.currentIndex);
    return (
      <>
        <View
          style={{
            alignItems: "flex-start",
            justifyContent: "center",
            borderColor: "blue",
            flexDirection: "row",
            justifyContent: "space-evenly"
          }}
        >
          <TouchableOpacity
            onPress={() => this.postData("Cancel")}
            disabled={this.state.list.length == 0}
          >
            <Avatar
              size="large"
              containerStyle={{ marginTop: 30 }}
              activeOpacity={0.2}
              rounded
              source={require("../assets/down.png")}
              style={{ height: 80, width: 80 }}
              // onPress={() => console.log("cancel!")}
            />
            <View>
              <Text style={{ fontSize: 25, fontWeight: "bold", color: "red" }}>
                Cancel
              </Text>
            </View>
          </TouchableOpacity>
          <TouchableOpacity
            onPress={() => this.postData("Confirm")}
            disabled={this.state.list.length == 0}
          >
            <Avatar
              size="large"
              activeOpacity={0.1}
              rounded
              source={require("../assets/up.png")}
              style={{ height: 80, width: 80 }}
              // onPress={() => console.log("Works!")}
            />
            <View>
              <Text
                style={{
                  fontSize: 25,
                  fontWeight: "bold",
                  color: "green",
                  marginHorizontal: 6
                }}
              >
                Cnfirm
              </Text>
            </View>
          </TouchableOpacity>
        </View>
        {this.state.list.length > 0 && (
          <Swiper
            style={styles.wrapper}
            showsButtons={false}
            onIndexChanged={this.onSwiperIndexChanged}
            index={this.state.list.length - this.state.initialIndex - 1}
          >
            {this.state.list.map((item, index) => (
              <InfoTable key={index} headerInfo={item}></InfoTable>
            ))}
          </Swiper>
        )}
      </>
    );
  }
}

this is the Modal2:
export default class Modal2 extends Component {
  state = {
    placeName: "",
    visibleModal: 3,
  };

  placeNameChangedHandler = val => {
    this.setState({
      placeName: val
    });
  };

  render() {
    return (
      <View style={styles.container}>
      <Modal>
        <LinearGradient
              colors={['#43D4FF', 'white']}
              style={{ borderRadius: 10 }}>
          <View style={styles.modalContent}>
          <Text>reson</Text>
        <TextInput
          style={{width: 300,height:100}}
          placeholder="write here"
          value={this.state.placeName}
          onChangeText={this.placeNameChangedHandler}
        />
        </View>
        <View style={{flexDirection: "row" ,marginLeft: 20, justifyContent: 'space-evenly',marginBottom:20}}>
    <Button
          title="ok"
          onPress={() => Alert('ok Button pressed')}
        />
    <Button
          title="cancel"
          onPress={() => Alert('not ok Button pressed')}
        />
</View>
         </LinearGradient>
        </Modal>
      </View>
    );
  }
}


text:
Q: Select aumentando a largura ao escolher item estou com problema nesse código:
    <v-row>
      <v-col class="d-flex align-center" cols="12">

Situação familiar:

        <v-select
          v-model="selectedFamilySituation"
          :items="itemsFamilySituation"
          solo
          dense
        ></v-select>
      </v-col>
    </v-row>

Resumindo tenho uma label seguida de um select. O problema é que um dos items do select é uma string muito grande, logo toda vez que seleciono esse item o select aumenta sua largura ficando assim desalinhado.

Como posso resolver isso?

A: Galera, consegui resolver. A label que vem antes do select ela tem tamanho fixo de 98px, logo quando eu escolho o item com string gigante, a largura do select aumenta os 98px que a label ocupa.
Coloquei isso no select:
style="max-width: calc(100% - 98px);"

Pronto :D


text:
Q: Fix ESLint no-plusplus and no-param-reassign linter errors when adding to accumulator in reduce function Give this code in TypeScript:
const res = arr.reduce((acc, cur) => (cur.id ? ++acc : acc), 0);

How do I stop the linter throwing these two errors?

(parameter) acc: number Unary operator '++' used. eslint no-plusplus

Assignment to function parameter 'acc'. eslint no-param-reassign

A: A reduce callback accepts an accumulator and the current value as arguments and returns the accumulator for the next iteration, or the accumulator as a result if there is no next iteration. There is no reason to mutate any of the arguments.
There are a few arguments in favor of avoiding mutating parameters in general, and that's why ESLint complains about this, with the no-param-reassign rule.
The no-plusplus rule, additionally, disallows syntax like ++acc.
Since there is no need to mutate acc to begin with, the minimal fix for both errors would be:
   const res = arr.reduce((acc, cur) => (cur.id ? acc + 1 : acc), 0);
//                                                ~~~~^~~              Replace `++acc` by `acc + 1`

This returns acc incremented by 1 if cur.id is truthy, and the current acc, otherwise, as expected. Your version mutates the current acc in addition to returning the incremented acc, but there is no reason to do so.

If you're using ESLint, you have to be aware of the rules. You can't write code that ESLint complains about and then be confused why ESLint complains about your code. Every rule has its own article explaining the rationale, listing alternatives, and explaining how the rule can be adjusted or disabled.
For example, you can disable the no-param-reassign rule

*

*by including the comment // eslint-disable no-param-reassign at the top of your file,

*or // eslint-disable-next-line no-param-reassign one line above a usage,

*or // eslint-disable-line no-param-reassign in the line after a usage,

*or by disabling it in your .eslintrc file.

There's also a rule that would disallow conditional expressions and some variants. You can further simplify your function to avoid even that:
const res = arr.reduce((acc, cur) => acc + Number(Boolean(cur.id)), 0);

This would have the same semantics, but it's still not quite clear what kind of condition cur.id was supposed to be. It's best practice to make that a little more explicit (especially in TypeScript), e.g. cur.hasOwnProperty("id") or cur.id !== 0 or cur.id !== "", depending on what cur.id may be. Then, the Boolean call is no longer necessary; for example, if you want to count how many objects in arr have an id own property, use this instead:
const res = arr.reduce((acc, cur) => acc + Number(cur.hasOwnProperty("id")), 0);

or this:
const res = arr.filter((cur) => cur.hasOwnProperty("id")).length;

If you still want to use your original falsy / truthy check, the code can be shortened to one of these, using destructuring assignment:
const res = arr.reduce((acc, {id}) => acc + Number(Boolean(id)), 0);

const res = arr.filter(({id}) => id).length;


text:
Q: Как добавить checked элементу (jquery) Как добавить элементу псевдокласс checked на jquery?
Имеется проверка:
$( init );
  function init() {
    if ( $('.lang-de').hasClass('active');
}

Как дальше дописать этот скрипт, чтобы добавить нужному input псевдокласс checked?

A: Исходя из исходного описания можно сделать как-то так:

$(document).ready(function() {
  if ($('.lang-de').hasClass('active')) {
    $('input.needed').attr('checked', 'checked');
  };
});

De

<input type="checkbox" class="no-needed" />
<input type="checkbox" class="needed" />


text:
Q: Wordpress: where to register custom post types? The docs clearly mention how to create a new post type with register_post_type but fails to mention in which file the code should go.
Anyone know where?

A: In the example at the bottom of the page, register_post_type is called from the init hook.


text:
Q: python requests error: Content is not allowed in prolog Basically if I run a command curl:
curl -k -u user:pass --header 'Content-Type: application/xml' --request POST --data '<LocalIDs><LocalID ID="9128615"/></LocalIDs>' --url https://rhtpcapc001:8182/pc/center/webservice/datasources/dataSourceConsoleName/Data%20Aggregator%40RHTPCADA201/itemids

I have the following answer:
<?xml version="1.0" encoding="UTF-8"?><ItemIDResults><ItemIDResult
LocalID="9528017" ItemID="828570"/></ItemIDResults>

I made a script in python to run this command:
#!/usr/bin/python

import requests
import urllib3

urllib3.disable_warnings()

headers = {
'Content-Type': 'application/xml',
}

data = {
'<LocalID ID': '"9528017"/>'
}

response = requests.post('https://rhtpcapc001:8182/pc/center/webservice/datasources/dataSourceConsoleName/Data%20Aggregator%40RHTPCADA201/itemids', headers=headers, data=data, verify=False, auth=('user', 'pass'))

print (response.encoding)
print (response.headers['Content-Type'])
print (response.headers)
print (response.text)
print (response.content)
print (response.reason)`

and gives me the following error:

ISO-8859-1 text/plain {'Set-Cookie':
  'JSESSIONID=md1waumsuoe81jceaxacbqgid;Path=/pc;Secure', 'Expires':
  'Thu, 01 Jan 1970 00:00:00 GMT', 'Content-Type': 'text/plain', 'Date':
  'Tue, 09 Apr 2019 10:28:54 GMT', 'Content-Length': '173', 'Server':
  'Jetty(9.3.5.v20151012)'} JAXBException occurred : ParseError at
  [row,col]:[1,1] Message: Content is not allowed in prolog.. ParseError
  at [row,col]:[1,1] Message: Content is not allowed in prolog..
  b'JAXBException occurred : ParseError at [row,col]:[1,1]\nMessage:
  Content is not allowed in prolog.. ParseError at
  [row,col]:[1,1]\nMessage: Content is not allowed in prolog.. ' Bad
  Request

I think the problem is the encoding. When I run only the command curl:
COMMAND:
curl -k -u user:pass --header 'Content-Type: application/xml' --request POST --data '<LocalIDs><LocalID ID="9128615"/></LocalIDs>' --url https://rhtpcapc001:8182/pc/center/webservice/datasources/dataSourceConsoleName/Data%20Aggregator%40RHTPCADA201/itemids

OUTPUT:
<?xml version="1.0" encoding="UTF-8"?><ItemIDResults><ItemIDResult LocalID="9528017" ItemID="828570"/></ItemIDResults>

in the answer we see encoding ="UTF-8"
in the python script with the response.encoding I see the encoding ISO-8859-1
thank you in advance for all the help.
BR
David


text:
Q: Submit Button won't appear UPDATE: Here it is my code so far. The download buttons now appear, but the code is printing the form closing tag instead of identifying it as a closing tag. How can I correct this? Please help. Thanks in advance!!

    <meta charset="utf-8">
    <link rel="stylesheet" href="css/style2.css">
    <TITLE>SAE Report</TITLE>

SAE Report

 <form action = "" method = "post">
 Report Type
    <select id="report" name="report">
        <option value="none"></option>
        <option value="new">New SAEs Report</option>
        <option value="cumulative">Cumulative SAE Report</option>
    </select>
 Start Date<input type="text" class="datepicker" name="start">
 End Date<input type="text" class="datepicker" name="end">
 <input type="submit" name="submit" value="Submit">
 </form>

 <?php
 $type='';
 $start='';
 $end='';

  if (isset($_POST['submit'])){

    $type=$_POST['report'];
    $start=$_POST['start'];
    $end=$_POST['end'];

    if ($type=="cumulative"){
        echo "<form action='cumulativeRptExcel.php' method='post' name ='xls'>";
        echo "<input type='submit' name='submitXLS' value='Download Excel'/>";
        echo "/form>
";
        echo "<form action='cumulativeRptPDF.php' method='post' name ='xls'>";
        echo "<input type='submit' name='submitXLS' value='Download PDF'/>";
        echo "/form>
";
    }
    elseif($type=='new' and $start!='' and $end!=''){
        echo "<form action='newRptExcel.php' method='post' name ='xls'>";
        echo "<input type='submit' name='submitXLS' value='Download Excel'/>";
        echo "/form>
";
        echo "<form action='newRptPDF.php' method='post' name ='xls'>";
        echo "<input type='submit' name='submitXLS' value='Download PDF'/>";
        echo "/form>
";
    }
    elseif($type="new" and ($start=='' or $end=='')){
        echo "You need to select START and END date for the report";
    }

}

?>

The report.php files contains the code to generate the excel or pdf file and make it downloadable to the user. When running those files by themselves it generates the files just fine.

A: Change your submit button from:
 <input type="submit" value="Submit">

to
 <input type="submit" name="submit" value="Submit">

The reason behind this is the $_POST variable will only have elements that had a name inside the previous form. In your example the submit button does not have a name.

A: It prints /form> because from your codes that's what you asked it to print. You echoed out "/form>
"; instead of "</form>
"; in every line that I can see. Simply add < to fix that


text:
Q: Java ArrayList Middle How to find the middle of an ArrayList ?

A: If you have N items, the middle item is usually defined as item at index N/2 (0-based).
10 items
0,1,2,3,4,5,6,7,8,9
          |
          5

13 items
0,1,2,3,4,5,6,7,8,9,0,1,2
            |
            6

Generally, if you need to find the middle of items between index low (inclusive) and high (exclusive), it's mathematically int mid = (low + high) / 2. But due to arithmetic overflow in limited-precision integer, the proper formula is int mid = (low + high) >>> 1;
See also

*

*Google Research Blog post by Josh Bloch

*

*Extra, Extra - Read All About It: Nearly All Binary Searches and Mergesorts are Broken

A: ArrayList.size()/2

A: If the size of ArrayList is even in number, then use
     (ArrayList.size()/2)+1 or    (ArrayList.size()/2) as the middle.
If the size of ArrayList is odd in number, then use     (ArrayList.size()+1)/2 as the middle.


text:
Q: How can I get my program to just count a word that is by itself while using a do-while loop? I am trying to make a program that finds a 'profane' word (which is 'cat' in this case) and say how many times it comes up in my input, and it works, except that it will count that profane word when it is embedded in a another word like 'conCATination'. Why is this the case? How can I get it to just count it when the word is by itself?
Edit: I forgot to mention it has to be done using if-else statements as well as using a loop Here is my program so far:
    private static Scanner keyboard = new Scanner(System.in);
    public static void main(String[] args) {
        String sentence = "";
        String word1 = "cat";
        int indexofSW1 = 0;
        int currentlocation = 0;
        int sentenceLength = 0;
        int word1Count = 0;
        int word1Length;
        System.out.println("Please enter a sentence.");
        sentence = keyboard.nextLine().toLowerCase().trim();
        word1Length = word1.length();
        indexofSW1 = sentence.indexOf(word1 , indexofSW1);
        sentenceLength = sentence.length();
        char character1;
if (indexofSW1 >= 0)
            do { if (sentenceLength > indexofSW1 + word1Length)
            {
                character1 = sentence.charAt(indexofSW1 + word1Length);
                switch (character1) {
                case ' ':
                case '\'':
                case '\t':
                case '\"':
                case '.':
                case '?':
                case '<':
                case '>':
                case ',':
                case '[':
                case ']':
                case '{':
                case '}':
                case '(':
                case ')':
                case '-':
                case '_':
                case '\\':
                case '|':
                case '+':
                case '=':
                case '/':
                case '*':
                case '&':
                case '^':
                case '%':
                case '$':
                case '#':
                case '@':
                case '!':

    }
                 currentlocation = sentence.indexOf(word1, currentlocation);
                }

             if (currentlocation == 0 || currentlocation > 0)
             {
                    currentlocation += word1Length;
                    word1Count++;
            }
}while(currentlocation > -1 && currentlocation > sentenceLength);

 System.out.printf("You have profane word %s %d times in your sentence." , word1 , word1Count);}}

A: You might want to consider using regex in this example, as it seems to be much better choice:
String source = "cat at the beginning, in the middle cat too, concatenating at the end cat.";
Pattern p = Pattern.compile("(?<=\\b)+(cat)(?=\\b)+");    // "cat" preceded by one or more whitespace characters or word boundary and followed by this too.
Matcher m = p.matcher(source);     // Set matcher to match given pattern
int counter = 0;    // to count occurences of "cat" int given String
while(m.find()) {    // if match was found...
    counter++;    // increment counter
    System.out.println(m.group(1) + " beginning from index: " + m.start(1)); // print match to the console
}
System.out.println("Number of occurences: " + counter);    // print number of occurences of "cat"

Output that you get from this code:
cat beginning from index: 0
cat beginning from index: 36
cat beginning from index: 70
Number of occurences: 3

A: you can use pattern.matcher with regex
   String cat = "cat concatination cat cat. cat";
        Pattern pattern = Pattern.compile("cat | cat");
        Matcher matcher = pattern.matcher(cat);

        int count = 0;
        while (matcher.find())
            count++;

        System.out.println(count);    // prints 3


text:
Q: Setting Up Virtualenvwrapper in Scheduled Task I've a makefile target that depends on the environment having the VIRTUALENVWRAPPER_SCRIPT variable set. This works fine when I run it from a PythonAnywhere bash terminal. When I run the command from the scheduler the VIRTUALENVWRAPPER_SCRIPT variable is not set. To make the schedule work I manually set the variable in the schedule definition. See below. Is this the right way to make this work or am I missing something?
This is What I Put in the Schedule Line
VIRTUALENVWRAPPER_SCRIPT=/usr/local/bin/virtualenvwrapper.sh /bin/bash -c 'make yesterday_stats'


text:
Q: Modal window not scrollable

Modal title

         <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           ×
         </button>

         Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
         tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
         quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
         consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
         cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
         proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
         tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
         quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
         consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
         cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
         proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
         tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
         quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
         consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
         cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
         proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
         tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
         quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
         consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
         cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
         proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

         <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
         <button type="button" class="btn btn-primary">Save changes</button>

I'm using the template provided by Bootstrap to create a scrollable modal window on my website, but it does not give me a scrollbar. The modal simply extends past the end of the viewport height.
I've tried the bootstrap code example and it doesn't work.
I expected a scrollable modal window like showed in the demo (https://getbootstrap.com/docs/4.3/components/modal/) but I get a modal that extends past the height of the viewport's height.

A: I had a look through the Bootstrap documentation you pointed to and all your code seemed accurate. Using the browser's dev tool I saw that the modal is given a maximum height. That still didn't work. I came across this article which suggests that this is a bug in Chrome, and the way to fix it is to set a max-height on the modal-body class, and to set overflow-y to scroll:

.modal-body {
  max-height: 50vh;
  overflow-y: scroll;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModalScrollable">
  Launch modal
</button>

Modal title

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
           ×
         </button>

        Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
        in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing
        elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
        cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut
        labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur
        sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
        quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa
        qui officia deserunt mollit anim id est laborum.

        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        <button type="button" class="btn btn-primary">Save changes</button>

A: I ran into this as well using Bootstrap 4.0.0, and MichaelvE's answer does fix it. But the problem is gone when using the latest version of Bootstrap, 4.3.1. Since it seems this behavior is actually a Bootstrap bug, upgrading is probably the better long-term fix.


text:
Q: E-mail validation, e-mail cannot be repeated How can I validate e-mails that they cannot be repeated? Okay I can push them from server to the array. What's next? How can I compare them? At this moment I have only validation by regex.

A: Server should check if email unique or not, and send response. Client just check if it's an email and not just a text


text:
Q: KIF - tests failed on Xcode 7.3 My app pass all KIF tests on Xcode 7.2. But after I upgrade to Xcode 7.3 it all get fail.
Reason : App is not coming to foreground during tests on Xcode 7.3
But if I manually click on the app and take into foreground then all good.
So I assume there is no issue with the test cases.
If anyone has has encounter anything similar and has a solution please let know.
Thanks

A: by manually clicking it will build a previous 7.2 build not 7.3 .clean the code and build again it will work.


text:
Q: Accuracy issue in caffe I have a network which has 4 Boolean outputs. It is not a classification problem and each of them are meaningful. I expect to get a zero or one for each of them. Right now I have used the Euclidean loss function.
There are 1000000 samples. In the input file, each of them have 144 features, so there the size of the input is 1000000*144.
I have used batch size of 50, because otherwise the processing time is too much.
The output file is of the size 1000000*4, i.e. there are four output per each input.
When I am using the accuracy layer, it complains about the dimension of output. It needs just one Boolean output, not four. I think it is because it considers the problem as a classification problem.
I have two questions.
First, considering the error of the accuracy layer, is the Euclidean loss function suitable for this task? And How I can get the accuracy for my network?
Second,I gonna get the exact value of the predicted output for each of the four variable. I mean I need the exact predicted values for each test record. Now, I just have the loss value for each batch.
Please guide me to solve those issues.
Thanks,
Afshin
The train network is:
{ state {
 phase: TRAIN
}
 layer {
   name: "abbas"
   type: "HDF5Data"
   top: "data"
   top: "label"
   hdf5_data_param {
     source: "/home/afo214/Research/hdf5/simulation/Train-1000-11-     1/Train-Sc-B-1000-11-1.txt"
     batch_size: 50
   }
 }

 layer {
   name: "ip1"
   type: "InnerProduct"
   bottom: "data"
   top: "ip1"
   inner_product_param {
     num_output: 350
     weight_filler {
       type: "xavier"
     }
   }
 }

 layer {
   name: "sig1"
   bottom: "ip1"
   top: "sig1"
   type: "Sigmoid"
 }

 layer {
   name: "ip2"
   type: "InnerProduct"
   bottom: "sig1"
   top: "ip2"
   inner_product_param {
     num_output: 150
     weight_filler {
       type: "xavier"
     }
   }
 }

The test network is also:
       state {
       phase: TEST
       }
        layer {
        name: "abbas"
        type: "HDF5Data"
        top: "data"
        top: "label"
        hdf5_data_param {
         source: "/home/afo214/Research/hdf5/simulation/Train-1000-11-         1/Train-Sc-B-1000-11-1.txt"
          batch_size: 50
         }
        }

        layer {
         name: "ip1"
  type: "InnerProduct"
  bottom: "data"
  top: "ip1"
  inner_product_param {
  num_output: 350
  weight_filler {
   type: "xavier"
  }
 }
 }

  layer {
  name: "sig1"
  bottom: "ip1"
   top: "sig1"
   type: "Sigmoid"
 }

   layer {
     name: "ip2"
     type: "InnerProduct"
     bottom: "sig1"
     top: "ip2"
     inner_product_param {
       num_output: 150
       weight_filler {
         type: "xavier"
       }
     }
   }

   layer {
     name: "sig2"
     bottom: "ip2"
     top: "sig2"
     type: "Sigmoid"
   }

   layer {
     name: "ip4"
     type: "InnerProduct"
     bottom: "sig2"
     top: "ip4"
     inner_product_param {
       num_output: 4
       weight_filler {
         type: "xavier"
       }
     }
   }
   layer {
     name: "accuracy"
       type: "Accuracy"
         bottom: "ip4"
          bottom: "label"
             top: "accuracy"
             }

   layer {
     name: "loss"
     type: "EuclideanLoss"
     bottom: "ip4"
     bottom: "label"
     top: "loss"
   }

And I get this error:

accuracy_layer.cpp:34] Check failed: outer_num_ * inner_num_ ==  bottom[1]->count() (50 vs. 200) Number of labels must match number of   predictions; e.g., if label axis == 1 and prediction shape is (N, C, H,   W), label count (number of labels) must be N*H*W, with integer values in   {0, 1, ..., C-1}.

Without using the accuracy layer caffe gives me the loss value.

A: Should "EuclideanLoss" be used for predicting binary outputs?
If you are trying to predict discrete binary labels then "EuclideanLoss" is not a very good choice. This loss is better  suited for regression tasks where you wish to predict continuous values (e.g., estimating coordinated of bounding boxes etc.).
For predicting discrete labels, "SoftmaxWithLoss" or "InfogainLoss" are better suited. Usually, "SoftmaxWithLoss" is used.
For predicting binary outputs you may also consider "SigmoidCrossEntropyLoss".
Why is there an error in the "Accuracy" layer?
In caffe, "Accuracy" layers expects two inputs ("bottom"s): one is a prediction vector and the other is the ground truth expected discrete label.
In your case, you need to provide, for each binary output a vector of length 2 with the predicted probabilities of 0 and 1, and a single binary label:
layer {
  name: "acc01"
  type: "Accuracy"
  bottom: "predict01"
  bottom: "label01"
  top: "acc01"
}

In this example you measure the accuracy for a single binary output. The input "predict01" is a two-vector for each example in the batch (for batch_size: 50 the shape of this blob should be 50-by-2).
What can you do?
You are trying to predict 4 different outputs in a single net, therefore, you need 4 different loss and accuracy layers.
First, you need to split ("Slice") the ground truth labels into 4 scalars (instead of a single binary 4-vector):
layer {
  name: "label_split"
  bottom: "label" # name of input 4-vector
  top: "label01"
  top: "label02"
  top: "label03"
  top: "label04"
  type: "Slice"
  slice_param {
    axis: 1
    slice_point: 1
    slice_point: 2
    slice_point: 3
  }
}

Now you have to have a prediction, loss and accuracy layer for each of the binary labels
layer {
  name: "predict01"
  type: "InnerProduct"
  bottom: "sig2"
  top: "predict01"
  inner_product_param {
    num_outout: 2 # because you need to predict 2 probabilities one for False, one for True
    ...
}
layer {
  name: "loss01"
  type: "SoftmaxWithLoss"
  bottom: "predict01"
  bottom: "label01"
  top: "loss01"
}
layer {
  name: "acc01"
  type: "Accuracy"
  bottom: "predict01"
  bottom: "label01"
  top: "acc01"
}

Now you need to replicate these three layer for each of the four binary labels you wish to predict.


text:
Q: Trying to avoid "attack reported by Rack::Protection::AuthenticityToken" message I have a new Padrino 0.13.1 project that I am hosting on an AWS Elastic Beanstalk worker instance. The worker instance has a cron job that calls a POST every 5 minutes in my Padrino app. I have defined the routine as follows:
post :myroutine, :with => :myparams, :csrf_protection => false do
  # ... do some stuff
  status 200
end

I have also configured /config/apps.rb as follows:
Padrino.configure_apps do
  set :session_secret, '...'
  set :protection, :except => :path_traversal
  set :protection_from_csrf, true
  set :allow_disabled_csrf, true
end

The worker instance does a post to http://localhost:80/myroutine/somevar every 5 minutes. The nginx access.log file shows:

127.0.0.1 - - [21/Mar/2016:04:49:59 +0000] "POST /myroutine/01234 HTTP/1.1" 200 0 "-" "aws-sqsd/2.0" "-"

But in my AWS production.log file, I also see this come up every 5 minutes:

WARN - 21/Mar/2016 04:49:59 attack reported by Rack::Protection::AuthenticityToken

Strangely, the routine executes fine, and does what it is supposed to do. I would just like to stop my log file from filling up with the Rack::Protection error every 5 minutes.
Is this because of a misconfigured csrf setting somewhere, or a bug?

A: it is caused by nginx reverse proxy setting.
which may lost http related information , result session information lost.
https://github.com/znc/znc/issues/946
i just add below line and it works :
proxy_set_header        X-Real_IP       $remote_addr;
proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header        X-NginX-Proxy   true;
proxy_set_header        Host            $http_host;
proxy_set_header        Upgrade         $http_upgrade;
proxy_pass_header       Set-Cookie;


text:
Q: Loop não está repetindo como deveria Estou criando um código que lê o número digitado pelo usuário e, se for de 1 a 10, ele realiza a tabuada, apresentando valor a valor na tela, além de permitir o usuário escolher se deseja verificar alguma outra tabuada.
A primeira vez, roda tranquilamente. Entretanto, se o usuário opta por fazer uma nova consulta, o programa solicita o novo número mas não apresenta os novos valores, ficando travado no loop condicional.
Segue lógica utilizada por mim:
static void Main(string[] args)
{
    int cont = 1, valor, auxiliar, continuar = 1;

    while (continuar == 1)
    {
        Console.WriteLine("Digite um numero de 1 a 10: ");
        valor = int.Parse(Console.ReadLine());

        if (valor <= 10)
        {
            while (cont <= 10)
            {
                auxiliar = valor * cont;
                Console.WriteLine(valor + " X " + cont + " = " + auxiliar);
                cont++;
            }

            Console.WriteLine("Deseja verificar a tabuada de algum outro número? Digite 1 para SIM ou 2 para NAO");
            continuar = int.Parse(Console.ReadLine());
            Console.ReadKey();
        }
        else
        {
            Console.WriteLine("Número inválido! ");
        }
    }
}

A: É porque você inicia cont fora do while principal e não volta o valor dele pro inicial. Isso faz com que o while interno não seja executado, já que a condição dele é que a variável cont seja menor ou igual a 10.
public static void Main(string[] args)
{
    int cont, valor, auxiliar, continuar = 1;
    while (continuar == 1)
    {
        Console.WriteLine("Digite um numero de 1 a 10: ");
        valor = int.Parse(Console.ReadLine());

        if (valor <= 10)
        {
            cont = 1;
            while (cont <= 10)
            {
                 auxiliar = valor * cont;
                 Console.WriteLine(valor + " X " + cont + " = " + auxiliar);
                 cont++;
            }

            Console.WriteLine("Deseja verificar a tabuada de algum outro número? Digite 1 para SIM ou 2 para NAO");
            continuar = int.Parse(Console.ReadLine());
        }
        else
        {
            Console.WriteLine("Número inválido! ");
        }
    }
}

Veja funcionando no Repl.it

A: Este código é pouco legível, tem variáveis demais, e elas estão declaradas muito antes de serem usadas o que complica o entendimento levando a erros.
Na verdade tem várias coisas que pode ser melhorado nele, inclusive é uma situação clara para usar um for e não um while.
Já que está fazendo verificações se a digitação está correta, faça por inteiro, e se alguém digitar algo que não seja um número? No momento seu código irá quebrar. Não. basta testar se o código funciona. Tem que estar o que não funciona, isto é muito mais importante. Use um TryParse().
Também modernizei o código. A maioria do material que ensina por aí está obsoleto, então aprenda fazer do jeito que se faz hoje.
Dá pra melhorar mais.
using static System.Console;

public class Program {
    public static void Main(string[] args) {
        int continuar = 1;
        while (continuar == 1) {
            WriteLine("Digite um numero de 1 a 10: ");
            int valor;
            if (int.TryParse(ReadLine(), out valor) && valor >= 1 && valor <= 10) {
                for (int cont = 1; cont <= 10; cont++) WriteLine($"{valor:D2} X {cont:D2} = {valor * cont:D2}");
                WriteLine("Deseja verificar a tabuada de algum outro número? Digite 1 para SIM ou 2 para NAO");
                if (int.TryParse(ReadLine(), out continuar)) continuar = 2;
            } else {
                WriteLine("Número inválido! ");
            }
        }
    }
}

Veja funcionando no ideone. E no .NET Fiddle. Também coloquei no GitHub para referência futura.


text:
Q: How to detect a desktop website when mobile website version is working using PHP? I downloaded a website template that includes separate layouts for mobile and desktop. I uploaded the files to the server and my mobile website works as it should but my desktop website does not work. The desktop website gives me an "internal server error". My error log states: "End of script output before headers: index.php". I tried messing with the .htaccess file but I do not think that is the problem.
My index.php file includes two PHP files that help detect which layout to use. These two files are config.php and detect.php which are in a folder called "app".
index.php
<?php
include "app/config.php";
include "app/detect.php";

if ($page_name=='') {
include $browser_t.'/index.html';
}
elseif ($page_name=='index.html') {
include $browser_t.'/index.html';
}
elseif ($page_name=='home.html') {
include $browser_t.'/home.html';
}
elseif ($page_name=='features.html') {
include $browser_t.'/features.html';
}
elseif ($page_name=='about.html') {
include $browser_t.'/about.html';
}
elseif ($page_name=='demo.html') {
include $browser_t.'/demo.html';
}
elseif ($page_name=='contact.html') {
include $browser_t.'/contact.html';
}
elseif ($page_name=='contact-post.html') {
include $browser_t.'/contact.html';
include 'app/contact.php';
}
else
{
    include $browser_t.'/404.html';
}

?>

app/config.php
<?php
$current_page_uri = $_SERVER['REQUEST_URI'];
$part_url = explode("/", $current_page_uri);
$page_name = end($part_url);
$email_id = "w3layouts@gmail.com";
?>

app/detect.php
<?php
$userBrowser = $_SERVER['HTTP_ACCEPT'];
if(stristr($userBrowser, 'application/vnd.wap.xhtml+xml'))
{
$_REQUEST['wap2'] = 1;
}

elseif(stripos($_SERVER['HTTP_USER_AGENT'],"iPod"))
{
$_REQUEST['iphone'] = 1;

}
elseif(stripos($_SERVER['HTTP_USER_AGENT'],"iPhone"))
{
$_REQUEST['iphone'] = 1;

}
elseif(stripos($_SERVER['HTTP_USER_AGENT'],"Android"))
{
$_REQUEST['Android'] = 1;

}
elseif(stripos($_SERVER['HTTP_USER_AGENT'],"IEMobile"))
{
$_REQUEST['IEMobile'] = 1;

}
elseif(stristr($userBrowser, 'DoCoMo/' || 'portalmmm/'))
{
$_REQUEST['imode'] = 1;
}

elseif(stristr($userBrowser, 'text/vnd.wap.wml'))
{
$_REQUEST['wap'] = 1;
}
elseif(stristr($userBrowser, 'text/html'))
{
$_REQUEST['html'] = 1;
}

 if(!defined('WAP'))
         define('WAP', isset($_REQUEST['wap']) || isset($_REQUEST['wap2']) ||   isset($_REQUEST['imode'])|| isset($_REQUEST['html'])|| isset($_REQUEST['Android'])|| isset($_REQUEST['iphone'])|| isset($_REQUEST['IEMobile']));

if (WAP)
{
define('WIRELESS_PROTOCOL', isset($_REQUEST['wap']) ? 'wap' : (isset($_REQUEST['wap2']) ? 'wap2' : (isset($_REQUEST['iphone']) ? 'iphone' : (isset($_REQUEST['imode']) ? 'imode' : (isset($_REQUEST['IEMobile']) ? 'IEMobile' :(isset($_REQUEST['html']) ? 'html' : (isset($_REQUEST['Android']) ? 'Android' : '')))))));

if (WIRELESS_PROTOCOL == 'wap')
  {
$browser_t = "mobile";
  }
elseif (WIRELESS_PROTOCOL == 'wap2')
  {

$browser_t = "mobile";

  }
elseif (WIRELESS_PROTOCOL == 'imode')
  {

$browser_t = "mobile";

  }
  elseif (WIRELESS_PROTOCOL == 'iphone')
  {

$browser_t = "smartphone";

  }
  elseif (WIRELESS_PROTOCOL == 'Android')
  {

$browser_t = "smartphone";

  }
   elseif (WIRELESS_PROTOCOL == 'IEMobile')
  {

$browser_t = "smartphone";

  }
  elseif (WIRELESS_PROTOCOL == 'html')
  {

 $mobile_browser = '0';

if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i',
strtolower($_SERVER['HTTP_USER_AGENT']))){
$mobile_browser++;
}

if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or
((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))){
$mobile_browser++;
}

$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-');

if(in_array($mobile_ua,$mobile_agents)){
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$mobile_browser++;
}
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'iemobile')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$mobile_browser=0;
}

if($mobile_browser>0){

// do something wap

$browser_t = "mobile";

}
// non-mobile
else
{

$_SESSION['Browser_d'] = "web";
$browser_t = "web";

}
   } else {

     // do something else html

$_SESSION['Browser_d'] = "web";
$browser_t = "web";
    }

  }

else
{
$mobile_browser = '0';

 if(preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone)/i',
strtolower($_SERVER['HTTP_USER_AGENT']))){
$mobile_browser++;
}

if((strpos(strtolower($_SERVER['HTTP_ACCEPT']),'application/vnd.wap.xhtml+xml')>0) or
((isset($_SERVER['HTTP_X_WAP_PROFILE']) or isset($_SERVER['HTTP_PROFILE'])))){
$mobile_browser++;
}

$mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'],0,4));
$mobile_agents = array(
'w3c ','acs-','alav','alca','amoi','audi','avan','benq','bird','blac',
'blaz','brew','cell','cldc','cmd-','dang','doco','eric','hipt','inno',
'ipaq','java','jigs','kddi','keji','leno','lg-c','lg-d','lg-g','lge-',
'maui','maxo','midp','mits','mmef','mobi','mot-','moto','mwbp','nec-',
'newt','noki','oper','palm','pana','pant','phil','play','port','prox',
'qwap','sage','sams','sany','sch-','sec-','send','seri','sgh-','shar',
'sie-','siem','smal','smar','sony','sph-','symb','t-mo','teli','tim-',
'tosh','tsm-','upg1','upsi','vk-v','voda','wap-','wapa','wapi','wapp',
'wapr','webc','winw','winw','xda','xda-');

if(in_array($mobile_ua,$mobile_agents)){
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'iemobile')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['ALL_HTTP']),'OperaMini')>0) {
$mobile_browser++;
}
if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'windows')>0) {
$mobile_browser=0;
}

    if($mobile_browser>0){
       // do something wap

$browser_t = "mobile";

}
// non-mobile
else
{
$_SESSION['Browser_d'] = "web";
$browser_t = "web";
}

}
 ?>

I believe the error is in the detect.php file but I am not sure how to fix it. Again, the mobile website works and the desktop website does not work. While troubleshooting, I was able to get the desktop to work but only when I removed everything in the detect.php file and left this:
<?php $_SESSION['Browser_d'] = "web";
$browser_t = "web";?>

Your help is much appreciated it.
Thanks,
Jon


text:
Q: How to explicitly indicate usage of default value of a named argument in a python function? Is it possible to explicitly tell a function in python to use the default value of a parameter ?
For instance, if a function is defined as:
def foo(a=1, b=2, c=3):
    pass

I would like to call the function like:
foo(a=3, b=<USE-DEFAULT>, c=10)
                ^
                |

which should be equivalent to:
foo(a=3, c=10)

One usage example is if a function is used to instantiate an instance of a class:
class foo():
    def __init__(a=1, b=2, c=3):
       self.a = a
       self.b = b
       self.c = c

def create_foo(a=None, b=None, c=None):
    f = foo( <PASS ALL EXCEPT NONE> )

F = create_foo(a=10, c=30)
# Then F should have a=10, b=2, c=30

In this example, I would like to avoid defining default values multiple times.

A: Just call that functions as
foo(a=3, c=10)

Alternatively, you could use the following approach, which is e.g. necessary for lists, because default values are evaluated in the module scope:
def foo(a=None, b=None, c=None):
    local_a = a or "default"
    ...

foo(a=42, b=None, c=16)

None then encodes to use the default, if None is no valid option.
Finally, you could just defined the defaults as "constants":
DEFAULT_A = 42
DEFAULT_B = "foo"
DEFAULT_C = 17

def foo(a=DEFAULT_A, b=DEFAULT_B, c=DEFAULT_C):
    pass

foo(16, DEFAULT_B, 123)

But this is quite uncommon.
For you updated example, I would propose to use * and ** operators:
def create_foo(*args, **kwargs):
    f = foo(*args, **kwargs)

create_foo(42, b="non-default")

See this question for explanations how these operators work.

A: If you don't use *args and **kwargs and subclassing there is no reason to explicitly call the defaults and as long as you are using only your own classes and you don't need mutual default arguments, you can just hand over the same values as the defaults - BUT if you are working with *args and **kwargs and the method to be called is from a super class, you might get problems with the MRO.
(See this article for further information: https://www.python.org/download/releases/2.3/mro/)
The only way I know to prevent a(n at this moment unknown) super class to pass an argument to the class your calss extends is to call the method explicidly and than hand over only the arguments you want it to get.
I don't see another use case for an explicit default call.

A: When defining function, you can set the default value, so when you call the function you do not need to pass the default argument to the function.
def foo(a=1, b=<USE-DEFAULT>, c=3):
    print(b)

foo(a=3, c=10)

In above function foo, you are actually setting the default value for all arguments a, b, c
example:
>>> def foo(a=1, b=2, c=3):
...     print('a: {0}, b: {1}, c: {2}'.format(a, b, c))
...
>>> foo(a=3, c=10)
a: 3, b: 2, c: 10
>>> foo()
a: 1, b: 2, c: 3
>>> foo(a=3)
a: 3, b: 2, c: 3
>>> foo(a=3, c=10, b=5)
a: 3, b: 5, c: 10
>>>


text:
Q: Умное слияние двух таблиц в sql Есть таблицы. Т1:
Предмет    | номер группы
Яблоко     | 1
Груша      | 1
Монитор    | 2
Клавиатура | 2
Чайник     | 3

и Т2:
Предмет | номер группы
Яблоко  | 1
Персик  | 1
Кактус  | 2
Монитор | 3
Мышь    | 3
Чайник  | 4

Нужно слить их в общую таблицу, сохранив сгруппированность, но переназначив индексы во второй таблице, чтобы получилась таблица Т3:
Предмет    | номер группы
Яблоко     | 1
Груша      | 1
Персик     | 1
Монитор    | 2
Мышь       | 2*
Клавиатура | 2
Чайник     | 3
Кактус     | 4*

То есть, перебирая по порядку вторую таблицу.

*

*Видим, что яблоко уже есть в Т1, причем с тем же индексом группы - пропускаем.

*Видим, что персика нет - добавляем, при этом даем номер группы тот же, что у яблока, т.к. они с ним в одной группе в Т2 и он есть в Т1, т.е. единицу.

*А вот, например, у мыши пришлось номер группы изменить. В таблице Т2 он равен 3. Но в Т1 группа компьютерных принадлежностей идет под номером 2. Это мы понимаем, т.к. есть пересечение по строке с монитором. В Т2 они в одной группе, а в Т1 у монитора номер группы - 2, значит переназначили на 2

*Кактус идет с группой 2 в Т2, но двойка уже занята в Т1, причем, у нас нет повода думать, что это та же группа, т.к. нет общих элементов у второй группы в Т1 и Т2, поэтому дали кактусу еще не занятый номер 4.

*С чайником из Т2 уже становится понятно. Он и так есть в Т1, поэтому пропускаем (хотя эта строка бы нам пригодилась, если бы попался в Т2 какой-нибудь тостер - 4 и мы бы поняли, что нужно в Т1 вставлять его с номером группы 3, как и чайник).

Надеюсь, ход мысли донес относительно прозрачно.

A: with cte as
(select * from t1 full join
(select num num1, subj subj1, (select num  from t2 where num = t.num group by num having count(*) >1
and exists(select 1 from t1 where t2.num=t1.num)) num2  from t2  t) t2
on t1.subj=t2.subj1)
select
coalesce(subj,subj1), case when subj is null
then
case when num2 is not null and exists (select 1  from cte cte1 where num is not null and cte1.num1=cte.num2 and cte.num1=cte1.num1)
          then (select min(num)  from cte cte1 where num is not null and cte1.num1=cte.num2 and cte.num1=cte1.num1)

else (select max(num) from cte)+rank() over(partition by num, case when num2 is null then 1 else 0 end order by num1)  end

else num end
from cte
order by 2;

A: select subj,
       coalesce(new_num, n1,
                dense_rank() over(order by n1, n2)+max(new_num) over()
               ) num
  from (
    select coalesce(t1.subj,t2.subj) subj, t1.num new_num, t2.num n2,
           first_value(t1.num) over(partition by t2.num order by t2.num desc, t1.num desc) n1
      from Table1 t1 full join Table2 t2 on t2.subj=t1.subj
  ) X
 order by num

Внимание: работа запроса чувствительна к порядку сортировки NULL значений, который отличается на разных СУБД. Запрос выше приведен для MS SQL. Для postgresql порядок сортировки во всех over() надо заменить на противоположный (пример на postrgesql).


text:
Q: how to export python files in Eclipse using pydev? I currently have a project in eclipse and Im using Pydev, and im trying to export all the source code..I know how to to export java files into a jar file but my question is how can you export python files in eclipse ? or can you even do that ? thanks

A: Python isn't like Java - it's an interpreted from the source files. Your *.py files are the only artefacts you need.
You may have seen *.pyc and *.pyo files around, but these are not needed, and don't inherently run faster than plain .py files. Read more here.
If you're looking to distribute your python code publicly, you may want to take a look at the python packaging documentation.


text:
Q: Create a second WebAccess RDS connection to servers already in a collection All of our staff who are working from home use Windows RD Web Access to connect in to our Remote Desktop Servers.
We currently have a 2012-r2 RD Broker with 1 collection consisting of 5 RDS 2012-r2 Servers and a second collection with just a Remote Apps Server. Currently the RDS collection is set-up to display the RDS session across all monitors available to the users machine that they are connecting from.
I need to set-up a second connection that when connecting will only use one monitor from the users machine when open the RDS Connection. This is so that users can have Video Conference hosted on their local machine on one monitor and the RDS connection on another. Not all users will need this so I can't just edit the existing connection.
I cannot create a second collection on the Broker as when I go through the create a new Collection wizard no servers appear until the "RD Session Host" step (presumably because they are all part of the first collection).
I cannot see anywhere in the properties of the first Collection to set-up a second RDS connection for that collection (where I can then change the property under Client Setting --> Max rediredcted Monitor).
Does anyone have any ideas of how I can get a second connection set-up for the same collection?

EDIT following Swisstone's Answer.
When the user open the RDP Connection from the WebAcess page they don't get to save the RDP connection as a RDP file. The users can only see the following options:
Is there a way to have the monitors option added to the "Show Details" section so that users can specify this?

A: You can't add a RD Session Host server to more than 1 collection.
However, your question is mainly about a client issue: in the Remote Desktop Connection client, just go to the "Display" tab, and uncheck "Use all my monitors for the remote session"


text:
Q: How do you get the cropped version of an image using ALAsset? I'm trying to get the cropped version of an image that's pulled using ALAsset. Specifically, I'm selecting items from the user's Photo Library and then uploading them. The issue is that in the library thumbnail view, iOS is showing us the cropped version. When you select that thumbnail and pull that image's asset using ALAsset, I get the full resolution version.
  I did some research and couldn't find anything that helps in getting a second coordinate system of where the cropping happens.
To test it, you need iOS5 to edit the image in your library. Select an image in your image library, select "Edit", and crop the image. When you get the ALAsset you'll get the full image, and if you sync using iPhoto, iPhoto also pulls the full image. Also, you can re-edit the image and undo your crop.
This is how I'm getting the image:
UIImage *tmpImage = [UIImage imageWithCGImage:[[asset defaultRepresentation] fullResolutionImage]];

That gives me the full resolution image, obviously. There's a fullScreenImage flag which scales the full resolution image to the size of the screen. That's not what I want.
The ALAssetRepresenation class has a scale field, but that's a float value, which is also what I don't want.
If anyone can tell me where this cropped coordinate system can be found, I'd appreciate it.

A: Your Options:
Option 1 (ALAssetLibrary)
Use the - (CGImageRef)fullScreenImage method of AlAssetRepresentation.
Pros:

*

*All the hard work is done for you, you get an image that looks just like the one in the Photos app. This includes cropping, and other changes.  Easy.

Cons:

*

*The resolution is "screen size", only as big as the device you are using, not the full possible resolution of the cropped image.  If this doesn't concern you, then this is the perfect option.

Option 2 (ALAssetLibrary)
Extract the cropping data using the AdjustmentXMP key in the image's metadata (what @tom is referring to). Apply the crop.
Benefit:

*

*It is possible to get a cropped image at the best possible resolution

Cons

*

*You only get the cropping edits, not any other adjustments (like red-eye)

*Who knows what Apple will support in the future in "Edit" mode, you may have to apply more edits in the future.

*It's complicated, you first have to parse the XML data to read the crop rectangle, crop the unrotated image, and then apply the rotation.

Option 3 (Wishful Thinking)
Beg Apple to include a method like fullResolutionEditedImage which gives you the best possible quality photo, with all edits applied.
Pros:

*

*Everything magically solved.

Cons:

*

*Apple may never add this method.

Option 4 (UIImagePickerController)
This option only applies if you are using the image picker, you can't use it directly with the asset library
In the NSDictionary returned by -(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
You can extract the full sized, adjusted image from the UIImagePickerControllerOriginalImage key.  Save this image somewhere. Then, instead of retrieving the image from the asset library, load the copy you made.
Pros:

*

*You get the full size image, with adjustments

*This is the only option Apple gives us for getting the full size image with all adjustments (like red-eye, etc), and not just the crop. This is particularly important in iOS 7 with the introduction of filters that can drastically alter the image.
Cons:

*

*Can only be used with the image picker (not ALAssetRepresentation)

*You must keep around a full-sized copy of the image. Depending on the number of such images, the disk usage by your app could grow substantially.

Update for iOS 7: you may wish to consider Option 4, or Option 1, as iOS 7 supports many operations now like filters, and your users will probably notice if they are missing. These two options support filters (and other edits), with Option 4 giving you a higher resolution result.

A: When a photo has been cropped with the iOS Photos App, the cropping coordinates can be found in the ALAssetRepresentation's metadata dictionary. fullResolutionImage will give you the uncropped photo, you have to perform the cropping yourself.
The AdjustmentXMP metadata contains not only the cropping coordinates but also indicates if auto-enhance or remove-red-eyes has been applied.
As of iOS 6.0 CIFilter provides filterArrayFromSerializedXMP:inputImageExtent:error: Probably you can use the ALAssetRepresentation's AdjustmentXMP metadata here and apply the CIFilter onto the ALAssetRepresentation's fullResolutionImage to recreate the modified image.
Be aware that the iOS Photos App handles JPG and RAW images differently. For JPG images a new ALAsset with the XMP metadata is stored in the Camera Roll. For RAW images an ALAssetRepresentation is added to the original ALAsset. I'm not sure if this additional ALAssetRepresentation is the modified image and if it has the AdjustmentXMP metadata. In addition to JPG and RAW images you should also test the behaviour for RAW+JPG images.


text:
Q: How to configure settings.xml to use custom application in maven project I am new for Maven.
I have created two class say App1 and App2 in a spring project using Maven build.
How can I configure settings.xml to use one of App1 or App2 class in my project.
So that if one person wants App1 to use, then he will change settings.xml and App1 will be used by project.
Same, If other person wants to use App2 then he will make change in settings.xml and App2 will be used by project.

A: Find example here
https://spring.io/guides/gs/maven/
or
How do I add a project as a dependency of another project?

A: What you probably are looking for are Maven profiles.
However, under normal circumstances you should not use Maven settings.xml for such things. If it is two different applications you should have two Maven projects.


text:
Q: Optuna for Catboost outputs "trials" in random order? I'm working on hyperparameter tuning using Optuna for CatboostRegressor, however I realised that the trials I'm getting are in random order (mine started with Trial 7 and then Trial 5 then Trial 8. All of the examples I see online are in order, for example Trial 0 finished with value: xxxxx, Trial 1, Trial 2... (Example: https://www.kaggle.com/saurabhshahane/catboost-hyperparameter-tuning-with-optuna)
Is this an issue or it's not something to worry about? Not sure why is mine in a random order though.
Also wondering if I should be doing cb.cv (Catboost's cross validation) instead of cb.CatBoostRegressor and then .fit and .predict for hyperparameter tuning? Or it doesn't matter which way I'm using to get the best hyperparameters?

This is my code:
def objective(trial):

    optuna_params = {"subsample": trial.suggest_float("subsample", 0.5, 0.99),
                     'od_wait': trial.suggest_int('od_wait', 10, 50, step=1),
                     "colsample_bylevel": trial.suggest_float("colsample_bylevel", 0.5, 0.99),
                     "random_strength": trial.suggest_int("random_strength", 1, 10, step=1),
                     "l2_leaf_reg": trial.suggest_float("l2_leaf_reg", 1.0, 50.0),
                     "max_depth": trial.suggest_int("max_depth", 4, 10, step=1),
                     "n_estimators": trial.suggest_int("n_estimators", 100, 2500, step=1),
                     'learning_rate': trial.suggest_loguniform("learning_rate", 0.005, 0.1)}

    cbregressor = cb.CatBoostRegressor(**optuna_params,
                                       random_state=0,
                                       loss_function='MAE',
                                       eval_metric='MAE',
                                       one_hot_max_size=0,
                                       boost_from_average=True)

    cat_optuna = cbregressor.fit(cat_train_pool2, eval_set=cat_val_pool2, verbose=False, early_stopping_rounds=10)

    y_valid_pred_cat3 = cat_optuna.predict(X_validation2)

    MAE = mean_absolute_error(y_validation, y_valid_pred_cat3)
    print('MAE score of CatBoost =', MAE)
    return MAE

study = optuna.create_study(direction="minimize", sampler = TPESampler(seed=0), study_name="Catboost Optuna")
study.optimize(objective, n_trials=100, n_jobs=-1)

A:
Is this an issue or it's not something to worry about? Not sure why is mine in a random order though.

No. When we set n_jobs=-1 in study.optimize method, optimisation is performed parallelly using thread.
Regresser vs CV
I suppose either is fine. In general, when we use CV, overfitting is less likely to happen than single train/val split (i.e., regresser in this setting). However, the computing of CV cost is expensive.


text:
Q: How to pass a (changing) variable between two view controllers? I have two view controllers. VC1 & VC2. VC1 is passing a variable which keeps changing & updating every second on VC1, in my case, it is the nearest beacon which is handled by a method in VC1.
VC1 code:
  var id: Int = 0 // initializing

  // send data to VC2
  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let vc2 = segue.destination as? navigationScreenVC else { return }
      vc2.id2 = id
    }

VC2 code:
  var id2: Int = 0

  override func viewDidLoad() {
    super.viewDidLoad()
    print(VC2)
  }

It is working where it sends the first value it encounters, but not when the value keeps changing, so I want that to be sent as soon as it triggers a change.
I tried to do didSet{} but it doesn't work that way.

A: Use a delegate pattern.
In VC2:
protocol VC2Delegate: AnyObject {
  var id2: Int { get }
}

class VC2 {
  weak var delegate: VC2Delegate?

  override func viewDidLoad() {
    super.viewDidLoad()
    print(delegate?.id2)
  }
}

In VC1:
class VC1: UIViewController, VC2Delegate {
...
  var id2: Int = 0

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    guard let vc2 = segue.destination as? navigationScreenVC else { return }
    vc2.delegate = self
  }
...
}

A: A ViewController should not be managing stuff after it stopped being visible. You should managing this in a separate class and waiting for updates from a delegate, lets say:
protocol BeaconUpdateListener : AnyObject {
    func currentBeaconIdWasUpdated(to newValue: Int)
}

class BeaconManager {
    struct DelegateWrapper {
        weak var delegate : BeaconUpdateListener?
    }

    static let delegates = [DelegateWrapper]()
    static var currentId : Int = -1 {
        didSet {
            delegates.forEach { (delegate) in
                delegate.delegate?.currentBeaconIdWasUpdated(to: currentId)
            }
        }
    }
}

Sample code, missing details. You could make your own or update this one. Now, having that data outside your UI code makes it easier to use from anywhere else, and update that code in the future. This way, you "subscribe" to id updates like this:
BeaconManager.delegates.append(OBJECT_THAT_NEEDS_TO_BE_NOTIFIED)

... update your id like this:
BeaconManager.currentId = 65421687543152

... and wait for updates like this:
class VC2 : ViewController, BeaconUpdateListener {
    func currentBeaconIdWasUpdated(to newValue: Int) {
        // Do stuff once i receive the update
    }
    // ...
}


text:
Q: How to average of data over specific time period recoding the ending time I need help with this.
I want to get the average of my data over a time interval using a specific time step for example 3 second intervals. So therefore, data is in one second resolution and I want to change the resolution to 3 seconds using the average values.
The Input:

time
S

2:30:01
5

2:30:02
9

2:30:03
450

2:30:04
7

2:30:05
10

2:30:06
300

This is what I was thinking... Alas, this is not changing the time intervals and the average isn't at the right index.
import pandas

step = 3  #3 seconds
df = df.groupby(df.index // step).mean()

Note: Please if you think there's another way to approach the problem I'm all ears.
Output:

time
S

2:30:03
154.7

2:30:06
105.7

A: TL;DR
import pandas as pd

from datetime import datetime, timedelta

x = [ ['2:30:01', '5'],
 ['2:30:02', '9'],
 ['2:30:03', '450'],
 ['2:30:04', '7'],
 ['2:30:05', '10'],
 ['2:30:06', '300']]

df = pd.DataFrame(x, columns=(['time', 's']))
df['time'] = df['time'].apply(lambda t: datetime.strptime(t, '%H:%M:%S'))
df['s'] = df['s'].astype(int)

df_new = pd.DataFrame([{'start_time':interval_start.strftime("%H:%M:%S"),
                        'end_time': (interval_start+timedelta(0,2)).strftime("%H:%M:%S"),
                        's': sum(rows['s'])/len(rows['s'])}
                        for interval_start, rows in
                        df.set_index('time').resample('3s',offset="1s")])

[out]:
    start_time  end_time    s
0   02:30:01    02:30:03    154.666667
1   02:30:04    02:30:06    105.666667

In Long
First it's easier to manipulate time if you convert the string time type to datetime objects (or if you are Dr. Who =)):
df['time'] = df['time'].apply(lambda t: datetime.strptime(t, '%H:%M:%S'))

The heavy lifting is done by:
df.set_index('time').resample('3s',offset="1s")]

The DataFrame.resample(...) acts like a group by where you group by 3 seconds using '3s' and you have an offset of 1s, thus grouping all your data points within the 3 secs interval.
And this converts the datetime object to the original string format of your timestamp:
interval_start.strftime("%H:%M:%S")

And to get the end time of the interval:
interval_start+timedelta(0,2))


text:
Q: Custom icon on infoBox shinydashboard Is there a way to use a custom icon on infoBox on shinydashboard. I am trying to use the example on hrbrmstr gist but it I can not find the place to update the infoBox function.
library(shiny)

ui <- dashboardPage(
  dashboardHeader(title = "Dynamic boxes"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(width = 2, actionButton("count", "Count")),
      infoBoxOutput("ibox"),
      valueBoxOutput("vbox")
    )
  )
)

server <- function(input, output) {
  output$ibox <- renderInfoBox({
    infoBox(
      "Title",
      input$count,
      #icon = icon("credit-card")
icon=icon(list(src=x, width="80px"), lib="local")
    )
  })
  output$vbox <- renderValueBox({
    valueBox(
      "Title",
      input$count,
      icon = icon("credit-card")
    )
  })
}

shinyApp(ui, server)

A: I used the apputils package from leonawicz. I replaced the infoBox function with the apputils::infoBox.
library(shiny)
library(apputils)
#exApp("icons")
ui <- dashboardPage(
  dashboardHeader(title = "Dynamic boxes"),
  dashboardSidebar(),
  dashboardBody(
    fluidRow(
      box(width = 2, actionButton("count", "Count")),
      infoBoxOutput("ibox"),
      valueBoxOutput("vbox")
    )
  )
)

server <- function(input, output) {

  output$ibox <- renderInfoBox({
    ic <- apputils::icon(list(src = "https://cdn1.iconfinder.com/data/icons/money-47/512/Money_Currency_Finance-41-512.png", width = "80px"), lib = "local")
    apputils::infoBox(
      "Title",
      input$count,
      icon = ic
      #icon = icon("credit-card")
      #icon=icon(list(src=x, width="80px"), lib="local")
    )
  })
  output$vbox <- renderValueBox({
    valueBox(
      "Title",
      input$count,
      icon = icon("credit-card")
    )
  })
}

shinyApp(ui, server)


text:
Q: how to select data that have the same value with sql? I have a table with three columns, id, name, and value, as shown below.  I want to count the average where the id and value columns are the same, how can I do this?
+----+--------+-------+
| id |  name  | value |
+----+--------+-------+
| 2  | rahmat |   3   |
| 2  | olive  |   5   |
| 3  | sari   |   3   |
| 3  | ryan   |   2   |
| 1  | zaki   |   1   |
+----+--------+-------+

A: Try using this query:
SELECT AVG(value)
FROM table
WHERE id = value

The output from the sample table you gave in your OP would be 1.5, since sari and zaki are the only 2 users whose records have id and value columns which are equal.

A: according to your question yes you need to use
SELECT AVG(value)
FROM #table
WHERE id = value

I have created a sqlfiddle here
http://sqlfiddle.com/#!3/9eecb7/4105
from the nature of this question I feel you trying to calculate average of values of those rows having same ids. If that's the case I have created another fiddle http://sqlfiddle.com/#!3/9eecb7/4110 where you need to use group by
select id, sum(value)/count(id) as average from #table group by id

Lemme know if it is something you are after or you need something else.


text:
Q: Intuition behind duality principle? I'm looking for an intuitive explanation of the duality principle. I found this proof but it was way above my head, considering I just started Boolean Algebra a couple of days ago.
I suspect most proofs will be above my head, so can someone help me see the intuition behind this principle?
Thanks.

A: How I think about this is that given a Boolean algebra $(B,\wedge,\vee,\top,\bot)$, there's another Boolean algebra structure on the same set given by $(B,\vee,\wedge,\bot,\top)$. And these two Boolean algebras are isomorphic! What's the isomorphism? $b\mapsto \neg b$, naturally. So dualizing a theorem is just rewriting it in an isomorphic Boolean algebra that happens to have suspiciously similar-looking symbols.
Edit: Let's see if we can say this in more elementary terms. Boolean algebra has axioms: $\bot\implies \phi=\top, a\wedge(b\vee c)=(a\wedge b)\vee (a\wedge c)$ and so on. The duality principle just points out that for every one of these axioms, there's another one with $\bot$ exchanged for $\top$ and $\wedge$ exchanged for $\vee$. So in my first example: $\bot\implies \phi=\neg \bot \vee \phi$ switches to $\neg \top\wedge \phi=\neg(\top \vee \neg \phi)$ so we get $\neg(\top\vee \neg\phi)=\bot$, i.e. $\top\vee\neg\phi=\top,$ i.e. $\phi\implies \top$. For the second example, we get $a\vee(b\wedge c)=(a\vee b)\wedge(a\vee c)$, the other distributive law. And the duality principle holds in general just because all the axioms of Boolean algebra pair up in this way with a "dual" axiom, so that all theorems pair up with a dual theorem-just by dualizing every step in a proof.

A: This is supposed to be intuitive, so I'll try to stay away from the formalism.
Let's pretend that I am not a cat and not a dog. This is exactly the same as saying that I am neither a cat nor a dog. Essentially, we swap some symbols in a specific way and the result is equivalent to original. Symbolically, we could say
$$\neg(\text{Robin is a cat})\vee\neg(\text{Robin is a dog})\iff \neg((\text{Robin is a cat})\wedge(\text{Robin is a dog})).$$
So, everything that was unnegated is negated, and everything that was negated became unnegated. Think of it like applying the word "not" to everything. If I said I am not not a dog, I'm saying I am a dog, because I've unnegated the negation. Simultaneously, the "or" ($\wedge$) and the "and" ($\vee$) have been switched.
And that's my intuitive version of boolean duality.


text:
Q: How to set formData for boolean in Axios post request I'm trying send a post request using axios to my backend but I can't send the boolean "isActive" for some reason. Is there a way to do this?
async submit() {
    const isValid = await this.$validator.validateAll()
    if (isValid && !this.submitting) {
        let formData = new FormData();
        formData.set("city", this.formData.city)
        formData.set("state", this.formData.state)
        formData.set("county", this.formData.county)
        formData.set("isActive", true) // <- NOT ACCEPTING THIS VALUE

        axios.post("/api/v1/team/createTeam", formData, {
            headers: {
                'Content-Type': 'application/json'
            }
        })
            .then(res => {
                if (res.status === 200) {
                    this.submitting = true
                    this.cancelModal()
                } else {
                    console.log(res.data.code);
                }
            })
            .catch(function (err) {
                console.log(err);
            })
        }
}

A: FormData can only contain string values. Setting a Boolean true would result in "true" for the value. The backend would have to convert that string to a Boolean.
Also, your header should not be application/json (intended for JSON payloads). If sending FormData as the payload, the header should be multipart/form-data:
axios.post("/api/v1/team/createTeam", formData, {
  headers: {
    'Content-Type': 'multipart/form-data'
  }
})

If your backend is actually expecting JSON, then you can't send FormData. Switch to a JavaScript object instead (which does accept Booleans):
const payload = {
  city: this.formData.city,
  state: this.formData.state,
  county: this.formData.county,
  isActive: true,
}

axios.post("/api/v1/team/createTeam", payload, {
  headers: {
    'Content-Type': 'application/json'
  }
})


text:
Q: Policy enforcement to add a new item - ASPECTJ I have to enforce a policy issuing a warning if items not belonging to a particular category are being added, apart from the three which are allowed and disallowing such additions.....
So far i am able to find the items and issue warning.... but not sure how to stop them from being added.... For Eg.
Allowed categories Shoes and socks
but if i try and add a vegetable item to the inventory it should give me a warning saying "category not allowed../nItem will not be added to inventory"..... and then proceed to the next item....
This is what i've written so far.....
import org.aspectj.lang.*;

public aspect a8 {

  boolean check;

    pointcut deliverMessage(): call(* ShoppingCart.addItem(..));

    pointcut interestingcalls(String categorie): call(Item.new(..)) && args(*, *, categorie);

      before(String categorie): interestingcalls(categorie)
       {
       if(categorie.equals("Shoes"))
        {
       System.out.println("categorie detect:" +categorie);
        }
        else if(categorie.equals("socks"))
        {
       System.out.println("categorie detect:" +categorie);
        }
        else
        {
        check=true;
        around(categorie);
        System.out.println("please check categorie" +categorie);
        }
    }

    around(String categorie): interestingcalls(categorie) {
            System.out.println("Start! "+categorie);
            proceed(categorie);
            System.out.println("End!");
    }
}

I know i'm not using the around advice correctly....

A: What you probabily want is comething like this:
public aspect CartAspect {

    pointcut checkAdd(String categorie) : call (void ShoppingCart.addItem(*)) && args(categorie);

    void around(String categorie) : checkAdd(categorie) {
        System.out.println("Start! " + categorie);
        if (categorie.equals("shoes")) {
            System.out.println("categorie detect:" + categorie);
            proceed(categorie);
        } else if (categorie.equals("socks")) {
            System.out.println("categorie detect:" + categorie);
            proceed(categorie);
        } else {
            System.out.println("please check categorie " + categorie);
        }
        System.out.println("End!");
    }

}

Notice that in the case that the category is different from "shoes" or "socks", we DON'T call the proceed() method.


text:
Q: how to request data from our spring boot micro-service to external server for a given id's? Currently I have created 2 microservices and and getting the data from one service to another using RestTemplate.
Microservice -1:
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class StringDataController {

List<String> stringList = new ArrayList<>();

@RequestMapping(value = "/securities/list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public List<String> sendStringData(){

    stringList.add("12345");
    stringList.add("23435");
    stringList.add("23436");
    return stringList;
}

}

Microservice-2:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
@EnableAutoConfiguration
public class ExternalRequestController {

@Value ("${sampleMS1.uri}")
String sampleMS1URI;

@RequestMapping(value="/listdata", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public void receiveStringFromAnotherMS(){
    List<String> list = null;

    list = new RestTemplate().getForObject(sampleMS1URI,List.class);

    System.out.println(list.toString());
    System.out.println("-->"+list);
}
}

Now, I have to send the List(String)(list of ID's) data to some external server and response should get Map(K,V) ==> key as a String and Value as a Double.
Note: The external server is not handling by us, so we can only request the data with List of id's and then they should sending the response with price data of specific id's.
Can anyone suggest me a way to do it ?
I am new to Spring & Spring boot.
Thank you!


text:
Q: ClassNotDef Exception for Jira Rest Java Client I have a Jira Rest Java Client which works perfectly as a standalone Java application but when I use it with a Tomcat server to make a dynamic web application using Maven, it throws the following Stack Trace :
java.lang.ClassNotFoundException: org.springframework.beans.factory.DisposableBean
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1702)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at java.lang.ClassLoader.defineClass1(Native Method)
at java.lang.ClassLoader.defineClass(ClassLoader.java:760)
at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142)
at org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2918)
at org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1174)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1669)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1547)
at com.atlassian.jira.rest.client.internal.async.AsynchronousHttpClientFactory.createClient(AsynchronousHttpClientFactory.java:53)
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.create(AsynchronousJiraRestClientFactory.java:35)
at com.atlassian.jira.rest.client.internal.async.AsynchronousJiraRestClientFactory.createWithBasicHttpAuthentication(AsynchronousJiraRestClientFactory.java:42)
at ReferenceClass.ListOfProjects(ReferenceClass.java:20)
at GetProjectList.doGet(GetProjectList.java:47)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:728)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:100)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1041)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:603)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:312)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)

I am using he following pom.xml
<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">
<modelVersion>4.0.0</modelVersion>
<groupId>com.javarticles.webapp</groupId>
<artifactId>webappExample</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>webappExample Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>3.8.1</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>3.1.0</version>
    </dependency>
    <dependency>
        <groupId>org.openengsb.wrapped</groupId>
        <artifactId>jira-rest-java-client-api</artifactId>
        <version>2.0.0-m32.w1</version>
        <exclusions>
            <exclusion>
                <groupId>org.apache.httpcomponents</groupId>
                <artifactId>httpclient</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>org.openengsb.wrapped</groupId>
        <artifactId>jira-rest-java-client-core</artifactId>
        <version>2.0.0-m32.w1</version>
    </dependency>

</dependencies>
<build>
    <finalName>webappExample</finalName>
</build>

My program is following:
import java.io.IOException;
import java.net.URISyntaxException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class HelloWorldServlet
 */
@WebServlet("/GetProjectList")
public class GetProjectList extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public GetProjectList() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        response.setContentType("text/html");
        response.setCharacterEncoding("UTF-8");
       /*
        try {
            r.ListOfProjects();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }*/
        response.getWriter().write("Success111");
        response.getWriter().flush();
        response.getWriter().close();
        ReferenceClass r = new ReferenceClass();
        try {
            r.ListOfProjects();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Code for Reference Class
public class ReferenceClass {
    public ArrayList<String> ListOfProjects() throws URISyntaxException,    IOException {
        String username = "xxxxx";
        String password = "xxxxx";
        ArrayList<String> list = null ;
         URI jiraserverURI = new URI("https://jira.xxxxx.com");
         JiraRestClientFactory restClientfactory = new AsynchronousJiraRestClientFactory();
         JiraRestClient Client = restClientfactory.createWithBasicHttpAuthentication(jiraserverURI, username,
                password);

        try {
            Iterable<BasicProject> allproject =  Client.getProjectClient().getAllProjects().claim();
            list = new ArrayList<String>();
            for (BasicProject project : allproject) {
                list.add(project.getName());
            }

            System.out.println( "--------" + list);

        } catch (Exception e) {
            System.out.println("Exception found " + e);
        }
        return list;
    }
}

If anyone has encountered this please let me know the solution.

A: You have not added any dependency for org.springframework.beans.factory.DisposableBean class.
I am guessing adding
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-core</artifactId>
    <version>1.0</version>
</dependency>

Should solve your problem. If not,
Check here to find the dependencies which have your class and add the correct dependency.


text:
Q: PHP MySQL Fill Textarea with Text that contains newlines using jQuery I have a form that users fill out which contains a textarea. This form is uploaded to a MySQL database, and then later the user can edit the info. The issue I am having is that when I use AJAX to suggest data for the textarea, javascript gives a "Invalid or unexpected token" error wherever a newline appears.
In the suggestion box it is a list with rows like so...

$benefiting

And selectBenefiting() is written like this...
function selectBenefiting(val) {
    $("#benefiting").val(val);
    $("#benefiting-sugg").hide();
}

Can anyone help me achieve this while preserving the line breaks? I have been searching for hours, and while I see other people with the same issue, I have yet to find a solution.
As I've said, it is a MySQL database. If I echo the data in the textarea using PHP it displays correctly, so I know it is in the database correctly. The issue is when using jQuery and AJAX to attempt to populate the textarea.
Any help would be greatly appreciated.
UPDATE:
$benefiting_js = str_replace("\r\n", "\\r\\n", $benefiting);

Slightly modified solution from Nick did the trick.

A: The problem is that Javascript doesn't like newlines in strings. So where you have them, you need to escape the newline characters. Try something like
$benefiting_js = str_replace("\n", "\\n", $benefiting);

And then change your
 to

$benefiting


text:
Q: Cron-based terminal job doesn't start until screen unlocked (sometimes) I have a cron job whose command line looks like:
30 5 * * * osascript -e 'tell application "Terminal" to do script "bash-script-file"'

FWIW the base script file sets some environment variables and then runs a Ruby program.
Prior to last week, most days this ran just fine, but occasionally (~ twice/month) it would hang until I either unlocked the screen or attached remotely to the system. At that time I would see a terminal screen with a message about new mail and a command line prompt with the bash-script-file on it. At that point, I could wait and the script would proceed to run normally. I have checked System Settings and the computer is set to sleep never. I'm not locking the screen (instead allowing it to go to sleep), and of course I have the screen saver locked, requiring a password to wake up.
Last week (about five days ago), I added a second cron job of the same form (running another bash script that started another Ruby program), and since then, both jobs have hung every day until I attached remotely. What is causing this? What can I do to resolve it?
tl;dr cron-scheduled terminal jobs are hanging until the screen unlocks.


text:
Q: Download file from dropbox using C# WebClient - encoding issue I'm trying to download the file from Dropbox then create an attachment and send it in an email in WFFM form in Sitecore 8.2 update 5.  On my website, I use two types of file upload controls: regular asp.net MVC file upload and the upload from Dropbox. I created a custom WFFM control for this purpose and custom save action.
Both controls are using the same code for email submission and the regular file upload files are going through perfectly, unfortunately, when I try to upload a file from Dropbox and open the attachment in the email I get an error message:
"Adobe Acrobat Reader could not open "filename.pdf" because it is either not a supported file type or because the file has been damaged (for example, it was sent as an email attachment and wasn't correctly decoded)."
In the code I can see that the bytes[] file size which I get from regular upload is different from Dropbox. I guess something is not right with encoding/decoding but I'm running out of ideas.
Code for dropbox upload:
using (var client = new WebClient())
                    {
                        client.Encoding = Encoding.UTF8;
                        client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(this.DownloadProgressChanged);
                        file = client.DownloadData(this.FileLocation);
                        fileName = Path.GetFileName(this.FileLocation).Replace(Constants.FileUpload.DropboxQueryString, string.Empty);
                        var fileExtension = Path.GetExtension(this.FileLocation).Replace(Constants.FileUpload.DropboxQueryString, string.Empty);
                        mimeType = MimeTypeMap.GetMimeType(fileExtension);
                    }

Then I use Convert.ToBase64String(file) to pass this value as a string (never mind why I need that but needs to be done in this way) in the form to custom save action Send Email Message and I decode it back while attaching the file:
private static IList<Attachment> RetrieveAttachments(string fileName, string mimeType, string file)
        {
            IList<Attachment> attachments = new List<Attachment>();
            if (!string.IsNullOrWhiteSpace(fileFieldValue))
            {
                byte[] fileContent = Convert.FromBase64String(file);

                var actualAttachment = new MemoryStream(fileContent)
                {
                    Position = 0
                };

                var attachment = new Attachment(actualAttachment, fileName, mimeType);
                attachment.ContentDisposition.Size = actualAttachment.Length;
                attachment.ContentDisposition.FileName = fileName;
                attachments.Add(attachment);
            }
            return attachments;
        }

Do you know how I should encode/decode the files uploaded from Dropbox or is there anything obviously wrong with the code above?