text:
Q: Choose or generate canonical variant from multiple sentences I'm working with an API that maps my GTIN/EAN queries to product data.
Since the data returned originates from merchant product feeds, the following is almost universally the case:

*

*Multiple results per GTIN

*Products' titles are pretty much unstructured

*Products' titles are "polluted" with

*

*SEO-related stuff,

*information about the quantity contained,

*"buy two, get one free" offers,

*etc.

I'm looking for a programmatic way to either

*

*choose the "cleanest"/most canonical version available

*or generate a new one that represents the "lowest common denominator".
Consider the following example results for a single EAN query:

*

*Nivea Deo Roll-On Dry Impact for Men

*NIVEA DEO Roll on Dry/blau

*Nivea Deo Roll-On Dry Impact for Men, 50 ml, 3er Pack (3 x 50 ml)

*Nivea Deo Roll on Dry/blau 50 ml

*Nivea Deoroller 50ml dry for Men blau   Mindestabnahme: 6 Stück (1 VE)

*NIVEA Deoroller, Dry Impact for Men

*NIVEA DEO Roll on Dry/blau_50 ml

My homebrew approach looks like this:

*

*Basic cleanup:

*

*Lowercase the titles,

*strip excessive whitespace,

*throw out apparent stopwords such as "buy" and "click"

*Build an array for word => global occurence

*

*"Nivea" => 7

*"Deo" => 5

*"Deoroller" => 2

*…

*"VE" => 1

*Calculate the "cumulative word value" for each of the titles

*

*"Nivea Deo" => 12

*"Nivea Deoroller VE" => 10

*Divide the cumulative value by the length of the title, resulting in a score

*

*"Nivea Deo" => 6

*"Nivea Deoroller VE" => 3.34
Obviously, my approach is pretty basic, error-prone and biased towards short sentences with frequently used words – yielding more or less satisfactory results.

*

*Would you choose a different approach?

*Is there some NLP magic way to take care of the problem that I don't know of?

A: Since your existing metric seems to bias towards shorter phrases, you should consider factoring in bigrams into the mix. So instead of considering scores for just individual words, additionally consider the score for consecutive pairs of words as well (e.g. 'nivea deo', deo roll-on', 'roll-on dry', etc). When computing the score for each title, factor in the scores for every unigram and bigram you can generate out of the title together, but maybe give the bigrams more weight, and this should encourage your algorithm to prefer longer phrases.
If you have large existing corpus of lots of names like these at your disposal, consider using something like TF-IDF
What you are doing right can be likened to just using TF. Using your global corpus, you can compute the idf of each unigram and bigram, which is basically a measure of unique or rare a word or phrase is across the entire corpus.
tf = the number of times you have seen an ngram within these results
idf = a global measure of how unique an ngram might be across all results (or atleast a very large number of them)
So when computing the score for a title, instead of simply adding up the tf's of each ngram in it, you add up the tf*idf of each ngram instead. Rarer ngrams (which possibly do a better job at distinguishing this item from all other items) have a higher idf, so your algorithm should give higher weight to them. A lot of junk terms (like Mindestabnahme) would have really high idf, but they would have a really small tf, so they might not make a big difference. Alternatively prune off tokens you see fewer than k times, to get rid of noise.
Another NLP trick to know about is Levenshtein distance .. which is a way to quantify how similar two strings are. You can compute the levenshtein distance between every pair of strings within your results, and then try preferring the result which has the lowest average distance from all the other strings. This might not work well by itself... but factoring this score in with your existing approach might help you navigate some tricky cases.

A: I'd:

*

*Convert all strings to lower (or upper) case

*Do a multiple sequence alignment over all strings

*Convert back to original case

*Find the most frequent letter in every column

*Remove the gaps

For your example:

*

*Convert all strings to lower (or upper) case

nivea deo roll-on dry impact for men
nivea deo roll on dry/blau
nivea deo roll-on dry impact for men, 50 ml, 3er pack (3 x 50 ml)
nivea deo roll on dry/blau 50 ml
nivea deoroller 50ml dry for men blau mindestabnahme: 6 stück (1 ve)
nivea deoroller, dry impact for men
nivea deo roll on dry/blau_50 ml

*Do a multiple sequence alignment over all strings

nivea deo roll°°-on °°dry °°°°°°°°°°impact for men°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
nivea deo roll°° on °°dry/blau°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
nivea deo roll°°-on °°dry °°°°°°°°°°impact for men, 50 ml, 3er pack (3 x 50 ml)°°°°°°°
nivea deo roll°° on °°dry/blau °°°°°°°°°°°°°°°°°°°°°50 ml°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
nivea deo°roller 50ml dry °°°°°°°°°°°°°°°°°for men blau mindestabnahme: 6 stück (1 ve)
nivea deo°roller, °°°°dry °°°°°°°°°°impact for men°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
nivea deo roll°° on °°dry/blau_50 ml°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°

(where ° denotes a gap character)

*Convert back to original case

Nivea Deo Roll°°-On °°Dry °°°°°°°°°°Impact for Men°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
NIVEA DEO Roll°° on °°Dry/blau°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
Nivea Deo Roll°°-On °°Dry °°°°°°°°°°Impact for Men, 50 ml, 3er Pack (3 x 50 ml)°°°°°°°
Nivea Deo Roll°° on °°Dry/blau °°°°°°°°°°°°°°°°°°°°°50 ml°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
Nivea Deo°roller 50ml dry °°°°°°°°°°°°°°°°°for Men blau Mindestabnahme: 6 Stück (1 VE)
NIVEA Deo°roller, °°°°Dry °°°°°°°°°°Impact for Men°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
NIVEA DEO Roll°° on °°Dry/blau_50 ml°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°

*Find the most frequent letter in every column

Nivea Deo Roll°° on °°Dry °°°°°°°°°°°°°°°°°for Men°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°

*Remove the gaps

Nivea Deo Roll on Dry for Men

Everything except step 2 (multiple sequence alignment) is straightforward. Multiple sequence alignment is commonly used in bioinformatics, see eg. here or here or here... You can certainly find C or Java code but I'm not sure about PHP.
Update:
To get you started with multiple alignment, so called "star alignment" is basically a combination of pairwise alignments of one sequence (the "star center") with every other. A pairwise alignment is typically computed using dynamic programming, see e.g. here or here. To produce multiple alignment, you choose one of your strings to be the star center. You find the pairwise alignments between it and every other string and then align the pairwise alignments by introducing gaps into them so that the star centers in all alignments are perfectly aligned. You can repeat the procedure by using the result of the previous step as the star center for the next one until it converges, i.e. the result does not change.
Update 2:
You can also use whole words as symbols (quants, atoms) to align. Say, A = nivea, B = deo etc. This has  following advantages:

*

*Words cannot be altered by the alignment and are treated equally, irrespectively of their lengths

*When doing pairwise alignment, you can assign costs for substituting individual words ("symbols") according to TF-IDF and their synonyms. Pairwise alignment tries to minimize (weighted) Levenshtein distance between the sequences.

In your example (try it yourself) this would lead to
Nivea Deo Roll on Dry for Men 50 ml

i.e. we get here also the 50 ml. This is because skipping two-letter words is not cheaper than skipping 20-letter words.

A: If I understood right you are not matching those names against existing database, but trying to get as close as possible to the actual name of the product, so here's my idea:

*

*Don't do the usual cleanup - just remove extra whitespace - leave stop words, character case, separators (such as hyphen) intact.

*Split strings into terms on whitespace.

*Split terms on separators, number/char, character case, but don't remove originals, just add additional ones right after the splited term, lowercase all terms, remove duplicate and empty terms

*Remove terms that are not common for fixed % of the strings (if it should be 40 or 95% you'll know after testing) - This will remove most if not all stuff added by merchants.

*Find most common position for each term.

*If you get more than one term with same most common position check which one is more commonly before the other. Increase "looser" position by 1, repeat till there is no conflict

*For each term that is left pick the most common capitalization

*Merge remaining terms

Using your example it would work like this:
Step 1:

Nivea Deo Roll-On Dry Impact for Men
NIVEA DEO Roll on Dry/blau
Nivea Deo Roll-On Dry Impact for Men, 50 ml, 3er Pack (3 x 50 ml)
Nivea Deo Roll on Dry/blau 50 ml
Nivea Deoroller 50ml dry for Men blau Mindestabnahme: 6 Stück (1 VE)
NIVEA Deoroller, Dry Impact for Men
NIVEA DEO Roll on Dry/blau_50 ml

Step 2:

Nivea, Deo, Roll-On, Dry, Impact, for, Men
NIVEA, DEO, Roll, on, Dry/blau
Nivea, Deo, Roll-On, Dry, Impact, for, Men, 50, ml, 3er, Pack, (3, x, 50, ml)
Nivea, Deo, Roll, on, Dry/blau, 50, ml
Nivea, Deoroller, 50ml, dry, for, Men, blau, Mindestabnahme:, 6, Stück, (1, VE)
NIVEA, Deoroller, Dry, Impact, for, Men
NIVEA, DEO, Roll, on, Dry/blau_50, ml

Step 3:

nivea, deo, roll-on, roll, on, dry, impact, for, men
nivea, deo, roll, on, dry/blau, dry, blau
nivea, deo, roll-on, roll, on, dry, impact, for, men, 50, ml, 3er, pack, 3, x, 50, ml
nivea, deo, roll, on, dry, blau, 50, ml
nivea, deoroller, 50ml, 50, ml, dry, for, men, blau, mindestabnahme, 6, stück, 1, ve
nivea, deoroller, dry, impact, for, men
nivea, deo, roll, on, dry/blau, dry, blau, 50, ml

Step 4: (assuming threshold of 60%)

nivea, deo, roll, on, dry, for, men
nivea, deo, roll, on, dry, blau
nivea, deo, roll, on, dry, for, men, 50, ml
nivea, deo, roll, on, dry, 50, ml
nivea, 50, ml, dry, for, men, blau
nivea, dry, for, men
nivea, deo, roll, on, dry, blau, 50, ml

Step 5:

nivea => 1
deo => 2
roll => 3
on => 4
dry => 5
for => 6
men => 7
blau => 6
50 => 8, 6, 2, 7
ml => 8, 7, 3, 8

Step 6:

nivea => 1
deo => 2
roll => 3
on => 4
dry => 5
blau => 6
for => 7
men => 8
50 => 9
ml => 10

Step 7

Nivea, Deo, Roll, on, Dry, blau for, Men, 50, ml

Step 8
end result: Nivea Deo Roll on Dry blau for Men 50 ml
This method has following problems:

*

*It doesn't handle names with duplicate terms well (or at all - all term occurences after 1st one are lost)

*It's biased to split hyphen-separated or case-separated (ProductName) name parts into space separated ones - this can be fixed if you check most common version at step 8.

A: You have a very good NLP problem. I have worked a similar one about an year ago. I would also recommend the approach by adi92. But in case you need to use any NLP software I suggest the Stanford NLP. The software and the respective publications are also present here. http://nlp.stanford.edu/ Hope this helps.


text:
Q: Is Java Memory Model still in use? It explains concurrency in terms of Java concurrency primitives but in practice best-performance concurrent code uses sun.misc.Unsafe primitives which involves CAS and direct memory fence instructions.
Moreover, personally I prefer to use fences over happens-before when reasoning over concurrent code.
So, is JMM still valid for modern Java?
Or, to say it in other words, can JMM be used to reason over programs, synchronized via sun.misc.Unsafe methods?

A: So, is JMM still useful for modern Java?
Not really.
So, is JMM still valid for modern Java?
Yes, is still valid
Most of the java memory are handled behind the scene, garbage collection calls and manual memory manipulation is very rarely used and considered bad design. Most people will tell you it is still useful due to certain things can be done such as native memory allocation or create native concurrency.
While JMM is supported and is valid, no one really uses it. Why? Those type of things are not safe to be done using sun.misc.Unsafe. One reason why it is unsafe code is because the instances are never garbage collected. (unless this is what you want). Is like using volatile variable for thread; it never cached locally and it cost you performance and is difficult to write. In a non atomic operation may give you different result!
It is not wrong to use fence code but think about the trade offs. Ask yourself why do you use java and not C?
In short, it could be useful to get certain things done but it is not practical, due to there would be alternative way to do this. (native code)

For Vince's comment I will add this:
volatile int i = 0;

public void foo() {
    if (i == 0) i = i + 1;
}

The above code is inherently unsafe, even though the variable's declaration as being volatile means that reads and writes are flushed to main memory - the only safe implementation of such a method would be something like:
int i = 0;

public synchronized void foo() {
    if (i == 0)
    i = i + 1;
}

So which should you prefer? Well, if you have multiple threads modifying a field dependent on that field's value (i.e. compare-and set), then synchronized is the only safe solution.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Facebook Api Integration with Java Application I have downloaded restfb Jar for connecting to facebook.I want to use this api in my java application to connect Facebook.I am developing a desktop application for this purpose.I have created account on Face book and registered as a developer.
I want The likes comments and friendslist
Is it possible to connect Facebook from my java application?
If yes please, can some one send me the example code for that and treat me as a New Bee in this facebook integration?
Thanks in advance.


text:
Q: Reuse Table View variables Swift Here is the table view:
   public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
           let too: AnyObject = rowData ["time"] as NSString
        var name: String = rowData["time"] as String
        var formattedPrice: String = rowData["date"] as String

        var alert: UIAlertView = UIAlertView()
        alert.title = name
        alert.message = formattedPrice
        alert.addButtonWithTitle("Ok")
        alert.show()
         println ("hi")
         println (too)
    }

I need to reference these variables in another view controller. I have not been able to fit that statement above in this:
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if (segue.identifier == "segueTest") {
var svc = segue!.destinationViewController as secondViewController;
svc.toPass = textField.text
}
}

I am trying to segue off cell click.
    from http://jamesleist.com/ios-swift-passing-data-between-viewcontrollers/

A: If it isn't a lot of data, the strategy I use to pass data between view controllers is to store the value in NSUserDefaults.
Setting A Value: When you first get the data, store it in NSUserDefaults.
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //This class variable needs to be defined every class where you set or fetch values from NSUserDefaults
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    var rowData: NSDictionary = self.tableData[indexPath.row] as NSDictionary
    let too: AnyObject = rowData ["time"] as NSString
    var name: String = rowData["time"] as String
    var formattedPrice: String = rowData["date"] as String
    defaults.setObject(rowData, forKey: "rowData")
    defaults.setObject(too, forKey: "too")
    defaults.setObject(name, forKey: "name")
    defaults.setObject(formattedPrice, forKey: "formattedPrice")
    defaults.synchronize() //Call this after you're done editing defaults, it saves your change to the disk

    var alert: UIAlertView = UIAlertView()
    alert.title = name
    alert.message = formattedPrice
    alert.addButtonWithTitle("Ok")
    alert.show()
     println ("hi")
     println (too)
}

Fetching A Value: When you need to get the values, just grab it from NSUserDefaults.
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.dictionaryForKey("rowData") as? NSDictionary
defaults.objectForKey("too") as? String
defaults.objectForKey("name") as? String
defaults.objectForKey("formattedPrice") as? String

Doing that gives you access to the stored values in any class and allows the data to persist after the app is closed and reopened. If you want to clear the data after the app closes, in AppDelegate applicationWillTerminate(application: UIApplication) function, call the removeObjectForKey function for each key previously set.
let defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.removeObjectForKey("rowData")
defaults.removeObjectForKey("too")
defaults.removeObjectForKey("name")
defaults.removeObjectForKey("formattedPrice")
defaults.synchronize()

Helpful Source on NSUserDefaults:
NSUserDefulats Class Reference: Link here.


text:
Q: The project is using an incompatible version (AGP 7.3.1) of the Android Gradle plugin. Latest supported version is AGP 7.2.1 (React-native) I recently created a new React-Native project with a (0.71) version.
When I opened the project in the Android Studio it is giving me the below error while Building.

The project is using an incompatible version (AGP 7.3.1) of the Android Gradle plugin. Latest supported version is AGP 7.2.1

I searched for this but I found a solution which is upgrading Android Studio.
Is there any other solution for these?

A: with this error come a redirect url talking about a table of compatibility https://developer.android.com/studio/releases?hl=fr#android_gradle_plugin_and_android_studio_compatibility
I updated Android Studio to the latest (Electric Eel 2022.1.1) and gradle build succesfully


text:
Q: Encoding space character in XML name I am given an XML file which contains names like below:
<Benchↂ0020Codeↂ0020>something</Benchↂ0020Codeↂ0020>

The ↂ symbol is represented with three bytes: 0xE2, 0x86, 0x82.
It looks like ↂ0020 is supposed to be treated as space character. But when I read the XML using System.Xml.XmlReader the characters ↂ0020 are not converted to space.
Is there is a way to have them converted (besides replacing, of course)? Or I just got broken XML?

A: Space characters are not permitted in XML names
There are 86 codepoints whose name contain the word space.  Ignoring the codepoints where SPACE hits due to MONOSPACE and any other that have a visual representation, leaves the following:

*

*#x0020 SPACE

*#x00A0 NO-BREAK SPACE

*[#x2002-#x200A] EN SPACE through HAIR SPACE

*#x205F MEDIUM MATHEMATICAL SPACE

*#x3000 IDEOGRAPHIC SPACE

None of the space-related code points (empty visual representation) are permitted in XML names by the W3C XML BNF for component names:

NameStartChar ::= ":" | [A-Z] | "_" | [a-z] | [#xC0-#xD6] | [#xD8-#xF6] |
                  [#xF8-#x2FF] | [#x370-#x37D] | [#x37F-#x1FFF] |
                  [#x200C-#x200D] | [#x2070-#x218F] | [#x2C00-#x2FEF] |
                  [#x3001-#xD7FF] | [#xF900-#xFDCF] | [#xFDF0-#xFFFD] |
                  [#x10000-#xEFFFF]
NameChar      ::= NameStartChar | "-" | "." | [0-9] | #xB7 | [#x0300-#x036F] |
                  [#x203F-#x2040]
Name          ::= NameStartChar (NameChar)*

Alternatives to spaces in XML names

*

*CamelCase

*underscore_char

*hyphen-char

*period.char
Colon should not be used as a word separator in XML names to avoid confusion with its use in XML Namespaces.

ↂ is permitted in XML names
The character, ↂ, (0xE2, 0x86, 0x82, which is #x2182), has nothing to do with spaces – it is ROMAN NUMERAL TEN THOUSAND.
ↂ is explicitly permitted: #x2182 is in the [#x2070-#x218F] code range.
The 0020 appearing after ↂ are just digits.  Together with the rest of the characters in Benchↂ0020Codeↂ0020, these form an allowed (albeit unconventional) XML name.  They do not constitute spaces in the XML name as spaces are not allowed in XML names.

A: The XML isn't broken, but it's representing names using a private convention for escaping disallowed characters. The XML parser won't understand this convention, it's up to the receiving application to interpret it.


text:
Q: How to expand and collapse specify section using SecionList? I call an api https://obscure-reaches-65656.herokuapp.com/api/getCloseTime?city=Miaoli&sTime=21&eTime=24 to my react-redux action and use SectionList to show the data.
With official tutorial, i use SectionList it will just show all of the section, i try to find the way when click title that can expand or collapse the section.
I find my sectionComp and renderSectionItem use the same title so i try use this.state{ title: '', expand: false }
When i click 國興戲院 use this.setState({ title: '國興戲院', expand: true }) and use like if(this.state.expand) {} in renderSectionItem
Obviously its not working because i may have a lot of section.
I have no idea what next step should i try.
Any help would be appreciated. Thanks in advance.
Here is my SectionList data:

Here is my class component:
import React, { Component } from 'react';
import { Text, SectionList, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { View } from 'react-native-animatable';
import { fetchSearchTime } from '../actions';
import { Spinner } from './common';
import GetUserTime from '../function/common/GetUserTime';

class MovieCloseTime extends Component {
  constructor(props) {
    super(props);
    const { selectedCity, firstSliderValue, secondSliderValue }
    = this.props.navigation.state.params;
    this.state = {
      selectedCity,
      firstSliderValue,
      secondSliderValue,
    };
  }

  componentDidMount() {
    const { selectedCity, firstSliderValue, secondSliderValue } = this.state;

    this.props.fetchSearchTime({
        selectedCity, firstSliderValue, secondSliderValue
    });
  }

  sectionComp = (info) => {
    const theaterCn = info.section.title;
    console.log('Title info is =>');
    console.log(info);
    return (
      <TouchableOpacity
        onPress={() => console.log('Hot to expand and collapse specify section when click here?')}
      >
        <View style={{ flex: 1, backgroundColor: '#DCDCDC' }}>
          <Text style={styles.sectionTitle}>{theaterCn}</Text>
        </View>
      </TouchableOpacity>
    );
  }

  renderSectionItem = (info) => {
    const cnName = info.item.cnName;
    console.log('Section info is =>');
    console.log(info);

    return (
      <TouchableOpacity
        onPress={() => {
        this.props.navigation.navigate('MovieDetail', {
          enCity: this.state.selectedCity,
          cnName
          });
        }
        }
      >
      <View style={{ flex: 1, flexDirection: 'column' }}>

        <Text style={styles.sectionSubTitle}>{cnName}</Text>

        <View style={{ flexDirection: 'row', flexWrap: 'wrap', backgroundColor: '#F8F8FF' }}>
        {info.item.releasedTime.map((value, index) => {
          const theTime = GetUserTime.getAsiaTime(value, 'YYYY/MM/DD HH:mm:ss');
          const hour = theTime.getHours();
          const minute = (theTime.getMinutes() < 10 ? '0' : '') + theTime.getMinutes();
          return (
            <Text style={styles.sectionTimeTitle} key={index}>{`${hour}:${minute}`}</Text>
          );
        })
        }
        </View>
      </View>
      </TouchableOpacity>
    );
  }

  render() {
    const movieData = this.props.searchTime;
    if (this.props.loading) {
      return <Spinner text='Loading...' />;
    }
    console.log('movieData is =>');
    console.log(movieData);

    return (
      <View style={{ flex: 1 }}>
        <SectionList
          renderSectionHeader={this.sectionComp}
          renderItem={this.renderSectionItem}
          sections={movieData}
          keyExtractor={(item, index) => index}
          ItemSeparatorComponent={() => <View style={styles.separator} />}
        />
      </View>
    );
  }
}

const mapStateToProps = (state) => {
  const searchTime = state.searchTime.searchList;
  const loading = state.searchTime.loading;

  return { searchTime, loading };
};

const styles = {
  // some styles
};

export default connect(mapStateToProps, { fetchSearchTime })(MovieCloseTime);

Here is my action fetchSearchTime:
export const fetchSearchTime = ({ selectedCity, firstSliderValue, secondSliderValue }) => {
  return (dispatch) => {
    dispatch({ type: SEARCH_TIME_REQUEST });
    console.log(`https://obscure-reaches-65656.herokuapp.com/api/getCloseTime?city=${selectedCity}&sTime=${firstSliderValue}&eTime=${secondSliderValue}`);
    fetch(`https://obscure-reaches-65656.herokuapp.com/api/getCloseTime?city=${selectedCity}&sTime=${firstSliderValue}&eTime=${secondSliderValue}`)
      .then(response => response.json())
      .then(responseData => {
        const movieData = responseData.reduce((r, s) => {
          r.push({ title: s.theaterCn, id: s._id, expand: true, data: s.movie });
          return r;
        }, []);
        //dispatch({ type: SEARCH_TIME, payload: responseData });
        dispatch({ type: SEARCH_TIME, payload: movieData });
      })
      .catch((error) => console.log(error));
    };
};

about type SEARCH_TIME reducer:
// with others type
import {
  SEARCH_TIME_REQUEST,
  SEARCH_TIME
} from '../actions/types';

const INITIAL_STATE = {
  searchList: [],
  loading: true,
  selectedCity: '',
  firstSliderValue: '',
  secondSliderValue: ''
};

export default (state = INITIAL_STATE, action) => {
  switch (action.type) {
    case SEARCH_TIME_REQUEST:
      return {
        searchList: [],
        loading: true,
      };
    case SEARCH_TIME:
      return {
        searchList: action.payload,
        loading: false
      };
    default:
      return state;
  }
};


text:
Q: "Generate" labels from data swift I have
["06:58"]
["07:13", "07:38", "07:53"]
["08:13", "08:38", "08:53"]
["09:13", "09:33", "09:53"]

and I want to show it in tableView as in picture:

every element - it's UILabel, I created class TimeViewCell: UITableViewCell where have property var labels = [UILabel]() but I don't know how to push data from my array in my function:
 func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cellTime", for: indexPath) as! TimeViewCell
        let showHour = self.infoWripper.sorted(by: { $0.hour < $1.hour })

        cell.labelTime.text = showHour[indexPath.row].showHour()

        for data in showHour {

            print(data.showFullTime()) //here you see my example of data in console
        }

        return cell
    }

A: I would add a UIStackView to your UITableViewCell. You can add the labels with the text to the UIStackView.
I wrapped your data into an array.
let tableViewData = [["06:58"],
    ["07:13", "07:38", "07:53"],
    ["08:13", "08:38", "08:53"],
    ["09:13", "09:33", "09:53"]]

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell = tableView.dequeueReusableCell(withIdentifier: "cellTime", for: indexPath) as! TimeViewCell

    cell.configure(data: tableViewData[indexPath.row])

    return cell
}

Then, in for your TimeViewCell, you have to add your UIStackView IBOulet (or add it programmatically) and the configure method.
class TimeViewCell: UITableViewCell {

    @IBOutlet var labelStackView: UIStackView!

    func configure(data: Array<String>) {
        for time in data {
            let timeLabel = UILabel()
            timeLabel.text = time
            labelStackView.addArrangedSubview(label)
        }
    }
}


text:
Q: Intersection Pairing and Poincaré Duality Let $M$ be an $n$-dimensional compact and oriented manifold. Then one can define the intersection pairing $H_k(M,\mathbb Z) \times H_{n-k}(M,\mathbb Z) \to \mathbb Z$. One possible formulation of the Poncaré duality is the folowing:
Every linear functional $H_{n-k}(M,\mathbb Z) \to \mathbb Z$ is given by intersection with some class $\alpha \in H_k(M,\mathbb Z)$ and if $\beta \in H_k(M,\mathbb Z)$ has interesection number $0$ with every class in $H_{n-k}(M,\mathbb Z) $ then $\beta$ is a torsion element.
This formulation is given on Griffiths & Harris "Principles of Algebraic Geometry" and they use this to define the fundamental class of a closed sumbanifold as follows: if $V \subset M$ is a closed and oriented submanifold of dimendion $k$, intersection with $V$ defines a linear funcional $H_{n-k}(M,\mathbb Z) \to \mathbb Z$ and they say
"the corresponding cohomology class $\eta_V \in H^{n-k}(M)$ is the fundamental class of $V$."
What does they mean by "the corresponding cohomology class"? I can see that $\text{Hom} (H_{n-k}(M,\mathbb Z), \mathbb Z)$ is related to $H^{n-k}(M,\mathbb Z)$ by the universal coefficient theorem, but how is $\eta_V$ obtained explicitly?

A: If $V$ is the closed submanifold of dimension $k$, I would think of $\eta_V$ as the unique closed $n-k$-form with the property that, for all $\gamma \in H_{n-k}(X)$, one has
$$
\int_{\gamma} \eta_v = \gamma\cdot V,
$$
where $\cdot$ is the intersection product and $\gamma$ is an arbitrary homology class of dimension $n - k$. The integral is well-defined here by Stokes.


text:
Q: Struggling with rewrite tactic in Idris I'm going through Terry Tao's real analysis textbook, which builds up fundamental mathematics from the natural numbers up. By formalizing as many of the proofs as possible, I hope to familiarize myself with both Idris and dependent types.
I have defined the following datatype:
data GE: Nat -> Nat -> Type where
    Ge : (n: Nat) -> (m: Nat) -> GE n (n + m)

to represent the proposition that one natural number is greater than or equal to another.
I'm currently struggling to prove reflexivity of this relation, i.e. to construct the proof with signature
geRefl : GE n n

My first attempt was to simply try geRefl {n} = Ge n Z, but this has type Ge n (add n Z). To get this to unify with the desired signature, we obviously have to perform some kind of rewrite, presumably involving the lemma
plusZeroRightNeutral : (left : Nat) -> left + fromInteger 0 = left

My best attempt is the following:
geRefl : GE n n
geRefl {n} = x
    where x : GE n (n + Z)
          x = rewrite plusZeroRightNeutral n in Ge n Z

but this does not typecheck.
Can you please give a correct proof of this theorem, and explain the reasoning behind it?

A: The first problem is superficial: you are trying to apply the rewriting at the wrong place. If you have x : GE n (n + Z), then you'll have to rewrite its type if you want to use it as the definition of geRefl : GE n n, so you'd have to write
geRefl : GE n n
geRefl {n} = rewrite plusZeroRightNeutral n in x

But that still won't work. The real problem is you only want to rewrite a part of the type GE n n: if you just rewrite it using n + 0 = n, you'd get GE (n + 0) (n + 0), which you still can't prove using Ge n 0 : GE n (n + 0).
What you need to do is use the fact that if a = b, then x : GE n a can be turned into x' : GE n b. This is exactly what the replace function in the standard library provides:
replace : (x = y) -> P x -> P y

Using this, by setting P = GE n, and using Ge n 0 : GE n (n + 0), we can write geRefl as
geRefl {n} = replace {P = GE n} (plusZeroRightNeutral n) (Ge n 0)

(note that Idris is perfectly able to infer the implicit parameter P, so it works without that, but I think in this case it makes it clearer what is happening)


text:
Q: StackOverflow exception in a recursive method I've written a recursive method in C# that should indent strings. For example, this string:
for (int i = 0; i < sb.Length; i++)
{
   if (sb[i] == '{')
   {
      startIndex = i;
      break;
   }
}

should be converted to:
for (int i = 0; i < sb.Length; i++)
{
        if (sb[i] == '{')
        {
          startIndex = i;
          break;
        }
}

My method is (updated):
private static string IndentText(string t,bool first = true)
{
    if (first == false)
    {
        t = t.PadLeft(2);
    }

    int startIndex = t.IndexOf('{') + 1;
    int stopIndex = t.LastIndexOf('}') - 1;

    int blockLength = stopIndex - startIndex + 1;
    if (blockLength <= 1 )
    {
        return "";
    }

    string start = t.Substring(0, startIndex);
    string end = t.Substring(stopIndex + 1);
    string indentBlock = t.Substring(startIndex, blockLength);

    if (!CheckNestedBlocks(indentBlock))
    {
        return indentBlock;
    }

    return start + IndentText(indentBlock,false) + end;
}

private static bool CheckNestedBlocks(string t)
{
    for (int i = 0; i < t.Length; i++)
    {
        if (t[i] == '{')  // { and } always come in pairs, so I can check of only one of then
        {
            return true;
        }
    }
    return false;
}

But I'm getting a StackOverflow exception in mscorlib.dll
What is my mistake? Thanks in advance.
By the way, because I think I'm complicating this problem, is there a better (and working) way to indent strings like this?

A: You should not include the braces in the "block" that is passed in the recursive call:
        if (t[i] == '{')
        {
            startIndex = i + 1;   // Start one character beyond {
            break;
        }

        // ...

        if (t[i] == '}')
        {
            stopIndex = i - 1;    // Stop one character prior to }
            break;
        }


text:
Q: Algebraic surface of a line arrangement Let $\mathcal{L}=L_1\cup \ldots \cup L_k$ be an arrangement of lines in $\mathbb{P}^2$ with $k>2$ and $t_k=0$ ($t_r$ is defined to be the number of $r$-fold points of the arrangement for $r\in \mathbb{N}$). For any natural number $n>1$ we may associate with $\mathcal{L}$ the following function field $$F_{\mathcal{L},n}:=\mathbb{C}(z_1/z_0,z_2/z_0)\left((l_2/l_1)^{1/n},\ldots, (l_k/l_1)^{1/n}\right),
$$
where $z_0, z_1, z_2$ are the homogeneous coordinates on $\mathbb{P}^2$ and each $l_i$ is a linear form associated with $L_i$.
In Hirzebruch's paper "Arrangements of lines and algebraic surfaces" he states that "The function field ($F_{\mathcal{L},n}$) determines an algebraic surface $X$ with normal singularities which ramifies over the plane with the arrangement ($\mathcal{L}$) as the locus of ramification."
I have two questions regarding this construction:

*

*I understand that the given function field would be associated with a
birational equivalence class of an algebraic surface, but how do we know immediately that this
function field determines an algebraic surface with normal singularities,
as it seems we may just as well associate with it any smooth surface in
the same birational equivalence class. So I guess what I'm really asking
is given an explicit description of a function field (or more specifically
an abelian extension of the function field of P^2) how do we go about
associating with it an explicit (possibly singular) algebraic surface?

*May we derive from this description of the function field an explicit
embedding of the surface in some ambient variety (say $\mathbb{P}^N$)?

A: Regarding 1: If $X$ is a variety with function field $K$, $L$ a finite separable extension of $K$, we can construct a normal variety $Y$, "normalization of $X$ in $L$", with function field $L$ and a finite map $Y\to X$. This is done as follows: for any affine open $X_i = Spec(R)$ in $X$, take $Y_i = Spec(S)$ where $S$ is the integral closure of $R$ in $L$, and then glue these $Y_i$ to obtain $Y$. In your situation, $X = \mathbb{P}^2$, $K = \mathbb{C}(z_1/z_0, z_2/z_0)$, $L$ is the field you described and $Y$ is the surface you need.
Regarding 2: I cannot say anything explicit, but if $f:Y\to X$ is a finite map and $L$ is an ample line bundle on $X$, then $f^* L$ is an ample line bundle on $Y$. This gives you a projective embedding of $Y$ (up to Veronese). Sorry I can't be more helpful here...


text:
Q: How can I recover a lost iDisk file? I recently had a file that was on my office computer (iMac) which was not syncing with my MacBook Air for some reason. I read that I should try to turn off iDisk and then re-activate. When I did this I lost the file that was on the iMac and can no longer find it.  This was a simple txt file with some important information in it.
Does anyone know if the file has been sent to a certain trash or similar? I would really like to recover this file if possible.

A: In answer to this I was recently looking through my desktop to clean some things up and noticed a directory labeled Previous local iDisks and within this directory contained the iDisk that had been removed.  Note I am on osx 10.6.8.
Hopefully this helps someone else out in a similar predicament in the future.


text:
Q: A way to ignore specific questions
Possible Duplicate:
Hide a particular question locally

I would really like a private-to-me tag, like Favorite, but kinda the opposite -- something that lets me ignore specific posts and by ignore, I mean 'exclude from lists'. I like to look at the unanswered list for certain tags, looking for things I know about or can help with. Some questions on the unanswered lists seem to languish for some time, and hinder ready access to questions further down the lists, that I might know something about. As for the questions I want to ignore: I don't know anything that would help, and I'm not interested, so I want to not see that question again in these lists. It would be ideal if it they would still show up in search results (if they match), just not in the unanswered, highest voted, and featured lists. (It's less of an issue for the newest and active lists.)
I don't want a public tag, since this is just about me specifically. I don't want to ignore the user as a whole, it's just this question. I don't (usually) want to ignore whole tags. I just want some way to take these specific posts out of my view of the lists, to clear the way to questions I might know something about.


text:
Q: Import.io simple script javascript I am trying to use integrate simple import.io with JavaScript (exemple website)  but the script not working. Can you help me?
  <!DOCTYPE html>       <title>Import•io
 Example</title>

     <button onclick="doQuery()">Query</button>

A: Before moving towards interaction extractor in import.io I always test it locally on desired website using User JavaScript and CSS chrome extension.
May be this can help you.


text:
Q: Controls Shifted after Displaying Error This is very embarrassing, but I am having a hard time getting it to display correctly. The form below has several controls which display correctly without validation message. However, the controls are shifted when I display the validation's error message; they are all over the place. After reading the bootstrap document and doing quite a bit of searching only, I played around with the clearfix and tried display table with no success. What can I do to prevent the controls from shifting after display a validation message?

Here is the HTML being used.

First Name:
 First Name:
                        @Html.TextBoxFor(mbox => mbox.FirstName, new { @class = "form-control", id = "FirstName" })

Middle Name:
 Middle Name:
                        @Html.TextBoxFor(m => m.MiddleName, new { @class = "form-control", id = "middleName" })

Last Name:
 Last Name:
                        @Html.TextBoxFor(m => m.LastName, new { id = "LastName", @class = "form-control" })

Department:
Department:
                        @Html.TextBoxFor(m => m.Department, new { @class = "form-control", id = "Department" })

Office Number:
Office Number:
                        @Html.TextBoxFor(mbox => mbox.OfficeNumber, new { id = "OfficeNumber", @class = "form-control" })

Extension:
 Extension:
                        @Html.TextBoxFor(mbox => mbox.Extension, new { id = "Extension", @class = "form-control" })

User Name:
 User Name
                        @Html.TextBoxFor(m => m.UserName, new { id = "UserName", @class = "form-control" })

Password:
Password:
                        @Html.PasswordFor(m => m.Password, new { id = "Password", @class = "form-control" })

Email Address:
Email Address:
                        @Html.TextBoxFor(m => m.EmailAddress, new { id = "emailAddress", @class = "form-control" })

Practitioner
Practitioner:
                        @Html.DropDownListFor(mbox => mbox.PractitionerID, new SelectList(Model.availablePractitioners, "ID", "FullName"), new { id = "Practitioner", @class = "form-control" })

Active:
Active:
                        @Html.CheckBoxFor(m => m.Active, new { id = "Active", @class = "form-control", @checked = "checked" })

A: After posting the question, I realized that wrapping a group of 3 controls inside a col-xs-12 will prevent them from shifting.

First Name:
 First Name:
                        @Html.TextBoxFor(mbox => mbox.FirstName, new { @class = "form-control", id = "FirstName" })

Middle Name:
 Middle Name:
                        @Html.TextBoxFor(m => m.MiddleName, new { @class = "form-control", id = "middleName" })

Last Name:
 Last Name:
                        @Html.TextBoxFor(m => m.LastName, new { id = "LastName", @class = "form-control" })


text:
Q: package name and certificate fingerprint combination already exists I'm getting an error while trying to add google play services like below:

Package name and certificate fingerprint combination already exists

How can I handle this?

A: I also had the same, i followed these steps it's working fine now.

*

*Click on Remove this app from Enter THE APP DETAILS section.

*Change the pacakge name of the application that you are trying to
add.

*Now replace the newly created package name in ENTER THE APP DETAILS
section.

*Now just give the SHA1 finger print key

*Done.

A: Maybe you have a duplicate project which you deleted long ago, but when you go to the page where you can set your project API and click on "manage all project", the deleted project actually is still there and you'll have to delete it there.
Check these questions:

*

*Google play services error with generating OAuth2.0 client

*possible bug for Google play game service package name?


text:
Q: Is there any XML-Tag associations or mapping for updraging Tomcat's web.xml file to GlassFish4's glassfish-web.xml configuration file? glassfish-web.xml file was by default included when i checked "GlassFish Web Extension" checkbox in Project Facets of the web application properties.
Is there any xml-tag association or mapping between GlassFish and Tomcat web configuration files for upgrading from Tomcat to GlassFish Server?
Apart from this issue, In Spring Tool Suite, both Tomcat and GlassFish Server were added and then tried to execute the web application on Tomcat Server, by default GlassFish is taking over it and starting.
When I am trying to start Tomcat Server this is the error message it is displaying:


text:
Q: 18.04 ctrl+shift to change language Can I use Ctrl+Shift for changing languages? I can't set this hotkey for changing keyboard languages.
At this moment Alt+Shift switch languages, but I can't see this hotkey in keyboard hotkeys list or in
gsettings list-recursively  org.gnome.desktop.wm.keybindings | sort | more

output.

A: You can set such keyboard shortcut as follows:

*

*On Ubuntu 18.04 LTS, 20.04 LTS, 21.04 and 21.10 with GNOME desktop from GNOME Tweaks.

*

*Install it
sudo apt-get install gnome-tweaks

*Then open GNOME Tweaks (gnome-tweaks).

*Select Keyboard & Mouse tab

*Click Additional Layout Options button

*Expand Switching to another layout

*Select Ctrl + Shift here
See screenshot below:

Or simply:
gsettings set org.gnome.desktop.input-sources xkb-options \
  "['grp:ctrl_shift_toggle']"

If you do not like Super + Space and Shift+Super+Space you can disable them with
gsettings set org.gnome.desktop.wm.keybindings switch-input-source "['']"
gsettings set org.gnome.desktop.wm.keybindings switch-input-source-backward  "['']"
gsettings set org.freedesktop.ibus.general.hotkey triggers "['']"

Note: you will face interference problem as Ctrl+Shift+T in GNOME Terminal will switch language at once with opening new tab. It is known bug 1683383.

*On Ubuntu MATE 18.04 LTS and newer versions this is possible from mate-keyboard-properties:

*

*Open MATE Control Center

*Click Keyboard

*Go to Layouts tab

*Click Options

*Expand Switching to another layout

*Select Ctrl + Shift here

See screenshot below:

Or simply:
gsettings set org.mate.peripherals-keyboard-xkb.kbd options \
      "['grp\tgrp:ctrl_shift_toggle']"

Note: here bug 1683383 is fixed by packages from my PPA :
sudo add-apt-repository ppa:nrbrtx/xorg-hotkeys
sudo apt-get update
sudo apt-get dist-upgrade

So Ctrl + Shift keyboard layout switcher will work normally on MATE DE after applying patch from ArchLinux AUR "for freedesktop bug 865 (need to kick hotkeys on release, not press)".

Warranty disclaimer: packages were tested in

*

*16.04 LTS with HWE (Unity, MATE, Xfce)

*18.04 LTS (Cinnamon, KDE, MATE, Xfce)

*18.10 (Cinnamon, KDE, MATE, Xfce)

*19.04 (Cinnamon, KDE, MATE, Unity, Xfce).

*19.10 (Cinnamon, KDE, MATE, Unity, Xfce)

*20.04 LTS (Cinnamon, KDE, MATE, Unity, Xfce)

*20.10 (Cinnamon, KDE, MATE, Unity, Xfce)

*21.04 (Cinnamon, KDE, MATE, Xfce)

*21.10 (Cinnamon, KDE, MATE, Xfce)

However other desktops may have issues even after applying the patch.
These packages do not fix problems for GNOME Shell (18.04 LTS, 18.10, 19.04, 19.10, 20.04 LTS, 20.10 and 21.04) and Unity (in 18.04 LTS and 18.10).

If you are interested you can participate in poll and discussion on community.ubuntu.com.

A: I found a partial workaround based on other answers for using Ctrl+Shift and shortcuts for GNOME in Ubuntu 18.04:

*

*Install GNOME Tweaks as proposed in N0rbert's anwser:
sudo apt install gnome-tweaks

then:

*

*run it;

*open "Keyboard & Mouse" tab;

*click "Additional Layout Options" button;

*instead of selecting Ctrl+Shift key combination in "Switching to another layout" of "Additional Layout Options" window simply untick all checkboxes:

*Open "Settings" application from "Show applications" menu at the left bottom corner. Alternatively run a command in terminal:
gnome-control-center

then

*

*go to "Devices" > "Keyboard" tab;

*scroll to "Typing" group;

*set shortcuts for "Switch to next input source" and "Switch to previous input source" (an order of keys DOES MATTER!!!):

If setting Ctrl+Shift or Shift+Ctrl shortcuts is impossible using this dialog (as it was in my case), then you can change these parameters in an alternative way:

*

*install dconf-editor:
sudo apt install dconf-editor

*run it from terminal:
dconf-editor

*go to org > gnome > desktop > wm > keybindings;

*select switch-input-source or switch-input-source-backward;

*switch off "Use default value" and input "Custom Value": <Control>Shift_L for changing layout with Ctrl+Shift or <Shift>Control_L — for changing layout with Shift+Ctrl:

Another way is to use gsettings set console command as proposed here:
gsettings set org.gnome.desktop.wm.keybindings \
switch-input-source "['<Control>Shift_L']"

A limitation of this solution is that an order of keys pressed is important. If you set Ctrl+Shift to change keyboard layout then it will work only when you press Ctrl key first, and then Shift key. Pressing Shift key first and Ctrl after will not work in this case. But this fact allows to use shortcuts containing Shift and Ctrl keys combination in different applications , for example:

*

*Shift+Ctrl+T to open new tab in Terminal;

*Shift+Ctrl+E to export image in Gimp;

*Shift+Ctrl+F to open search dialog in WebStorm/PhpStorm.


text:
Q: ASP.NET Core Web App Dependency Injection with Multiple Implementations How do you register services in an enumerable way? For example I'm working on a solution similar to OpenLM. I would like to have a configuration file that defines the inputs.  For example:
"Collectors": {
"Frequency": "2",
"FlexLM": {
  "ExePath": "Resources\\lmutil.exe",
  "Servers": [
    {
      "Server": "port@server",
      "Product": "product"
    }
  ],
},
"SentinelRMS": {
  "ExePath": "Resources\\lsmon.exe",
  "Servers": [
    {
      "Server": "server",
      "Product": "product 2"
    }
  ]
}

This requires two services, one knows how to communicate with FlexLM and the other with Sentinel RMS. I've implemented it a non-IoC way like this
internal static IEnumerable<IDataCollector> Build()
{
    var time = DateTime.Now;
    var collectors = new List<IDataCollector>();
    AddSection("Collectors:FlexLM", collectors);
    AddSection("Collectors:SentinelRMS", collectors);
    return collectors;
}

private static void AddSection(string section, List<IDataCollector> collectors)
{
   if (ConfigurationAdapter.Sections.Contains(section))
   {
        var exePath = ConfigurationAdapter.Config.GetSection($"{section}:ExePath").Get<string>();

        var children = ConfigurationAdapter.Config.GetSection(section + ":Servers").Get<ServerConfig[]>();
        if (children != null)
        {
            foreach (var item in children)
            {
               if (section == "Collectors:FlexLM")
               {
                   collectors.Add(new FlexLmDataCollector(item.Server, item.Product, exePath));
               }
               else if (section == "Collectors:SentinelRMS")
               {
                   collectors.Add(new SentinelRmsDataCollector(item.Server, item.Product, exePath));
               }
            }
        }
    }
}

Later in the process these services are consumed in parallel like this
Parallel.ForEach(collectors, new ParallelOptions { MaxDegreeOfParallelism = 99 }, (collector) =>
{
    collector.ReadLicenses();
});

Creating a service for communicating with

A: I created one service for each type of license server. Each service is responsible for multiple servers, which are passed in a IOptions. First I configured the services.
builder.Services.Configure<SentinelRmsServiceOptions>(
    builder.Configuration.GetSection(SentinelRmsServiceOptions.Section));
builder.Services.Configure<FlexLmServiceOptions>(
    builder.Configuration.GetSection(FlexLmServiceOptions.Section));
builder.Services.Configure<DataCollectorsOptions>(
    builder.Configuration.GetSection(DataCollectorsOptions.Section));

Register multiple services
builder.Services.AddSingleton<IDataCollectorService, SentinelRmsDataService>();
builder.Services.AddSingleton<IDataCollectorService, FlexLmDataService>();

The constructor for the service that calls the server specific services looks like this
public DataCollectorsService(
    ILogger<DataCollectorsService> logger,
    IEnumerable<IDataCollectorService> services,
    IOptions<DataCollectorsOptions> options)

The options class matches the appsettings.json
public class FlexLmServiceOptions
{
    public static string Section => "Collectors:FlexLM";
    public string ExePath { get; set; }
    public IEnumerable<ServerInfo> Servers { get; set; }
}

The service communicates with the servers using the original classes
Parallel.ForEach(options.Servers, item =>
{
    var collector = new FlexLmDataCollector(item.Server, item.Product, options.ExePath, enrichers);
    collector.ReadLicenses();
});


text:
Q: How to debug sql files in eclipse? I have a big .sql files which contain long queries which are confusing. Is there any possibility to debug in eclipse? if not, is there a good method to see what the single parts of the longer query deliver?

A: Look for an option to execute the highlighted text, then you can select parts of the query and run them in isolation. As per comment from Uwe, you can't single step the decisions the query engine makes and the rows it sticks together as it builds the result set. you may also need to employ selective commenting out, for example, multiline comment out all the select list and just select *, comment out X number of joined in tables and their related where clauses, and run the query.. keep adding tables back in to the join until things go pear shaped (usually things like duplicate values, or missing rows) and examine the problematic join
Familiarise yourself with the execution plan explanation system; it tells you how the database executed the query, but teaching you how to read it is too broad for a SO answer; some hours work will be needed to gain this understanding
Lastly, make sure your sales are well formatted/indented. There isn't a set standard, so just make up your own style if one isn't already published for your workplace, or get consensus from other debts.. I tend to lay mine to like:
Select
  Columns
From
  Table
  Join
  Table
  On
    Predicates
  Join
  (
    Select
      Columns
    ...
  ) subquery
  On
    Predicates
Where
  Predicates
Group/order by

Because everything that operates at the same "level" is indented the same amount. Subqueries go in brackets at the same level as the data they produce interacts with other tables.. this makes it vastly easier to see which groups/joins/selects act together and what feeds into what


text:
Q: Is CircleCI able to interpret JUnit XML results generated through Gradle without extra plugins? I have a build.gradle running on CircleCI with the following characteristics:

*

*It contains the dependency: testCompile 'junit:junit:4.12'

*It contains normal JUnit test cases.

*Tests run with commands like gradle build or gradle test

*When tests run, JUnit writes their results as XML files in the build/test-results directory. These are files with names like TEST-*.xml
However, CircleCI seems to be unable to parse these files. All it shows is a message like 'The following errors were encountered parsing test results:', and, then, a list of all the XML files.
Does anyone know whether it is necessary to generate these test results in a particular format? If so, what would it be?

A: For some reason I can't explain, introducing the Gradle Wrapper into the project solved my problem.
For info about the Gradle Wrapper, see: https://docs.gradle.org/current/userguide/gradle_wrapper.html


text:
Q: Create select option button with nested categories in Laravel excuse me for my bad language :)
I have a table with multilevel categories like this :
category_id ------ category_name--------parent_id
1------------------sample 1 ------------ NULL
2------------------sample 2 ------------ 1
3------------------sample 3 ------------ NULL

and...
now I need to have this data in the select option menu
this is my form :

        مادر

            <select name="parent_id" class="select2 form-control" id="parent_id">
                <option value="">انتخاب دسته مادر</option>
                @foreach ($categories as $cat)
                    <option value="{{ $cat -> category_id }}"
                            {{ isset($productItem) && $productItem->category_id == $cat->category_id ? 'selected':'' }}
                    >{{ $cat -> category_name }}</option>
                @endforeach
            </select>

A: You should use <optgroup> to make some "nested" options. Check this example.
Your code would be:
<select name="parent_id" class="select2 form-control" id="parent_id">
  <option value="">انتخاب دسته مادر</option>
  @foreach ($categories->where('parent_id', null) as $cat)

    <option value="{{ $cat->category_id }}">
      {{ $cat->category_name }}
    </option>

    @if($cat->children->count())
    <optgroup label="{{$cat->category_name}}">
      @foreach($cat->children as $child)
        <option value="{{ $child -> category_id }}">
          {{ $child -> category_name }}
        </option>
      @endforeach
    </optgroup>
    @endif
  @endforeach
</select>

This should create:

*

*<optgroup> for each parent categories

*<option> placed just before optgroup for the parent categories

*<option> for every child categories

A: should be like this
but in level 3 I have the problem
and I changed my code :
<select name="parent_id" class="select2 form-control" id="parent_id">
                <option value="">انتخاب دسته مادر</option>
                @foreach ($categories as $cat)
                    @if($cat -> parent_id == NULL)
                        <option value="{{ $cat -> category_id }}">
                            {{ $cat -> category_name }}
                        </option>
                    @endif
                    @if ($cat->children->count() > 0)
                        @foreach($cat->children as $child)
                            <option value="{{ $child -> category_id }}">
                                {{ $child -> category_name }}
                            </option>
                        @endforeach
                    @endif
                @endforeach
            </select>

A: After hoping to find an answer that uses Laravel nicely, I ended up giving up and just writing the code to do what I wanted myself, and it ended up smaller than I anticipated.
public function get_categories()
{

    $categories = Category::where('parent',null)->get();
    while(count($categories) > 0){
        $nextCategories = [];
        echo "<option value='.$categories->.'>'.$categories->name .'</option";
        foreach ($categories as $category) {
          $childCategories = Category::where('parent',$category->id)->get();
          echo "<option value='.$categories->.'>'.$childCategories->name .'</option";
        }
    }

}


text:
Q: Cannot install shutter due to libxml-simple-perl I cannot install shutter:
$ sudo apt-get install -f  shutter
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 shutter : Depends: libxml-simple-perl but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

$ sudo apt-get install -f libxml-simple-perl
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 libxml-simple-perl : Depends: libxml-sax-perl but it is not going to be installed
                      Depends: libxml-libxml-perl but it is not going to be installed or
                               libxml-sax-expat-perl but it is not going to be installed
E: Unable to correct problems, you have held broken packages.

Ubuntu version is 12.04 LTS - "Wubuntu" standard install.
I have not added any other repositories.
Running: apt-cache policy shutter libxml-simple-perl libxml-sax-perl libxml-libxml-perl libxml-sax-expat-perl results in:
Installed: (none) and 500 http://archive.ubuntu.com/ubuntu/ precise/main amd64 Packages

for each of those packages.
What to do next?

A: After adding mirrors to my sources configuration:

*

*sudo apt-get update

*sudo apt-get install -f
and shutter is installed.


text:
Q: Is it possible to upload files to multiple google drive accounts synchronously using Drive API in Android? Details:- I want to synchronously upload three files to three different google drive accounts from my Android Application.My current implementation is uploading all the three files in just one (last logged-in) account.So i want to know whether is it technically possible to do so?
1> Right now,I have three different classes for three Drive accounts.I am using Drive API and GooglePlay services gms:play-services:11.4.2 .
Code snippet for initializing mGoogleApiClient:-
 public void init(Activity context, final ICDCallback<String> cb) {
    if (this.mGoogleApiClient == null) {
        this.mGoogleApiClient = new Builder(context).addOnConnectionFailedListener(new OnConnectionFailedListener() {
            public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                cb.failure(connectionResult.getErrorMessage());
            }
        }).addConnectionCallbacks(new ConnectionCallbacks() {
            public void onConnected(@Nullable Bundle bundle) {
                cb.success("");
            }

            public void onConnectionSuspended(int i) {
                cb.progress(0);
            }
        }).addApi(Drive.API).addApi(Auth.GOOGLE_SIGN_IN_API, new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestScopes(new Scope("https://www.googleapis.com/auth/drive.file"), new Scope[0]).requestEmail().build()).build();
    }
    if (this.mGoogleApiClient != null && this.mGoogleApiClient.isConnected())
    {
        cb.success("");
    } else {
        connect();
    }
}

2> Result:- This method is called each time the user is logged in and file uploading. But the mGoogleApiClient has always last logged-in google drive Account because of which I think,files are uploaded in the last logged-in account instead of three different accounts.
3>So please what should i do in this case?
i) Is it possible to save the user account info in respective class in current implementation and use it while uploading? Or is there any other better way to do that?
ii) Can Google OAuth2.0 library help if i try to save any user specific account information in corresponding drive classes?
Please suggest pointers to go ahead.


text:
Q: Basic LISP recursion, enumerate values greater than 3 I need a recursive LISP function that enumerates the number of elements in any list of numbers > 3. I'm not allowed to use lets, loops or whiles and can only use basic CAR, CDR, SETQ, COND, CONS, APPEND, PROGN, LIST...
This is my attempt at the function:
(defun foo (lst)
  (COND ((null lst) lst)
    (T (IF (> (CAR lst) 3)
      (1+ (foo (CDR lst)))
      (foo (CDR lst)) ) ) ) )

The function call:
(foo '(0 1 2 3 4 5 6))

A: Your code is pretty close to correct, just a small mistake in the base case:
For the empty list you return the empty list. So if you have the list (6), you add 6 to foo of the empty list, which is the empty list. That does not work because you can't add a number to a list.
You can easily fix it by making foo return 0 instead of lst when lst is empty.
As a style note: Mixing cond and if like this, seems a bit redundant. I would write it like this, using only cond instead:
(defun foo (lst)
  (cond
    ((null lst)
      0)
    ((> (car lst) 3)
      (1+ (foo (cdr lst))))
    (T
      (foo (cdr lst)))))

A: Some stylistic points:

*

*There's no need to put some Lisp built-ins in uppercase. It's not 1958 anymore!

*But if you are going to put built-ins in uppercase, why not DEFUN and NULL?

*You have an if inside the last branch of your cond. This is redundant. Since the purpose of cond is testing conditions, why not use it?

*There's no need to space out your closing parentheses like that. No-one counts parentheses these days, we have parenthesis-matching editors.

*Lisp has separate namespaces for functions and values, so you don't have to call your argument lst to avoid conflicting with the built-in function list.

If you were programming this for real, of course you'd use count-if:
(count-if #'(lambda (x) (> x 3)) '(0 1 2 3 4 5 6))
    ==> 3

A: One save you can have on duplication of the recursive call:
(defun foo (l)
  (if (null l) 0               ; if list is empty, return 0
    (+ (if (> (car l) 3) 1 0)  ; else +1 if condition is satisfactory
      (foo (cdr l)))))         ; plus the result from the rest


text:
Q: Which is better LOOP before CONDITIONAL or CONDITIONAL before LOOP in a menu type code? Good day,
I currently have a code for applying photo effects from a menu and would like some advice on how to handle it better.
Should I do LOOP before CONDITIONAL like this:
function applyFilter(filter){
  var ctx = canvas.getContext('2d');
  var imageData = ctx.getImageData(img.x,img.y,img.width,img.height);
  var dataArr = imageData.data;

  for(i = 0; i < dataArr.length; i+= 4){
    let color = {
      r : dataArr[i],
      g : dataArr[i+1],
      b : dataArr[i+2],
    }

    if(filter == "negative")
        negateImage(dataArr, i, color)
    else if(filter == "sephia")
        addSephia(dataArr, i, color)
    // else if  some other effects

or CONDITIONAL before LOOP like this:
function applyFilter(filter){

   if(filter == "negative")
       negateImage()
   else if(filter == "sephia")
      addSephia()
   // else if some other effects

}

function negateImage(){
  var ctx = canvas.getContext('2d');
  var imageData = ctx.getImageData(img.x,img.y,img.width,img.height);
  var dataArr = imageData.data;

  for(i = 0; i < dataArr.length; i+= 4){
  // negate image algorithm
  }

}

Thank you in advance for answering!

A: Checking the condition only once is definitely better performance-wise. That said, the performance impact is likely minimal, especially once branch prediction starts kicking in, especially in comparison to other parts of the code. Best to avoid premature optimization unless you've run a performance test and have identified a section of code that needs to run faster - until then, better to write code to be DRY and readable.
You might consider creating a function that calls the negateImage or addSephia outside of the loop. You may also save the length of the dataArr, rather than re-calculate on each iteration:
function applyFilter(filter) {
  var ctx = canvas.getContext('2d');
  var imageData = ctx.getImageData(img.x, img.y, img.width, img.height);
  var dataArr = imageData.data;
  const fn = filter === 'negative' ?
    (i, color) => negateImage(dataArr, i, color) :
    (i, color) => addSephia(dataArr, i, color);
  const { length } = dataArr;
  for (let i = 0; i < length; i += 4) {
    fn(
      i,
      {
        r: dataArr[i],
        g: dataArr[i + 1],
        b: dataArr[i + 2],
      }
    );
    // ...

(make sure not to implicitly create global variables too - declare the i in the for loop)


text:
Q: java.io.FileNotFoundException for file R.java (R.java gets generated to wrong path) I have had a problem where R.java is being generated to a strange path when I build.  The path is as follows:
<App folder>\<App Name>\build\generated\source\r\<Flavor suffix>\debug\<ApplicationId>\<Flavor suffix>\R.java

To my knowledge the path should be only under the flavor suffix first and then under the applicationId, but as you can see from my example it is being generated under a second Flavor suffix.
Any help would be appreciated.  The exact error is as follows:
    * What went wrong:
Execution failed for task ':aiDx:generateY1DebugR2'.

java.io.FileNotFoundException: C:\Workspace\Y1 - Test App\aiDx\build\generated\source\r\y1\debug\ait\com\aidx\y1\R.java (The system cannot find the path specified)

A: For anyone that gets this issue, Butterknife was causing this build problem.
The solution can be found here: https://github.com/JakeWharton/butterknife/issues/1177


text:
Q: k nearest neighbours algorithm python this is my code for the k nearest neighbor algorithm:
import numpy as np

from EuclideanDistance import EuclideanDistance

dataset = np.loadtxt('C:\Users\Toshiba\Documents\machine learning\RealEstate.csv',      delimiter=',', usecols=(2,3,4,5))
p1 = ()

def normalizeToZscores(data):
    '''Normalizes the variables to z-scores'''
    zScores = list()
for s in data:
    zScore = (s - np.mean(data))/np.std(data)
    zScores.append(zScore)
    return np.asarray(zScores)

def InOutBudget(data):
    '''Decides whether a particular house is within
    or outside the budget of $153000 and assigns values of 1 and 0 respectively'''
    data2 = list()
    for i in data:
        if (i > 153000): data2.append(0)
        else: data2.append(1)
    return np.array(data2)

classes = dataset[:,0]
classes = classes.reshape((dataset.shape[0],1))
classes = InOutBudget(classes)

data = dataset[:20,:]
data = normalizeToZscores(data)

p1s = dataset[20:400,:]

def measureDis(data, p1):
    listD = []
    for x in data:
    D = EuclideanDistance(x, p1)
    listD.append(D)
return listD

def most_common(lst):
    '''Finds the most frequently occuring element of a list.
    It will be used to predict a class based on the classification
    of the k-nearest neighbours'''
    return max(set(lst), key=lst.count)

def findKnn(k):
    '''K nearest neighbours algorithm'''
    knns = list()
    errors = list()
    #for i in k:
    for p1 in p1s:
        # Create a list of tuples containing distance and class,
        # Then sort them by shortest distance
        tuples = zip(measureDis(data,p1), classes[20:400])
        tuples = sorted(tuples)
        knn = tuples[:k]
        print knn
        knn = [x[1] for x in knn]
        knn = most_common(knn)
        knns = knns.append(knn)
        print knn
        error = np.abs(knn - p1)
        errors = errors.append(error)
    errorsNum = np.sum(errors)

    return knns

But I keep getting:
Traceback (most recent call last):
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 76, in <module> knn = findKnn(k)
File "C:\Users\Toshiba\workspace\assignment5\src\knn2.py", line 64, in findKnn knns = knns.append(knn)
AttributeError: 'NoneType' object has no attribute 'append'

I know the code is really amateur, but could someone please help me just solve the issue?

A: list.append doesn't return the list. Simply do:
knns.append(knn)

instead of:
knns = knns.append(knn)

A: append does not return the list, it returns None, so you are clobbering it after the first loop.


text:
Q: Decompress data in Span with Deflate algorithm I have a code that parses a binary file. It uses Span<byte> to pass chunks of data among functions to avoid unnecessary memory allocations.
Simplified example:
class Reader {
    bool IsCompressed { get; set; }
    public byte[] Data { get; set; }

    function ReadOnlySpan<byte> ReadBlock() {
        ...
    }

    public function Read() {
        if (IsCompressed) {
            Data = ???
        } else {
             Data = ReadBlock.ToArray();
        }
}

I can decompress data with Syste.IO.Compression.DeflateStream, but this class accepts only Stream as the input, so I have to convert ReadOnlySpan<byte> to a stream and thus allocate memory for byte[].
using(var stream = new MemoryStream(buffer.ToArray())) {
    using(var deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) {
        Data = ... read from deflateStream
    }
}

Is there any way to pass ReadOnlySpan<byte> to the DeflateStream without allocating unnecessary memory? Or is there any other library, that can decompress data directly from ReadOnlySpan<byte>?
I am using .NET Core 2.1.0-preview1-26103-03, but I can use any other version if necessary.

A: As of January 2018, there isn't any build-in support for ReadOnlySpan<byte>, but as Stephen Toub pointed out on GitHub it can be solved with the UnmanagedMemoryStream
private unsafe byte[] Decompress(ReadOnlySpan<byte> buffer, int decompressedSize) {
    fixed (byte* pBuffer = &buffer[0]) {
        using (var stream = new UnmanagedMemoryStream(pBuffer, buffer.Length)) {
            using (var deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) {
                var data = ArrayPool<byte>.Shared.Rent(decompressedSize);
                deflateStream.Read(data, 0, decompressedSize);

                return data;
            }
        }
    }
}

A: I'm not sure if unmanaged code is needed, perhaps consider something like this:
using var resource = Assembly.GetExecutingAssembly().GetManifestResourceStream("MyApp.Resources.Data.zip");
if (resource is null)
    throw new ResourceNotFoundException("Data.Zip", Assembly.GetExecutingAssembly());

using (ZipArchive archive = new System.IO.Compression.ZipArchive(stream: resource))
{
    foreach (var entry in archive.Entries)
    {
        if (string.Equals(entry.Name, "My.json", StringComparison.InvariantCultureIgnoreCase))
        {
            using var unZip = entry.Open();
            var bytes=new byte[(int)entry.CompressedLength].AsSpan();
            unZip.Read(bytes);
            var data= Newtonsoft.Json.JsonConvert.DeserializeObject<MyObject>(System.Text.Encoding.UTF8.GetString(bytes));
        }
    }
}

Performs ok and lowers the size of embedded resources considerably


text:
Q: Unable to defragment win7 laptop I have a Windows 7 laptop that I have been unable to defragment for the last several months.
When I try to invoke the defragmenter from the command line it says "The dirty bit is set on this volume".  So I have tried to force it to defragment on the next reboot but that never happens.
When I try to invoke the defragmenter UI I get a dialog which says "Disk Defragmenter was scheduled using another program" and presents me with a "Remove settings" button which apparently has no effect.
I can't delete the scheduled task even when I run Task Scheduler as Administrator, I get a message that says "Transaction support within the specified resource manager is not started or was shut down due to an error"
Any suggestions on how to get the win7 defragmenter to run?  I am aware that 3rd party defragmenter solutions exist.

A: Raymond Chen (long time Windows developer) explains the dirty bit here:

One mystery that has gone unsolved for the longest time now is the
  dirty bit on hard drive volumes. Basically a dirty bit is just a 1 hex
  value located somewhere hidden on the hard drive that Microsoft has
  never reveal until recently. Windows will check the dirty bit to
  determine if a volume can contain corrupted files due to hard
  resetting your Windows computer with files that are still opened or
  when you unplug a USB flash drive that is in the midst of copying a
  file.
When the computer boots up with the dirty bit enabled on a hard drive,
  you will be asked to check the disk for consistency before Windows is
  loaded. You can skip the disk checking by pressing any key but it will
  come back again the next time you start up your computer. This will
  usually keep happening until you let the drive be scanned or
  alternatively you can tell Windows to stop checking the specific
  drive. This method doesn't clear the dirty bit on the drive though and
  simply forces Windows not to scan a drive on boot.

So, assuming that the dirty bit is set (which you can use fsutil dirty query c: to find out) then you have three options:

*

*Reboot your computer and allow the disk to be checked.

*Run chkdsk c: /F to attempt to fix any errors.

*Use a hex editor/alternative boot CD to manually set the bits on the drive (found on page 2 of his article).

Personally I'd probably just reboot the computer as it ensures that there is nothing running that could prevent the scan from happening.
Once the dirty bit has been unset, you should be able to run the defragment program.
Side note: Use fsutil dirty set c: if you want to manually set the dirty bit on drive C. There is no way to use fsutil to unset it though.


text:
Q: Pass json to Vue component and loop This is the expected output:

Title 1

Text 1

Title 2

Text 2

    ...

This is my PHP file:
// Contains HTML markup
$array = [
    ['title' => 'Title 1', 'text' => '
Text 1<\/p>'],
    ['title' => 'Title 2', 'text' => '
Text 2<\/p>'],
    ...
];

    <list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>

And this is my JavaScript file:
var containers = document.querySelectorAll('.container');
if(containers.length > 0) {
    for(var i=0; i<containers.length; i++)
        buildList(containers[i]);
}

function buildList(el) {

    Vue.component('list-item', {
        props: ['listProp'],
        template: '

{{ listProp.title }}

{{ listProp.text }}

'
    });

    var container = new Vue({
        el: el,
        data: {
            list: JSON.parse(el.dataContent)
        }
    });
}

I'm getting an error Unexpected token u in JSON at position 0 at JSON.parse I'm obviously doing something wrong but I'm not sure where. Would love to know if there are better ways to achieve this. I read answers using :prop but I don't know how to implement it in my case.

A: I REALLY hate this suggestion, but here is something you could do without creating a simple REST API with PHP. Then, once you have this object on the window object, you can then reference it within your Vue.js code.

// Contains HTML markup
<?php
$array = [
    ['title' => 'Title 1', 'text' => '
Text 1<\/p>'],
    ['title' => 'Title 2', 'text' => '
Text 2<\/p>'],
    ...
];
?>

    <list-item v-for="item in list" v-bind:list-prop="item" v-bind:key ="item.title"></list-item>


text:
Q: How to get distances from all trained images in face recognition using EmguCV? I was able to compile a simple face detection and recognition program in c# using EmguCV, following this article:
http://ahmedopeyemi.com/main/face-detection-and-recognition-in-c-using-emgucv-3-0-opencv-wrapper-part-1/
Once trained the recognizer, the Predict method correctly returns the corresponding Label (or distance) of the image passed.
Is it possible to get a list of all the distances between the image sample and the faces in the database?
Basically, I would have to write another predict method like suggested in:
http://answers.opencv.org/question/3494/adding-new-method-in-facerecognizer/
http://answers.opencv.org/question/19681/confidence-values-for-all-faces-from-facerecognizer/
But I'm working with c# and Emgu, how can I do?
Thanks for your help


text:
Q: url cyrillic encoding issue (with webbrowser control) I use C# web browser to send request. But url includes cyrillics symbols, and I use proxy so I need to encode the url.
The origin url: http://mysite.com/info?q=москва+дизайн
I need  http://mysite.com/info?q=%E4%E8%E7%E0%E9%ED+%EC%EE%F1%EA%E2%E0
What C# functions exist to make that?

A: You can use System.Web.HttpUtility.UrlEncode().  Its default encoding is utf-8, yours look like Windows code page 1251 with the words reversed.  I suppose you ought to pass Encoding.Default.  The closest match is:
var enc = Encoding.GetEncoding(1251);
var url = "http://mysite.com/info?q=" +
          System.Web.HttpUtility.UrlEncode("москва+дизайн", enc);

Which produces:
"http://mysite.com/info?q=%ec%ee%f1%ea%e2%e0%2b%e4%e8%e7%e0%e9%ed"


text:
Q: customize validation messages i want to know how to fully customize validation messages, this is how my code looks like
user_profile.rb:-
validates: first_name, :presence => {:message => "First name can't be blank"}

but this gives me an error message user profile first name First name can't be blank and what i want is to have an error message First name can't be blank. I look around for solution and i think i have to do some changes in en.yml file, but i don't know what to do. Any help?

A: You have three options:
validate do |user|
  user.errors.add_to_base("First name can't be blank") if user.first_name.blank?
end

or
Doing user_profile.errors.full_messages will give you  -> ["First Name can't be blank"]
validates: first_name, :presence => {:message => "can't be blank"}

or
# config/locales/en.yml
en:
  activerecord:
    attributes:
      user_profile:
        first_name: "First name"
    errors:
      models:
        user_profile:
          attributes:
            first_name:
              blank: "can't be blank"

For more information on how to use locales, have a look at this

A: Rails uses their own error handling. Which means that it shows the database column. This results into name of column *can't be blank.
Try using something like this and only thing you have to do is change your model.
<% if object.errors.any? %>

   <%= pluralize(object.errors.count, "error") %>
   probited this <%= object.class.to_s.underscore.humanize.downcase %> from being saved

There were problems with the following fields:

  <% object.errors.full_messages.each do |message| %>

<%= message %>

  <% end %>

<% end %>

Besides that, I'd use Javascript/HTML5 validation for blank fields. To decrease bandwith usage.
Hope this helps.


text:
Q: Refresh in iOS simulator over VNC we have a mac mini, where we test over VNC-viewer our iOS app in iOS simulator 6.0 (369.2).
I guess after some system upgrades (now it's 10.8.3) VNC-viewer doesn't show simulator's screen changes and in order to see next screen, moving of simulator's window required.
I tried Ultra- and TigerVNC-viewer on Windows and Remmina on linux - seems to be - it's not the client. Everywhere the problem persists.
Does anyone have an idea, how to improve the situation?
Thanks in advance!
Daniel

A: https://discussions.apple.com/thread/4924818
I bet you don't have a monitor connected to your mac mini like me. I didn't use their trick but I can confirm once I hooked my monitor up to the mac mini it started working correctly. Hope this helps.


text:
Q: Resource Loading: How to determine if it's a directory Currently I use this solution to load resources:
URL url = MyClass.class.getClassLoader().getResource("documents/"+path);
if(url == null)
    throw new FileNotFoundException();

BufferedReader reader = new BufferedReader(
    new InputStreamReader(url.openStream()));

Sadly I can't control whether path is a file or a directory. Is there any way I can determine if the denoted path is a directory? I'm looking for a solution independent from where the resource is loaded (in other words: File.isFile won't work when loading resource from JAR).

A: I use this code to grab names of text files from a jar.
public String[] getFiles() throws IOException {
    ArrayList<String> list = new ArrayList<String>();
    List<JarEntry> ents = new ArrayList<JarEntry>();
    Enumeration<JarEntry> e = null;

    URL jarp = getLocation();
    if (jarp != null) {
        jar = jarp.getProtocol().equalsIgnoreCase("jar") ? jarp : new URL("jar:" + jarp.toString() + "!/");
        JarFile jarf = null;
        try {
            jarf = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<JarFile>() {

                        @Override
                        public JarFile run() throws Exception {
                            JarURLConnection conn = (JarURLConnection) jar.openConnection();
                            conn.setUseCaches(false);
                            return conn.getJarFile();
                        }
                    });
        } catch (PrivilegedActionException ex) {
            Logger.getLogger(LicenseLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
        e = jarf.entries();
        while (e.hasMoreElements()) {
            JarEntry je = e.nextElement();
            if (!je.isDirectory()) {
                ents.add(je);
            }
        }
        for (JarEntry ent : ents) {
            if ((ent.getName().startsWith(pathName)) && (ent.getName().endsWith(".txt"))) {
                String name = ent.getName().replace(pathName, "");
                list.add(name);
            }
        }
    }
    return list.toArray(new String[list.size()]);
}


text:
Q: Batch file - start program with admin rights I have a .bat file in my startup folder:
d:
cd\
cd TrueCrypt
truecrypt /ll /p "" /q /v d:\MYO

Is there a way to start TrueCrypt with admin right?

A: You can use runas
d:
cd\
cd TrueCrypt
runas /noprofile /user:mymachine\administrator truecrypt /ll /p "" /q /v d:\MYO

A: If it is run as a Startup Script it runs with Elevated permissions (at least in XP and earlier Not sure on Vista/7) This is set under Computer Configuration-Windows Setting-Scripts(Startup/Shutdown)


text:
Q: How to suppress TS6133 error with TypeGraphQL and TypeScript? I'm starting with TypeGraphQL and TypeOrm. I begin fallowing the "Getting started" guide in https://typegraphql.ml/docs/getting-started.html. I change the class in the guide with my own class so I have this:
@ObjectType()
@Entity()
export class Photo {

    @Field(type=>ID)
    @PrimaryGeneratedColumn()
    id: number;

    @Field()
    @Column()
    name: string;

    @Field()
    @Column()
    description: string;

    @Field()
    @Column()
    filename: string;

    @Field()
    @Column("real")
    views: number;

    @Field()
    @Column()
    isPublished: boolean;
}

But when I compile I get the error:
src/entity/Photo.ts(8,12): error TS6133: 'type' is declared but its value is never read.
What I need to do to suppress this error in TypeScript?

A: You do not need the type param for the @Field of your id :
@ObjectType()
@Entity()
export class Photo {

    @Field(()=>ID) // here is the difference
    @PrimaryGeneratedColumn()
    id: number;

    @Field()
    @Column()
    name: string;

    @Field()
    @Column()
    description: string;

    @Field()
    @Column()
    filename: string;

    @Field()
    @Column("real")
    views: number;

    @Field()
    @Column()
    isPublished: boolean;
}

A: Since you did not configure tsconfig.json for TypeScript correctly, it detects an error in the compile phase.
I am sharing a sample tscongif.json file.
With the TypeORM and TypeGraphQL binary, it is comfortable and to meet the desired requirements. You can change it later.
You can solve problem that friend who answered before me said @Julien TASSIN, but I would like to remind you that you know that main source of problem is through the TypeScript compilation rules.
example tsconfig.json file for TypeORM + TypeGraphQL
{
  "compilerOptions": {
    /* Basic Options */
    // "incremental": true,                    /* Enable incremental compilation */
    "target": "esnext",                        /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */
    "module": "commonjs",                      /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */
    "lib": ["esnext", "esnext.asynciterable"], /* Specify library files to be included in the compilation. */
    // "allowJs": true,                        /* Allow javascript files to be compiled. */
    // "checkJs": true,                        /* Report errors in .js files. */
    // "jsx": "preserve",                      /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
    // "declaration": true,                    /* Generates corresponding '.d.ts' file. */
    // "declarationMap": true,                 /* Generates a sourcemap for each corresponding '.d.ts' file. */
    // "sourceMap": true,                      /* Generates corresponding '.map' file. */
    // "outFile": "./",                        /* Concatenate and emit output to single file. */
    // "outDir": "./",                         /* Redirect output structure to the directory. */
    // "rootDir": "./",                        /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
    // "composite": true,                      /* Enable project compilation */
    // "tsBuildInfoFile": "./",                /* Specify file to store incremental compilation information */
    // "removeComments": true,                 /* Do not emit comments to output. */
    // "noEmit": true,                         /* Do not emit outputs. */
    // "importHelpers": true,                  /* Import emit helpers from 'tslib'. */
    // "downlevelIteration": true,             /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
    // "isolatedModules": true,                /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */

    /* Strict Type-Checking Options */
    // "strict": true,                         /* Enable all strict type-checking options. */
    // "noImplicitAny": true,                  /* Raise error on expressions and declarations with an implied 'any' type. */
    // "strictNullChecks": true,               /* Enable strict null checks. */
    // "strictFunctionTypes": true,            /* Enable strict checking of function types. */
    // "strictBindCallApply": true,            /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
    // "strictPropertyInitialization": true,   /* Enable strict checking of property initialization in classes. */
    // "noImplicitThis": true,                 /* Raise error on 'this' expressions with an implied 'any' type. */
    // "alwaysStrict": true,                   /* Parse in strict mode and emit "use strict" for each source file. */

    /* Additional Checks */
    // "noUnusedLocals": true,                 /* Report errors on unused locals. */
    // "noUnusedParameters": true,             /* Report errors on unused parameters. */
    // "noImplicitReturns": true,              /* Report error when not all code paths in function return a value. */
    // "noFallthroughCasesInSwitch": true,     /* Report errors for fallthrough cases in switch statement. */

    /* Module Resolution Options */
    "moduleResolution": "node",                /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
    // "baseUrl": "./",                        /* Base directory to resolve non-absolute module names. */
    // "paths": {},                            /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
    // "rootDirs": [],                         /* List of root folders whose combined content represents the structure of the project at runtime. */
    // "typeRoots": [],                        /* List of folders to include type definitions from. */
    // "types": [],                            /* Type declaration files to be included in compilation. */
    // "allowSyntheticDefaultImports": true,   /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
    // "esModuleInterop": true,                /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
    // "preserveSymlinks": true,               /* Do not resolve the real path of symlinks. */
    // "allowUmdGlobalAccess": true,           /* Allow accessing UMD globals from modules. */

    /* Source Map Options */
    // "sourceRoot": "",                      /* Specify the location where debugger should locate TypeScript files instead of source locations. */
    // "mapRoot": "",                         /* Specify the location where debugger should locate map files instead of generated locations. */
    // "inlineSourceMap": true,               /* Emit a single file with source maps instead of having a separate file. */
    // "inlineSources": true,                 /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */

    /* Experimental Options */
    "experimentalDecorators": true,           /* Enables experimental support for ES7 decorators. */
    "emitDecoratorMetadata": true             /* Enables experimental support for emitting type metadata for decorators. */
  }
}


text:
Q: Write ObjectNode to JSON String with UTF-8 Characters to Escaped ASCII I would like to write the contents of Jackson's ObjectNode to a string with the UTF-8 characters written as ASCII (Unicode escaped).
Here is a sample method:

private String writeUnicodeString() {
    ObjectMapper mapper = new ObjectMapper();
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("field1", "Maël Hörz");
    return node.toString();
}

By default, this outputs:
{"field1":"Maël Hörz"}

What I would like it to output is:
{"field1":"Ma\u00EBl H\u00F6rz"}

How can I accomplish this?

A: You should enable the JsonGenerator feature which controls the escaping of the non-ASCII characters. Here is an example:
    ObjectMapper mapper = new ObjectMapper();
    mapper.getFactory().configure(JsonGenerator.Feature.ESCAPE_NON_ASCII, true);
    ObjectNode node = mapper.getNodeFactory().objectNode();
    node.put("field1", "Maël Hörz");
    System.out.println(mapper.writeValueAsString(node));

The output is:
{"field1":"Ma\u00EBl H\u00F6rz"}

A: JsonGenerator is deprecated use JsonWriteFeature instead of it
 mapper.getFactory().configure(JsonWriteFeature.ESCAPE_NON_ASCII.mappedFeature(), true);


text:
Q: Manipulate system clipboard via bash script Is it possible to have a bash script put some text in the system clipboard?
(I use Ubuntu with default Gnome and Bash.)

A: There is a commandline tool xclip .
Example: Copy output of the following command to clipboard:
$ sort -n -k 3, -k 2 file.txt | xclip

Tutorial: http://www.cyberciti.biz/faq/xclip-linux-insert-files-command-output-intoclipboard/

A: I haven't tried it on my own, but there is a Bash Clipboard Interactive Script project on SourceForge: http://bics.sourceforge.net/


text:
Q: Align inline tikz nodes text with current line text (in table) I have this table, where the first column has inline tikz nodes. I would like the text of the nodes to be vertically aligned with the text of the table.
I found this question about his (among others), the problem is that I can't use baseline=(v1.base) to aline v1, because v1 does not know itself before being shown.
(I'm using pgfplotstable, but I don't think that changes anything)
MWE:
\documentclass[10pt,a4paper,twoside]{report}

\usepackage{geometry}
\geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}
\usepackage{setspace}
\setstretch{1.5}
\usepackage[table,pdftex]{xcolor}
%---------------------------------- tikz ---------------------------------------
\usepackage{tikz}
\usetikzlibrary{positioning,chains,fit,shapes,calc,arrows,patterns,external,shapes.callouts,graphs}
\tikzstyle{fancy}=[rectangle,rounded corners=1mm,thick,draw=white,ultra thin,
                   top color=white,bottom color=black!20,%
                   minimum height=.5cm,minimum width=.5cm,inner sep=2pt]

\usepackage{pgfplots}          % to print charts
\pgfplotsset{compat=1.9}

\usepackage{pgfplotstable}
\usepackage{booktabs,colortbl}
\usepackage{fixltx2e}

\begin{document}

\begin{table}
  \centering
  \caption{Parameters in blue.}
  \label{tab:1024groups1}
  \vspace{1em}

  \pgfplotstabletypeset[
  col sep=comma,
    columns/groups/.style={
        string type,
        column name=g.,},
    columns/vmin/.style={
%       string type,
        column name=$n)$,},
    columns/vmax/.style={
        column name=$(n$,},
    columns/density/.style={
        column name=$d$,},
    every head row/.style={
        after row=\midrule},
  every even row/.style={
    before row={\rowcolor{cyan!7}}},
  ]{
        groups,vmin,vmax,density
        \tikz[baseline=0] {\node[fancy] at (0,0) (v1){1};},2,1,1
        \tikz[baseline=0] {\node[fancy] at (0,0)(v2){2};},10,100,0
        \tikz[baseline=0] {\node[fancy] at (0,0)(v3){3};},10,25,0
        \tikz[baseline=0] {\node[fancy] at (0,0)(v4){4};},2,70000,0
        \tikz[baseline=0] {\node[fancy] at (0,0) (v1){1};},2,10,1
        \tikz[baseline=0] {\node[fancy] at (0,0)(v2){2};},100,10,0
        \tikz[baseline=0] {\node[fancy] at (0,0)(v3){3};},10,25,0
        \tikz[baseline=0] {\node[fancy] at (0,0)(v4){4};},200,7,0
      }

  \vspace{1em}

\end{table}
\end{document}

A: Anchor them to the base:
\documentclass[10pt,a4paper,twoside]{report}

\usepackage{geometry}
    \geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm}
\usepackage{setspace}
\setstretch{1.5}
\usepackage[table,pdftex]{xcolor}
%---------------------------------- tikz ---------------------------------------
\usepackage{tikz}
\usetikzlibrary{positioning,chains,fit,shapes,calc,arrows,patterns,external,shapes.callouts,graphs}
\tikzstyle{fancy}=[rectangle,rounded corners=1mm,thick,draw=white,ultra thin,
                   top color=white,bottom color=black!20,%
                   minimum height=.5cm,minimum width=.5cm,inner sep=2pt]

\usepackage{pgfplots}          % to print charts
\pgfplotsset{compat=1.9}

\usepackage{pgfplotstable}
\usepackage{booktabs,colortbl}
\usepackage{fixltx2e}

\begin{document}

\begin{table}
  \centering
  \caption{Parameters in blue.}
  \label{tab:1024groups1}
  \vspace{1em}

  \pgfplotstabletypeset[
  col sep=comma,
    columns/groups/.style={
        string type,
        column name=g.,},
    columns/vmin/.style={
%       string type,
        column name=$n)$,},
    columns/vmax/.style={
        column name=$(n$,},
    columns/density/.style={
        column name=$d$,},
    every head row/.style={
        after row=\midrule},
  every even row/.style={
    before row={\rowcolor{cyan!7}}},
  ]{
        groups,vmin,vmax,density
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0) (v1){1};},2,1,1
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v2){2};},10,100,0
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v3){3};},10,25,0
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v4){4};},2,70000,0
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0) (v1){1};},2,10,1
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v2){2};},100,10,0
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v3){3};},10,25,0
        \tikz[baseline=0] {\node[fancy,anchor=base] at (0,0)(v4){4};},200,7,0
      }

  \vspace{1em}

\end{table}
\end{document}


text:
Q: Pandas adding columns: TypeError: unhashable type: 'list' With the  code at the bottom of the post I am getting the below error message - any ideas how to solve or why this is happening? The source data already has "Date" and "Value" populated. Thanks!
Traceback (most recent call last):
  File "H:/Testing.py", line 12, in <module>
    df = df[['Form_ID', 'Date', 'Value']]
TypeError: unhashable type: 'list'

Code Used:
import pandas

path = r'H:/Hello.xlsx'

# read file into dataframe
df = pd.read_excel(path)

# add series
df['Form_ID'] = 'TESTID'

# order columns
df = df[['xl', 'Form_ID', 'Date', 'Value']]

# export dataframe
df.to_excel(path, index=False)

A: You can use reindex_axis, in your case:
df = df.reindex_axis(['xl', 'Form_ID', 'Date', 'Value'], axis=1)
that 1 is to tell Pandas to reindex the columns, not the indexes.


text:
Q: How to convert string array to string I have made a method which random the string array and print it out.
But now I need to use that method and assign it to a string to count the number of letters in the string.
I cant seem to find the answer anywhere.
Is there any way that I can do? Help me out. I m a beginner in programming.

A: You can use Arrays.toString() in combination with StringBuilder/StringBuffer to iterate over the array and keep on appending the array element to this string object .
EX:
StringBuilder stringBuilder = new StringBuilder();
   for(String string : array) {
   stringBuilder.append(string);
 }
 return stringBuilder.toString();

For counting the no. of letters you can use:
String input = userInput.toLowerCase();// Make your input lower case.
int[] alphabetArray = new int[26];
for ( int i = 0; i < input.length(); i++ ) {
     char ch=  input.charAt(i);
     int value = (int) ch;
     if (value >= 97 && value <= 122){
     alphabetArray[ch-'a']++;
    }
}

And for displaying the result:
 for (int i = 0; i < alphabetArray.length; i++) {
  if(alphabetArray[i]>0){
    char ch = (char) (i+97);
    System.out.println(ch +"  : "+alphabetArray[i]);   //Show the result.
  }
 }