_id
stringlengths
2
6
partition
stringclasses
3 values
text
stringlengths
4
46k
language
stringclasses
1 value
title
stringclasses
1 value
d15701
val
I haven't read all the details of the forum post you're referring to, but i'm sure you need to know a few things about data binding before you can start using it. * *The target of a data binding is a dependency property *A dependency property has to be declared in a class that is derived from DependencyObject (at least when it is not an attached property, but we don't talk about those here) *The SetBinding method you're looking for is either a static method in BindingOperations, or a method of FrameworkElement. So when you're going to set up a binding on some property of your DataRange class, it would have to be derived from DependencyObject, and you would set the binding like this: DataRange dataRange = ... Binding binding = ... BindingOperations.SetBinding(dataRange, DataRange.StartProperty, binding); If DataRange were derived from FrameworkElement, you could write this: dataRange.SetBinding(DataRange.StartProperty, binding); Here DataRange.StartProperty is of type DependencyProperty and represents the Start dependency property of class DataRange. You should at least read the MSDN articles Data Binding Overview, Dependency Properties Overview and Custom Dependency Properties.
unknown
d15702
val
date in PHP accepts 2 parameters. The first is the format you want the date to be displayed in, and the second is a unix timestamp. What you would be better of using is the DateTime class. Then you can get the timezone like this: echo (new \DateTime('2019-01-17T10:00:00-05:00'))->format('P');
unknown
d15703
val
If you already created the mask, you may be able to simplify the rest of it into one command like this... convert in.png in2.png in3.png null: ^ -matte mask.png -compose dstin -layers composite +append result.png That would read in the three input images and do the mask composite on each of them all at the same time. Then it appends the three results into a single file for the output. A: This will do what you ask in Imagemagick using parenthesis processing Unix syntax: convert \ \( in.png -matte mask.png -compose DstIn -composite \) \ \( in2.png -matte mask.png -compose DstIn -composite \) \ \( in1.png -matte mask.png -compose DstIn -composite \) \ -append result.png Windows syntax: convert ^ ( in.png -matte mask.png -compose DstIn -composite ) ^ ( in2.png -matte mask.png -compose DstIn -composite ) ^ ( in1.png -matte mask.png -compose DstIn -composite ) ^ -append result.png I note that you have in1.png in the third convert. Did you mean in3.png? Please always identify your Imagemagick version and platform/OS, since syntax differs. A: This may be of interest for those wanting to make rounded corners with Imagemagick. Unix syntax. Input: Imagemagick 6 Rounded Corners: convert thumbnail.gif \( +clone -alpha extract \ \( -size 15x15 xc:black -draw 'fill white circle 15,15 15,0' -write mpr:arc +delete \) \ \( mpr:arc \) -gravity northwest -composite \ \( mpr:arc -flip \) -gravity southwest -composite \ \( mpr:arc -flop \) -gravity northeast -composite \ \( mpr:arc -rotate 180 \) -gravity southeast -composite \) \ -alpha off -compose CopyOpacity -composite thumbnail_rounded.png Rounded Corners With Shadow: convert thumbnail.gif \( +clone -alpha extract \ \( -size 15x15 xc:black -draw 'fill white circle 15,15 15,0' -write mpr:arc +delete \) \ \( mpr:arc \) -gravity northwest -composite \ \( mpr:arc -flip \) -gravity southwest -composite \ \( mpr:arc -flop \) -gravity northeast -composite \ \( mpr:arc -rotate 180 \) -gravity southeast -composite \) \ -alpha off -compose CopyOpacity -composite -compose over \ \( +clone -background black -shadow 80x3+5+5 \) \ +swap -background none -layers merge thumbnail_rounded_shadow.png Imagemagick 7 Rounded Corners: magick thumbnail.gif \ \( +clone -fill black -colorize 100 -fill white -draw 'roundrectangle 0,0 %w,%h 15,15' \) \ -alpha off -compose CopyOpacity -composite thumbnail_rounded2.png Rounded Corners With Shadow: magick thumbnail.gif \ \( +clone -fill black -colorize 100 -fill white -draw 'roundrectangle 0,0 %w,%h 15,15' \) \ -alpha off -compose CopyOpacity -composite -compose over \ \( +clone -background black -shadow 80x3+5+5 \) \ +swap -background none -layers merge thumbnail_rounded_shadow2.png
unknown
d15704
val
You may use searchsortedlast with broadcasting: julia> x = [0.2, 6.4, 3.0, 1.6] 4-element Array{Float64,1}: 0.2 6.4 3.0 1.6 julia> bins = [0.0, 1.0, 2.5, 4.0, 10.0] 5-element Array{Float64,1}: 0.0 1.0 2.5 4.0 10.0 julia> searchsortedlast.(Ref(bins), x) 4-element Array{Int64,1}: 1 4 3 2
unknown
d15705
val
Query the created question object. As a side effect, you can test that the question was created. ... q = Question.query.filter_by(title='What about somestuff in Flask?').first() self.assertRedirects(response, '/questions/%d/' % q.id)
unknown
d15706
val
Alright, looks like I can use @Bindable in a Hibernate @Entity!! Misha
unknown
d15707
val
you can define a system varible when starting tomcat. and access it from your library. for example inside your catalina.bat(on windows)/setenv.sh(linux) windows set JAVA_OPTS=%JAVA_OPTS% -Dconfig.path=%CATALINA_HOME%/{path to conf file} linux JAVA_OPTS="$JAVA_OPTS -Dconfig.path=$CATALINA_HOME/{path to conf file}" then access it from your code System.getProperty("config.path")
unknown
d15708
val
I think what you're actually looking for is: @Html.ValidationSummary() A: I would go with @Html.ValidationSummary() if possible A: Check out Custom ValidationSummary template Asp.net MVC 3. I think it would be best for your situation if you had complete control over how the validation is rendered. You could easily write an extension method for ValidationMessageFor. A: Actually, at the top should be: @Html.ValidationSummary(/*...*/) The field validations should be with their respective fields. However, if you absolutely insist on putting @Html.ValidationMessageFor(/*...*/) at the top then adjust their layout behavior in your CSS and forget about the <br />'s A: I'm not sure if there's a built in way, but you could easily make another Extension method: public static MvcHtmlString ValidationMessageLineFor<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) { return helper.ValidationMessageFor(expression) + "<br />"; } Something like that?
unknown
d15709
val
You need minor tweaking in your code: change: bottom: TabBar( tabs: _tabs, ), ), body: TabBarView( children: _tabBarView, ), to bottom: TabBar( tabs: _tabs.toList(), // Creates a [List] containing the elements of this [Iterable]. ), ), body: TabBarView( children: _tabBarView.toList(), // Creates a [List] containing the elements of this [Iterable]. ),
unknown
d15710
val
See this example: var query = from p in Pets select p; if (OwnerID != null) query = query.Where(x => x.OwnerID == OwnerID); if (AnotherID != null) query = query.Where(x => x.AnotherID == AnotherID); if (TypeID != null) query = query.Where(x => x.TypeID == TypeID); Hope this help you
unknown
d15711
val
You can't; not with this data structure. You have a few options: * *iterate through everything, but abort this iteration at the top if it doesn't match your required state. For example: for (Card card : deck) { if (card.getRank() != Rank.ACE) continue; /* code to deal with aces here */ } *You use stream API constructs to filter. You did not include your Deck class in your paste, but assuming deck.deck is some sort of java.util.List, you can for example do: deck.deck.stream().filter(x -> x.getRank() == Rank.ACE).iterator() which will give you an iterator that iterates through only the aces. A: I just want to iterate through all the Spades or all the Kings. Here we are. new DeckIterator(deck, card -> Rank.KING.equals(card.getRank())); new DeckIterator(deck, card -> Suit.SPADES.equals(card.getSuit())); I fully agree with @rzwitserloot's answer, and will extend his post with my iterator which takes a Predicate to form another iterator that runs over only selected elements. class DeckIterator implements Iterator<Card> { private final Iterator<? extends Card> iterator; public DeckIterator(Deck deck, Predicate<Card> predicate) { iterator = deck.deck.stream().filter(predicate).iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Card next() { return iterator.next(); } @Override public void remove() { iterator.remove(); } }
unknown
d15712
val
I got the same crash log.And my reason is the view controller is released but the UITextField.delegate is not setting nil. So you can set UITextField.delegate = nil in dealloc of the view controller.
unknown
d15713
val
I managed to solve the issue myself. I still cannot fully explain cause and effect here, but this is what I did: I removed crossorigin="anonymous" from the html's img element. This will at least make sure that the image is always loaded. The color calculation part I solved by basically rewriting its logic: var imgSrc = $('#<?= $bigimage['image_id'] ?>').attr('src'); var cacheBurstPrefix = imgSrc.indexOf("?") > -1 ? '&' : '?'; imgSrc += cacheBurstPrefix + 'ts=' + new Date().getTime(); var imagePreloader = new Image(); imagePreloader.crossOrigin = "Anonymous"; imagePreloader.src = imgSrc; $(imagePreloader).imagesLoaded(function() { var rgb = getAverageRGB(imagePreloader); document.body.style.backgroundColor = 'rgb('+rgb.r+','+rgb.g+','+rgb.b+')'; if (rgb!==false) { $.get(basepath + "image/<?= $bigimage['image_id'] ?>/setcolor/" + rgb.r + "-" + rgb.g + "-" + rgb.b); } }); Instead of reusing the img element from the html, I'm creating a new in-memory image element. Using a cache bursting technique I'm making sure it is freshly loaded. Next, I'm using imagesLoaded (a 3rd party plugin) to detect the event of this in-memory image being loaded, which is far more reliable than jQuery's load() event. I've tested extensively and can confirm that in no case does normal image loading ever break again. It works in every browser and proxy situation. As an added bonus, the color calculation part now seems to work in far more browsers, including several mobile browsers. Although I am still not confident on the root cause, after much frustration I'm very happy with the new situation.
unknown
d15714
val
Try this, firstSpinner.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub string selectedValue = arg0.getSelectedItem().toString(); if(selectedValue.equalsIgnoreCase(string1) { ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, firstArray); secondSpinner.setAdapter(firstAdapter);// } else if(selectedValue.equalsIgnoreCase(string2) { ArrayAdapter<String> firstAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2); secondSpinner.setAdapter(firstAdapter); } } Hope it will help you. A: If it's a String array you could define it in XML then use getResource().getStringArray() or declare it in Java. In your listener for the first spinner, you could do the following to set the choices for the second spinner. secondSpinnerAdapter = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, newArray); secondSpinner.setAdapter(secondSpinnerAdapter); Tested and working A: update the array list of second spinner in 1st spinner setOnItemSelectedListener spinner1.setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) { // TODO Auto-generated method stub string str=spinner1.getSelectedItem().toString(); if(str.equals("spinner item"))//spinner item is selected item of spinner1 { ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array1); //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinner2.setAdapter(adapter1);// }else if{ ArrayAdapter<String>adapter1 = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, array2); //adapter1.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line); spinner2.setAdapter(adapter2); } }
unknown
d15715
val
Here's one SnmpSharpNet. More can be found here. A: I use SharpSnmpLib. It works very well for SNMPv2 and is pretty easy to understand
unknown
d15716
val
float((m_df.ix[:,1:1]).values) For pandas dataframes, type casting works when done on the values, rather than the dataframe.
unknown
d15717
val
You just setState in constructor. If you want to make a call you can put it in componentWillMount() or componentDidMount() import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } } citySearch(city){ this.setState({city}) } componentWillMount(){ //Axios call let city = this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); this.citySearch('London'); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={citySearch} /> </div> ); } } export default App; A: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the App component. This is because of your axios call inside the constructor. Put your axios call in componentDidMount should resolve it citySearch is not defined It is because React cannot find citySearch function. You should change <SearchBar onSearchTermChange={citySearch} /> to <SearchBar onSearchTermChange={this.citySearch} /> In order to use citySearch this way, you should also bind citySearch in your constructor In summary: import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this) } componentDidMount() { //Axios call let city = this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } citySearch(city){ this.setState({city}) } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={this.citySearch} /> </div> ); } } export default App; Don't call setState in your constructor, you can just initialize your state like your did. So the original setState in your constructor should be deleted. UPDATE To search again everytime you call citySearch. import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this) } componentDidMount() { axioSearch(); } axioSearch(city) { let city = city || this.state.city; let country = this.state.country; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } citySearch(city){ this.axioSearch(city); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={this.citySearch} /> </div> ); } } export default App; A: First, you should not make your axios calls in the constructor. The component is not yet mounted at this point. Do this in a componentDidMount to ensure that the component is already mounted. Secodly, you did not bind citySearch to the App class. So in the SearchBar component, it does not know that the citySearch Method should be called from the App class. It is advisable to do this binding in the App class constructor for optimization reasons. Lastly, I will advise you to write React in a more functional way leveraging state management frameworks like Redux or Flux The code below should work import React, { Component } from 'react'; import './App.css'; //Libraries import axios from 'axios'; //Components import SearchBar from './Components/search-bar'; class App extends Component { constructor(props){ super(props); this.state = { city: 'London', country: 'uk', temperature: 0, humidity: 0, pressure: 0 } this.citySearch = this.citySearch.bind(this); this.citySearch('London'); } citySearch(city){ this.setState({city}) } componentDidMount() { //Axios call let {city, country} = this.state; axios .get(`http://api.openweathermap.org/data/2.5/weather?APPID=${API_KEY}&q=${city},${country}`) .then(function(response) { this.setState({ city: response.data.name, country: response.data.name, temperature: response.data.main.temp, humidity: response.data.main.humidity, pressure: response.data.main.pressure }); }.bind(this)) .catch(function(error) { console.log(error); }); } render() { return ( <div className="container"> <h1 className="display-1 text-center">Weather App</h1> <SearchBar onSearchTermChange={citySearch} /> </div> ); } } export default App; For the searchBar component, you didn't bind onHandleChange in the SearchBar component. This will throw errors. You should do this in the searchBar constructor constructor() { ... this.onHandleChange = this.onHandleChange.bind(this) //Very important you do this } A: To pass data from child components to the parent component you have to use a callback method. Check this out. (About how to pass data from parent to child and child to parent). I know that I'm not touching your code here (I'm sorry), but if you're interested in a different approach this works. https://medium.com/@ruthmpardee/passing-data-between-react-components-103ad82ebd17
unknown
d15718
val
Try this var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList(); A: A simple approach is using Enumerable.GroupBy: var dups = list.GroupBy(s => s) .Where(g => g.Count() > 1) .Select(g => g.Key); A: List<string> list = new List<string>() { "a", "a", "b", "b", "r", "t" }; var dups = list.GroupBy(x => x) .Where(x => x.Count() > 1) .Select(x => x.Key) .ToList(); A: var list = new List<string> { "a", "a", "b", "b", "r", "t" }; var distinct = new HashSet<string>(); var duplicates = new HashSet<string>(); foreach (var s in list) if (!distinct.Add(s)) duplicates.Add(s); // distinct == { "a", "b", "r", "t" } // duplicates == { "a", "b" } A: var duplicates = list.GroupBy(s => s).SelectMany(g => g.Skip(1).Take(1)).ToList(); A: var duplicates = list.GroupBy(a => a).SelectMany(ab => ab.Skip(1).Take(1)).ToList(); It will be more efficient then the one using Where(g => g.Count() > 1) and will return only one element from every group.
unknown
d15719
val
Here is the entry from the manifest file from one of the VB6 apps I maintain: <assemblyIdentity name="name of application" processorArchitecture="X86" type="win32" version="a.b.c.d" /> ... <file name="tabctl32.ocx"> <typelib tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" version="1.1" flags="control,hasdiskimage" helpdir="" /> <comClass clsid="{BDC217C5-ED16-11CD-956C-0000C04E4C0A}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" progid="TabDlg.SSTab.1" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst"> <progid>TabDlg.SSTab</progid> </comClass> <comClass clsid="{942085FD-8AEE-465F-ADD7-5E7AA28F8C14}" tlbid="{BDC217C8-ED16-11CD-956C-0000C04E4C0A}" threadingModel="Apartment" miscStatus="" miscStatusContent="recomposeonresize,cantlinkinside,insideout,activatewhenvisible,simpleframe,setclientsitefirst" /> </file> generated from OCS version 6.1.98.39 using https://github.com/wqweto/UMMM using a INI configuration file line like so: File tabctl32.ocx This is somewhat different from the one in the question: * *Has a relative path to the file *Different list of classes *Various different attributes Hard to say without experimentation how important those differences might be. I highly recommend logging your program in Process Monitor and seeing what if any errors you get in the log. This is usually how I identify tricky manifest problems.
unknown
d15720
val
if you're using nuxt.js (which I suppose you do since you have the tag on your question), it's pretty easy, just add the following in your nuxt.config.js: vuetify: { defaultAssets: false, treeShake: true, icons: { iconfont: 'mdiSvg', // --> this should be enough // sideNote: you can also define custom values and have access to them // from your app and get rid of the imports in each component values: { plus: mdiPlus, // you have access to this like $vuetify.icons.values.plus from your component } } } for the values to work you just have to import the appropriate icon in the nuxt.config.js like: import { mdiPlus } from '@mdi/js' or if you don't like the custom values you can import the needed icons for each component in the component itself and use them there like: import { mdiPlus } from 'mdi/js' ... data() { return { plusIcon: mdiPlus } } A: What I ended up doing currently is to have all the svg in @mdi/svg package and use that as an img src. That way, I won't have to deal with dynamically importing it from @mdi/js and hoping for a treeshake.
unknown
d15721
val
you can download the missing file from the link below https://www.dropbox.com/s/au2irnctslcpjih/libz.dylib and paste it in your iOS Simulator folder. I hope it will work .
unknown
d15722
val
Docotic.Pdf library can be used for your task. Please see my answer for similar question. Disclaimer: I work for the company that develops Docotic.Pdf library. A: 1) Create your own PDF "parser": http://www.quick-pdf.com/pdf-specification.htm Probably could be minimal if you just need text data and not any of the formatting. 2) Find a library in your language of choice that can "natively" read .pdfs (tons of them out there). 3) use a pre-built tool (like pdf2text or pdfgrep): https://unix.stackexchange.com/questions/6704/grep-pdf-files A: If your requirement is to search a for a word and replace it, you can go for Aspose.pdf.Kit A: Poppler contains tools to extract text from a pdf document. Use it to search on documents. A: In Java and C#, you can do that with iText, if the pdf file is not locked. http://itextpdf.com/
unknown
d15723
val
GenPass.replace(GenPass[Pos],number) will replace every occurrence of the character at GenPass[Pos] with the value of number. You need to make sure you replace one character at a time. A: Create a list of all chars and a list with all nums, then just pick one by using list.pop(randint(0, len(list) - 1), you will always pick a different letter / number like this but you will also be limited to 10 digits (0-9) and 20-something letters.
unknown
d15724
val
Solution from @nik will work only for bash. For sh will work: before_script: - variableName=... - export wantedValue=$( eval echo \$$variableName ) A: We found a solution using indirect expansion (bash feature): before_script: - variableName=${GITLAB_USER_ID}_CI_K8S_PROJECT - export wantedValue=${!variableName} But we also recognised, that our setup was somehow stupid: It does not make sense to have multiple branches for each user and use prefixed variables, since this leads to problems such as the above and security concerns, since all variables are accessible to all users. It is way easier if each user forks the root project and simply creates a merge request for new features. This way there is no renaming/prefixing of variables or branches necessary at all. A: Something like this works (on 15.0.5-ee): variables: IMAGE_NAME: "test-$CI_PROJECT_NAME"
unknown
d15725
val
There is no convenient way to do this in Access without using code to iterate over the returned rows and build the string yourself. Here is some code that will help you do this: Public Function ListOf(sSQL As String, Optional sSeparator As String = ", ") As String Dim sResults As String Dim rs As DAO.Recordset Set rs = CurrentDb.OpenRecordset(sSQL) While Not rs.EOF If sResults = "" Then sResults = Nz(rs.Fields(0).Value, "???") Else sResults = sResults + sSeparator & Nz(rs.Fields(0).Value, "???") End If rs.MoveNext Wend ListOf = sResults End Function And here is how you can use it in an Access query: SELECT [CustomerNo], (ListOf('SELECT [UpdateDate] FROM StatusTbl WHERE CustomerNo = ' + CStr([CustomerNo]))) AS UpdateDates FROM StatusTbl Note that this only works if you're executing the query in Access, queries executed from (for instance) an ADO connection will not have access to the ListOf function. A: This comes up fairly often, here is a previous take: Combine rows / concatenate rows
unknown
d15726
val
Use the anyString() argument matcher: when(iplayer.capture(Mockito.anyString())).thenReturn(true);
unknown
d15727
val
Right now, the only way is via a global option, MvcOptions.AllowEmptyInputInBodyModelBinding. It defaults to false, so you just need to do: services.AddControllers(o => { o.AllowEmptyInputInBodyModelBinding = true; }); A: There is now an easier way (since 5.0-preview7) You can now achieve this per action method, by configuring a FromBodyAttribute property named EmptyBodyBehavior Demonstration: public IActionResult Post([FromBody(EmptyBodyBehavior = EmptyBodyBehavior.Allow)] MyModel model) Thanks to LouraQ's comment, which guided me towards the above answer on github A: I'm not sure about your final intention, but if you don't want to choose the content-type, you can pass an empty json string. At this time, the user is not empty, but the content of it's field's value is null, and the final result is the same. Maybe you You can try it. Here is the debug process with the postman:
unknown
d15728
val
Using dplyr, we can do this after converting the 'MES_ZOO' column to character class as the zoo class is not supported within the mutate (using dplyr_0.4.1.9000). We group by 'FILIAL_CODE', get the lead of columns MES_ZOO to DEVOLUCIONES using mutate_each, change the column names and left_join with the original dataset. df$MES_ZOO <- as.character(df$MES_ZOO) library(dplyr) df %>% group_by(FILIAL_CODE) %>% mutate_each(funs(lead), MES_ZOO:DEVOLUCIONES)%>% setNames(., c(names(.)[1:2], paste0('NEW_', nm1))) %>% left_join(df, .) Or we could use shift from the devel version of 'data.table' i.e. v1.9.5 (Instructions to install the devel version are here. We convert the 'data.frame' to 'data.table' (setDT(df)). Specify the columns to shift in the .SDcols, use shift with option type='lead' grouped by 'FILIAL_CODE'. Create new columns by assigning (:=) library(data.table)#v1.9.5+ nm1 <- colnames(df)[3:5] setDT(df)[, paste0("NEW_", nm1) :=shift(.SD, type='lead') , by = FILIAL_CODE, .SDcols = nm1] df # FILIAL_CODE UNIDADES MES_ZOO PRODUCTOSUNICOS DEVOLUCIONES NEW_MES_ZOO #1: 10 26394 Jan 2010 3592 39 Feb 2010 #2: 10 24314 Feb 2010 3337 22 Mar 2010 #3: 10 26280 Mar 2010 3459 12 Apr 2010 #4: 10 25056 Apr 2010 3256 24 May 2010 #5: 10 28827 May 2010 3355 26 Jun 2010 #6: 10 24781 Jun 2010 3196 31 <NA> # NEW_PRODUCTOSUNICOS NEW_DEVOLUCIONES #1: 3337 22 #2: 3459 12 #3: 3256 24 #4: 3355 26 #5: 3196 31 #6: NA NA
unknown
d15729
val
I really don't know why you said "I can't just change view frames". Of course you can! The approach I always take to this scenario (where your view's height is variable) is to declare a yOffset property and based on this I place my content at the right y position. @property (nonatomic, assign) int yOffset; Then inside the init method I initialize this property to either 0 or some predefined initial margin. _yOffset = TOP_MARGIN; Then consider the following scenario: a user profile with n number of skills. This is how you would use the yOffset property. for (int i=0; i<n; ++i) { // place the skillView at the right 'y' position SkillView *skillView = [[SkillView alloc] initWithFrame:CGRectMake(0,self.yOffset,300,50)]; // configure the skillView here [self.view addSubview:skillView]; // Don't forget it has to be "+=" because you have to keep track of the height!!! self.yOffset += skillView.frame.size.height + MARGIN_BETWEEN_SKILLS; } And then imagine the user profile has c number of Education entries; same thing: for (int i=0; i<c; ++i) { // place the educationView at the right 'y' position EducationView *educationView = [[EducationView alloc] initWithFrame:CGRectMake(0,self.yOffset,300,50)]; // configure the educationView here [self.view educationView]; // Don't forget it has to be "+=" because you have to keep track of the height!!! self.yOffset += educationView.frame.size.height + MARGIN_BETWEEN_EDUCATIONS; } Finally, when all your subviews have been added you have to change the frame of the containing view. (Because when you created it you couldn't know upfront how tall it was going to be) CGRect viewFrame = self.view.frame; viewFrame.size.height = self.yOffset + BOTTOM_MARGIN; self.view.frame = viewFrame; And that's it. Hope this helps! A: As you've stated, manually updating the frames is a lot of work and is the old way of doing things. The new better way as you've also said is to use auto layout. Describing how to use auto layout to position your views would require more specific information on how you want it to look but there are some awesome tutorials out there on the web! Here's one of many: Ray Wenderlich autolayout in iOS 7 part 1
unknown
d15730
val
Yes. You can do this pretty easily with Twisted. Just have one of the peers act like a server and the other one act like a client. In fact, the twisted tutorial will get you most of the way there. The only problem you're likely to run into is firewalls. Most people run their home machines behind SNAT routers, which make it tougher to connect directly to them from outside. You can get around it with port forwarding though. A: Yes, each computer (as long as their on the same network) can establish a server instance with inbound and outbound POST/GET. A: I think i am way too late in putting my two bits here, i accidentally stumbled upon here as i was also searching on similar lines. I think you can do this fairly easily using just sockets only, however as mentioned above one of the machines would have to act like a server, to whome the other will connect. I am not familiar with twisted, but i did achieved this using just sockets. But yes even i am curious to know how would you achieve peer2peer chat communication if there are multiple clients connected to a server. Creating a chat room kind of app is easy but i am having hard time in thinking how to handle peer to peer connections.
unknown
d15731
val
Your query is definitively far from being optimized. Try this instead: seismic2DSurvey.EndsAndBends = winPicsDbContext.Locations .Where(t => t.surveyId = seismic2DSurvey.Id && (t.IsBend || (t.IsEnd.HasValue && t.IsEnd.Value))).OrderBy(t => t.TraceNumber).ToList(); seismic2DSurvey.TraceCount = locations.Count(); seismic2DSurvey.SurveyLocations = null;
unknown
d15732
val
After reading the Quirksmode article on the subject, I realized that the problem was exactly what was being described there - the function was being referred instead of copied. From what I gathered, it's impossible to have inline JS work like I wanted for multiple instances on a single page. My solution was to extract the JS from the HTML tags and make it into functions. I used some jQuery to do so (because jQuery!). :p Here's the HTML: <input class="span1 hasDefaultValue" type="text" name="abc" value="25" placeholder="25"> And the JS: <script type="text/javascript"> function fieldFocus() { if (this.value==this.defaultValue) { this.value=''; } else { this.select(); } } function fieldBlur() { if (!this.value) { this.value=this.defaultValue; } } $(document).ready(function() { $("input.hasDefaultValue").click(fieldFocus); $("input.hasDefaultValue").blur(fieldBlur); }); </script> I'm sure that can be made more streamlined, but I wanted to post the answer ASAP. I might update with a streamlined solution later.
unknown
d15733
val
Ok, I'm finally done with it. I am a fool, really. In the Manifest.mf, section "Import-Package", don't forgot to add android.content It now works perfectly ;)
unknown
d15734
val
I ended up using inheritance to fix my issue. Although I have objects of many types, I created a "baseObject" class that contains the fields I needed for this to be successful. I was then able to use the following: for obj in objectStack{ let obj2 = obj as! baseObject fieldArrays[objectType]!.append(obj2.name.value) } I also used the solution here to use a dictionary to populate the correct array using the "didSet" event on the dictionary.
unknown
d15735
val
@addy.first.street should work, as it is list of Adress classes containing only one member. For displaying each street for more adresses in list: @addy.each do |address| puts address.street end or list_of_streets = @addy.map { |address| address.street } Edit: When you have problem identifying what class you have, always check object.class. When you just use object in IRB, then you see output from object.inspect, which doesn't have to show class name or even can spoof some informations. You can also call object.methods, object.public_methods. And remember that in Ruby some class is also an instance (of Class class). You can call @addr.methods to get instance methods and @addr.class.methods to get class methods. Edit2: In Rails #find can take as first parameter symbol, and if you pass :first of :last, then you'll get only one object. Same if you pass one integer (id of retrieved object). In other cases you get list as result, even if it contains only one object.
unknown
d15736
val
found a solution. The tricky bit was to get the bookmarklet to see inside an iframe! see this link: How to pick element inside iframe using document.getElementById so to manage the zoom in the iframe list this is the working example. In the link above I developed this further to make it a numbered list but the code is below: javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('.notifications-list--cMVsqVbKkaXV4SQ {zoom: 0.8!important;}'); style.appendChild(styleContent); var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head'); caput[0].appendChild(style); })(); to create a numbered list: javascript:(function(){ var style = document.createElement('style'), styleContent = document.createTextNode('ul.notifications-list--cMVsqVbKkaXV4SQ li {zoom: 1.0!important; counter-increment: my-counter !important; } ul.notifications-list--cMVsqVbKkaXV4SQ li::before { content: counter(my-counter) \". \" !important; color: red !important; font-weight: bold !important; margin-left: 10px}'); style.appendChild(styleContent); var caput = document.getElementById('xm-feed-iframe').contentWindow.document.getElementsByTagName('head'); caput[0].appendChild(style); })(); Just for awareness, I've tried to do this using TamperMonkey but struggled and gave up upon finding a bookmarklet option (see this thread: Use Tampermonkey to add or append a number to each line of a list). I will loop back to this thread though and see if I can get it working (with the aid of stackoverflow users!). resulting picture:
unknown
d15737
val
Don't set the src attribute until the user has clicked on that element. Here is an example: http://codepen.io/tevko/pen/raQMjP
unknown
d15738
val
Save yourself the trouble of using a regex where you don't need one and just use: name := url[strings.LastIndex(url, "/")+1:] Or if you are not sure that the url is a valid github url: i := strings.LastIndex(url, "/") if i != -1 { // Do some error handling here } name := url[i+1:] A: I am not that much familiar with golang till days. May be you can go with replace instead of split. For example using the following pseudocode. Make a regex .*/ and then replace it with your string. reg.ReplaceAllString(url, "") This will replace anything before the last / and you'll have the repo.git
unknown
d15739
val
You can use dryRun for this - or in UI just type SELECT * FROM mytable$20180701 and see in Validator how much bytes will be processed - this is the size of the table
unknown
d15740
val
The problem is that Typescript will infer config to be of type { headers: { 'X-Requested-With': string; 'Content-Type': string; 'Host-Header': string; }; responseType: string; } Typescript does not know that you are trying to create a config object for Axios. You can explicitly type the entire object as AxiosRequestConfig, or you could explicitly type responseType: 'json' to be of type ResponseType. const config: AxiosRequestConfig = { headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded', 'Host-Header': 'dsa', }, responseType: 'json' }; A: Fixed using explicit casting responseType: <ResponseType> 'json'
unknown
d15741
val
You're going to need to be more specific -- the way the question is now it's basically impossible to determine what you're after. Do you need to transfer a file from a Windows Mobile handheld to a Windows PC? Over what type of connection (are they on the same 802.11 network) ? You need more details or no one will be able to even attempt to help you. A: So, if what I gather is correct, you want to plug a device with your app on it into a PC and then be able to push files to the PC from the device without having to install anything over on the PC. Is that correct? If so, the next question is are you insane? It's not possible, and for very good reason. You don't see any potential security problems with being able to just plug a device into a PC and push files up to the PC without the user having to explicitly have installed something to receive that data? I could write a simple attack app that would fill up the PC's hard drive in about 5 minutes. A: A vanilla version of this is to just use the Active Sync synchronization folders. If you on the device save a file to the device synch folder, then Active Sync will move it over to the PC synch folder automatically.
unknown
d15742
val
Here's the code for automatic granting the SYSTEM_ALERT_WINDOW permission to the package. To run this code, your Android application must be system (signed by platform keys). This method is based on the following Android source code files: AppOpsManager.java and DrawOverlayDetails.java, see the method DrawOverlayDetails.setCanDrawOverlay(boolean newState). @TargetApi(Build.VERSION_CODES.KITKAT) public static void autoSetOverlayPermission(Context context, String packageName) { PackageManager packageManager = context.getPackageManager(); int uid = 0; try { ApplicationInfo applicationInfo = packageManager.getApplicationInfo(packageName, 0); uid = applicationInfo.uid; } catch (PackageManager.NameNotFoundException e) { e.printStackTrace(); return; } AppOpsManager appOpsManager = (AppOpsManager)context.getSystemService(Context.APP_OPS_SERVICE); final int OP_SYSTEM_ALERT_WINDOW = 24; try { Class clazz = AppOpsManager.class; Method method = clazz.getDeclaredMethod("setMode", int.class, int.class, String.class, int.class); method.invoke(appOpsManager, OP_SYSTEM_ALERT_WINDOW, uid, packageName, AppOpsManager.MODE_ALLOWED); Log.d(Const.LOG_TAG, "Overlay permission granted to " + packageName); } catch (Exception e) { Log.e(Const.LOG_TAG, Log.getStackTraceString(e)); } } } The code has been tested in Headwind MDM project, it successfully grants "Draw over other apps" permission without any user consent to the Headwind Remote application (disclaimer: I'm the project owner of Headwind MDM and Headwind Remote), when Headwind MDM application is signed by platform keys. The code has been tested on Android 10 (LineageOS 17). A: You can check and ask for overlay permission to draw over other apps using this if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 0); } A: if (!Settings.canDrawOverlays(this)) { Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION, Uri.parse("package:" + getPackageName())); startActivityForResult(intent, 0); } <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> A: Check this question and the answer: SYSTEM_ALERT_WINDOW - How to get this permission automatically on Android 6.0 and targetSdkVersion 23 "Every app that requests the SYSTEM_ALERT_WINDOW permission and that is installed through the Play Store (version 6.0.5 or higher is required), will have granted the permission automatically."
unknown
d15743
val
use regexp_extract(col, r"&q;Stockcode&q;:([^/$]*?),&q;.*") if applied to sample data in your question - output is
unknown
d15744
val
Get the list with document.querySelector('#list') and the first li by adding .querySelectorAll('li')[0], then find inputs inside. document.addEventListener('DOMContentLoaded', () => { document.querySelector('#delete').addEventListener("click", function deletes(){ let li = document.querySelector('#list').querySelectorAll('li')[0]; let inputs = li.querySelectorAll('input'); // Is there any input in li? if(inputs.length > 0) { // Delete only the first one inputs[0].remove(); // If you want to keep other inputs, just disable the button this.disabled = true; } }); }); <ul id="list"> <li> <input type="text" value="input1"> <input type="text" value="input2"> </li> </ul> <button id="delete">Delete</button> querySelector() and querySelectorAll() lets you find items by id, classname, tagname, attributes, etc. Just like jQuery does. Reference: https://developer.mozilla.org/en/docs/Web/API/Document/querySelector
unknown
d15745
val
Scipy's curve_fit() uses iterations to search for optimal parameters. If the number of iterations exceeds the default number of 800, but the optimal parameters are still not found, then this error will be raised. Optimal parameters not found: Number of calls to function has reached maxfev = 800 You can provide some initial guess parameters for curve_fit(), then try again. Or, you can increase the allowable iterations. Or do both! Here is an example: popt, pcov = curve_fit(exponenial_func, x, y, p0=[1,0,1], maxfev=5000) p0 is the guess maxfev is the max number of iterations You can also try setting bounds which will help the function find the solution. However, you cannot set bounds and a max_nfev at the same time. popt, pcov = curve_fit(exponenial_func, x, y, p0=[1,0,1], bounds=(1,3)) Source1: https://github.com/scipy/scipy/issues/6340 Source2: My own testing and finding that the about github is not 100% accurate Also, other recommendations about not using 0 as an 'x' value are great recommendations. Start your 'x' array with 1 to avoid divide by zero errors. A: Curve_fit() uses iterations to search for optimal parameters. If the number of iterations exceeds the set number of 1000, but the optimal parameters are still not available, then this error will be raised. You can provide some initial guess parameters for curve_fit(), then try again. A: Your original data is t1 and F1. Therefore curve_fit should be given t1 as its second argument, not t. popt, pcov = curve_fit(func, t1, F1, maxfev=1000) Now once you obtain fitted parameters, popt, you can evaluate func at the points in t to obtain a fitted curve: t = np.linspace(1, 3600 * 24 * 28, 13) plt.plot(t, func(t, *popt), label="Fitted Curve") (I removed zero from t (per StuGrey's answer) to avoid the Warning: divide by zero encountered in log.) import matplotlib.pyplot as plt import scipy.optimize as optimize import numpy as np # data F1 = np.array([ 735.0, 696.0, 690.0, 683.0, 680.0, 678.0, 679.0, 675.0, 671.0, 669.0, 668.0, 664.0, 664.0]) t1 = np.array([ 1, 90000.0, 178200.0, 421200.0, 505800.0, 592200.0, 768600.0, 1036800.0, 1371600.0, 1630800.0, 1715400.0, 2345400.0, 2409012.0]) plt.plot(t1, F1, 'ro', label="original data") # curvefit def func(t, a, b): return a + b * np.log(t) popt, pcov = optimize.curve_fit(func, t1, F1, maxfev=1000) t = np.linspace(1, 3600 * 24 * 28, 13) plt.plot(t, func(t, *popt), label="Fitted Curve") plt.legend(loc='upper left') plt.show() A: After fixing your import statements: #import matplotlib as mpl import matplotlib.pyplot as plt your code produced the following error: RuntimeWarning: divide by zero encountered in log changing: #t=np.linspace(0,3600*24*28,13) t=np.linspace(1,3600*24*28,13) produced the following output:
unknown
d15746
val
Make sure your database inside App_Data folder on your root application. and change the connection string to this one <add name="ConnectionStringName" providerName="System.Data.SqlServerCe.4.0" connectionString="Data Source=\KeywordsDB.sdf;Connection Timeout=30" /> things you need to concern is you are using SQL Server Compact, so the provider name need use System.Data.SqlServerCe.4.0 otherwise it will confused with SQL Server Client
unknown
d15747
val
Hope you want this. Thanks // handle links with @href started with '#' only $(document).on('click', 'a[href^="#"]', function(e) { // target element id var id = $(this).attr('href'); // target element var $id = $(id); if ($id.length === 0) { return; } // prevent standard hash navigation (avoid blinking in IE) e.preventDefault(); // top position relative to the document var pos = $(id).offset().top - 10; // animated top scrolling $('body, html').animate({scrollTop: pos}); }); .Home-section { height:500px; background: deepskyblue; } .About-section { height:300px; background:deeppink; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#home">Home</a> <a href="#about">About</a> <div class="Home-section" id="home"><h1> Hello </h1> </div> <div class="About-section" id="about"><h1>Bye</h1> </div> A: To get more like a parallax effect, you can add background-attachment: fixed; .About-section { height: 300px; background: url('http://lorempicsum.com/futurama/627/200/3') no-repeat; background-size: cover; background-attachment: fixed; } Like this Note : I use @sagar kodte JS code which works good for the animation. A: please try this .Home-section { height:500px; background: deepskyblue; } .About-section { height:300px; background:deeppink; } a{cursor:pointer} html code <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script> <script> $(document).ready(function(){ $("a").click(function() { var ourclass = $(this).attr('class'); $('html, body').animate({ scrollTop: $("#"+ourclass).offset().top-10 }, 2000); }); }); </script> <a class="home">Home</a> <a class="about">About</a> <div class="Home-section" id="home"><h1> Hello </h1></div> <div class="About-section" id="about"><h1>Bye</h1></div> and also js fiddlde here A: .Home-section { height: 500px; background: deepskyblue; } .About-section { height: 300px; background: deeppink; } <a href="#home">Home</a> <a href="#about">About</a> <div class="Home-section" id="home"> <h1> Hello </h1> </div> <div class="About-section" id="about"> <h1>Bye</h1> Try this.
unknown
d15748
val
This code saves the path to SQLScripts into %SQLSCRIPTSPATH% variable, and it works on WinXP: DIR SQLScripts /B /P /S>tmp.txt for /f "delims=" %%a in (tmp.txt) do set SQLSCRIPTSPATH=%%a del tmp.txt EDIT: Better solution (without using a temporary file) suggested by Joe: for /f "tokens=*" %%i in ('DIR SqlScripts /B /P /S') do SET SQLSCRIPTSPATH=%%i
unknown
d15749
val
You have to run the image with the -p option like: docker run -p 80:80 <image name> Expose is only working for internal docker image communication. -p then maps the host port to the container port: -p <host_port>:<container_port>
unknown
d15750
val
Ok... So just for information. Solution (workaround) is: When logging in (entering the password), select the cog and change from: Standard (Wayland display server) to Classic (X11 display server) then the last selected correct resolution will automatically be loaded. This option will also be remembered after reboot (Classic)
unknown
d15751
val
Actually, in OpenCV there is a specific way to do that. You can write an object in an XML file as follow: CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_WRITE); cvWrite(storage, "histogram", global_histogram); and read is as such: CvHistogram* global_histogram; CvFileStorage* storage = cvOpenFileStorage("globalHistogram.xml", 0, CV_STORAGE_READ); global_histogram = (CvHistogram *)cvReadByName(storage, 0, "histogram" ,0); A: The Boost Serialization library is pretty nice. It may do what you want. http://www.boost.org/doc/libs/1_49_0/libs/serialization/doc/index.html A: 1) Decide on a file format, plan it at the byte level (If an existing format is suitable, prefer it). 2) Write out the data in the file format you decided on. A: You can add a method to the class called Serialise, something along the lines of the following: CvHist::Serialise( std::string fName, bool read ) { if ( read ) { std::ifstream fStream( fName ); // Read in values from file, eg: fStream >> this->param1; fStream >> this->param2; // ...etc } else { std::ofstream fStream( fName, ios::trunc ); // (ios::trunc clears file) // Read out values into file, eg: fStream << this->param1; fStream << this->param2; // ...etc } } Note, the order is important - the order that you read the various parameters from the file must match the order you write parameters to the file. Also remember to #include <fstream> Now, to create a CvHist object populated with data from a file data.txt you can simply write this: CvHist object; object.Serialise( "data.txt", true ); If you've populated an object and want to store it in a file, this time, say, bob.dat, write this: // (object has been populated with data previously) object.Serialise( "bob.dat", false );
unknown
d15752
val
The issue is that you're using the actions-on-google library for fulfillment, which only creates results that are valid on the Google Assistant. If you want to send back a reply that is valid for other Dialogflow integrations, you will need to use the dialogflow-fulfillment library.
unknown
d15753
val
I have a quick guess that I'll try to flesh out if I get time today. I suspect that the Forms App was built expecting to need to find any custom ddm-type modules and display them in the UI for selection. The Structures JSP is probably not updated to automatically expect to need to to find new types. So, I'm going to guess that there's a JSP that you need to modify somewhere in a dynamic-data-mapping-*-web module. Once you find what you need to modify and where it is, you'll be able to do that with a JSP override fragment. see here: https://dev.liferay.com/develop/tutorials/-/knowledge_base/7-0/overriding-a-modules-jsps Hopefully that at least helps you direct your research into this matter.
unknown
d15754
val
You have 4 arguments in your render of which 2 is context. It needs only one dictionary with context or you can make a context dictionary variable and pass it as argument in render. Try this: from django.shortcuts import render, get_object_or_404 from CGI.models import tank_system, ambient def index(request): tank = tank_system.objects.all() room = ambient.objects.all() return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room}) OR from django.shortcuts import render, get_object_or_404 from CGI.models import tank_system, ambient def index(request): tank = tank_system.objects.all() room = ambient.objects.all() context = { 'tank': tank, 'room': room } return render(request, 'CGI/Pages/DashBoard.html',context) A: You can pass data using two different ways def index(request): tank = tank_system.objects.all() room = ambient.objects.all() return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank,'room': room}) or return render(request, 'CGI/Pages/DashBoard.html', locals()) locals() stands for get all local variable/objects and pass to the html as context A: In your index method, make changes as: def index(request): tank = tank_system.objects.all() room = ambient.objects.all() return render(request, 'CGI/Pages/DashBoard.html', {'tank': tank, 'room': room})
unknown
d15755
val
Try s.ToString().Replace(@"\""", "\""). The @ tells C# to interpret the string literally and not treat \ as an escape character. "\"" as the second argument uses \ as an escape character to escape the double quotes. You also don't need to call ToString() if s is already of type string. Last but not least, don't forget that string replacement is not done in place and will create a new string. If you want to preserve the value, you need to assign it to a variable: var newString = s.ToString().Replace(@"\""", "\""); // or s = s.Replace(@"\""", "\""); if "s" is already a string. A: Update if you have a string containing ", when you view this string in the Visual Studio immediate window it will display it as \". That does not mean that your string contains a backslash! To prove this to yourself, use Console.WriteLine to display the actual value of the string in a console, and you will see that the backslash is not there. Here's a screenshot showing the backslash in the immediate window when the string contains only a single quote. Original answer Three things: * *Strings are immutable. Replace doesn't mutate the string - it returns a new string. *Do you want to replace a quote "\"" or a backslash followed by a quote "\\\"". If you want the latter, it would be better to use a verbatim string literal so that you can write @"\""" instead. *You don't need to call ToString on a string. Try this: s = s.Replace(@"\""", "\""); See it on ideone. A: Ironically, you need to escape your quote marks and your backslash like so: s.ToString().Replace("\\\"", "\""); Otherwise it will cat your strings together and do the same as this (if you could actually use single quotes like this): s.ToString().Replace('"', ""); (your second string has four quotes... that's why you're not getting a compile error from having """)
unknown
d15756
val
You can achieve it using ngFor with index. Live example: https://stackblitz.com/edit/angular-b5qvwy Some code: Basic HTML <h1>{{list[i].name}}</h1> <div (click)="prev()"><</div> <div (click)="next()">></div> Basic TS code export class AppComponent { list = [ { name: "Jhon" }, { name: "Joe" }, { name: "Marth" } ]; i = 0; prev(){ if(this.i > 0){ this.i--; } } next(){ if(this.i < this.list.length -1){ this.i++; } } } For your example, simply do that in the html: <div class="container"> <div class="row"> <div class="col-12 text-center"> <h1 class="mt-5 mb-1"><strong>carousel</strong></h1> <div class="container"> <div class="row"> <div class="col-12"> <div class="carousel-container"> <div class="carousel-cell" *ngIf="carousel[i].id"> <div class="row text-center"> <div class="col-12"> <div class="row carousel-control"> <div class="col-2 carousel-prev fa-2x" (click)="carouselPrev()"> <fa-icon [icon]="faChevronLeft" class="mr-2"></fa-icon> </div> <div class="col-7 col-md-2"> <div class="carousel-image"> <img [src]="carousel[i].image" alt="carousel image"> </div> </div> <div class="col-2 carousel-next fa-2x" (click)="carouselNext()"> <fa-icon [icon]="faChevronRight" class="mr-2"></fa-icon> </div> </div> </div> <div class="col-12"> <div class="carousel-text mt-4"> <h3>{{carousel[i].description}}</h3> <p><em> {{carousel[i].name}}, <span>{{carousel[i].affiliation}}</span></em></p> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div> </div>
unknown
d15757
val
You should not run animation off of the UI thread ("main" thread) - you should load your content in another thread by using a Loader (or something similar) and play the animation on the UI thread. That's what it's for. Here are official thread guidelines: Do not block the UI thread Do not access the Android UI toolkit from outside the UI thread More here
unknown
d15758
val
Because your else case says: unique [] = [] unique (x:xs) = if (fst x) == (snd x) then unique (xs) else x:[] It thus says if fst x is not equal to snd x, then we return x : [] (or shorter [x]), and we are done. So it does not perform recursion on the rest of the list. We can solve this by adding recursion on the rest of the list, like: unique [] = [] unique (x:xs) = if fst x == snd x then unique xs else x : unique xs That being said, we can use a filter here, like: unique :: Eq a => [(a, a)] -> [(a, a)] unique = filter (\(x, y) -> x /= y) or even shorter: unique :: Eq a => [(a, a)] -> [(a, a)] unique = filter (uncurry (/=)) We thus retain all elements for which the first element x is not equal to the second element y.
unknown
d15759
val
Do: $(document).ready(function() { $("input[type='file']").blur(function(){ var path = $(this).val(); alert(path); $.ajax({ type: "GET", url: path, dataType: "xml", success: function(response) { parseXml(response); } }); }); }); function parseXml(xml) { //parse here }
unknown
d15760
val
Traffic is only routed within the cluster by default, so if the application on C is not part of the cluster, then ingress and egress won't be possible between the A/B nodes and C. This is all controlled by application's service configuration. To route ingress and egress traffic from/to outside the cluster, you'll need to configure the service of your application. One of the easier ways to do this is to use the type LoadBalancer service. You can also use the type NodePort service, which will expose the service on a mapped port in the range of 30000 - 32767 across all nodes. Lastly, you can assign an External IP to the service to allow outside traffic into the cluster. Hope this helps!
unknown
d15761
val
In your code: try with n=10000 and you'll see more of a difference (a factor of almost 10 on my machine). These things related with allocation are most noticeable when the size of your variable is large. In that case it's more difficult for Matlab to dynamically allocate memory for that variable. To reduce the number of operations: do it vectorized, and reuse intermediate results to avoid powers: y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20)); Benchmarking: With n=100: Parag's / venergiac's solution: >> tic for count = 1:100 y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2); end toc Elapsed time is 0.010769 seconds. My solution: >> tic for count = 1:100 y = (1 + x.*(-3/5 + x.*(3/20 - x/60))) ./ (1 + x.*(2/5 - x/20)); end toc Elapsed time is 0.006186 seconds. A: You don't need a for loop. Replace the for loop with the following and MATLAB will handle it. y=(1-(3/5)*x+(3/20)*x.^2 -(x.^3/60))./(1+(2/5)*x-(1/20)*x.^2); This may give a computational advantage when vectors become larger in size. Smaller size is the reason why you cannot see the effect of pre-allocation. Read this page for additional tips on how to improve the performance. Edit: I observed that at larger sizes, n>=10^6, I am getting a constant performance improvement when I try the following: x=0:1/n:1; instead of using linspace. At n=10^7, I gain 0.05 seconds (0.03 vs 0.08) by NOT using linspace. A: try operation element per element (.*, .^) clear y; n=50000; x=linspace(0,1,n); % no y pre-allocation using zeros start_time=tic; for k=1:n, y(k) = (1-(3/5)*x(k)+(3/20)*x(k)^2 -(x(k)^3/60)) / (1+(2/5)*x(k)-(1/20)*x(k)^2); end elapsed_time1 = toc(start_time); fprintf('Computational time for serialized solution: %f\n',elapsed_time1); start_time=tic; y = (1-(3/5)*x+(3/20)*x.^2 -(x.^3/60)) / (1+(2/5)*x-(1/20)*x.^2); elapsed_time1 = toc(start_time); fprintf('Computational time for product solution: %f\n',elapsed_time1); my data Computational time for serialized solution: 2.578290 Computational time for serialized solution: 0.010060
unknown
d15762
val
Ransack uses a predicate added on to the end of the field you're searching for to indicate how to search for it. If you have an attribute of :state on your model, you could search for states that match to 'expired' or 'deleted' using form.select :state_match, where the _match says to match records with state of whatever you selected. (Things like _cont (contains) or _start (starts with)). Ransack makes SQL queries to find records, so if you had an attribute on your model like :deleted_at you could search by presence or lack-of. It won't look at methods, just the information stored in the db. More predicates and info are here: https://github.com/activerecord-hackery/ransack/wiki/Basic-Searching
unknown
d15763
val
The Sinatra documentation on routes is pretty thorough. Assuming you're just trying to call a class method of Jobs::last, and that the method returns something stringifyable, then: get '/most-recent-job' do Jobs.last end should get it done. If that's insufficient for your use case, you'll have to expand your question to include code and output showing what Jobs.last is supposed to return, whatever errors you're getting from the route currently, and what you think the route's output ought to look like if you're expecting a MIME type other than text/plain.
unknown
d15764
val
You need to create the database and the sde login manually using e.g. pgAdmin, and grant the rds_superuser group role to the sde login. Also create a schema named sde in your database, and make the sde login the owner of that schema. Then you can create a .sde database connection in ArcCatalog using the sde login and, importantly, the *.rds.amazonaws.com hostname. Finally you can run the Enable Enterprise Geodatabase using this connection as your input. This only works if you connect to the database using the *.rds.amazonaws.com hostname. Apparently, ESRI uses the hostname to determine if the database in question is an RDS server. Once you've enabled the geodatabase you can connect to it with .sde connections using other dns aliases as well. Refer to the ESRI documentation for further details: http://server.arcgis.com/en/server/latest/cloud/amazon/create-geodatabase-in-amazon-rds-for-postgresql.htm
unknown
d15765
val
Is it even possible to set a Date object with a different timezone? No, it's not possible. As its javadoc describes, all the java.util.Date contains is just the epoch time which is always the amount of seconds relative to 1 january 1970 UTC/GMT. The Date doesn't contain other information. To format it using a timezone, use SimpleDateFormat#setTimeZone() A: getTime is an Unix time in seconds, it doesn't have the timezone, i.e. it's bound to UTC. You need to convert that time to the time zone you want e.b. by using DateFormat. import java.util.*; import java.text.*; public class TzPrb { public static void main(String[] args) { Date d = new Date(); System.out.println(d); DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("Australia/Sydney")); System.out.println(df.format(d)); df.setTimeZone(TimeZone.getTimeZone("Europe/London")); System.out.println(df.format(d)); } }
unknown
d15766
val
I took a look at the src and I see that the PhoneGap.exec calls in analytics.js does not match the plugin name. You have two ways to fix this. * *In plugins.xml make the plugin line: <plugin name="GoogleAnalyticsTracker" value="com.phonegap.plugins.analytics.GoogleAnalyticsTracker"/> *Or in analytics.js replace all instances of 'GoogleAnalyticsTracker' with 'Analytics' This is a bug in the way the code is setup in github. You should message the author to get them to fix it. A: Rather than using the PhoneGap plugin, I would recommend using the Google Analytics SDK for tracking usage of application developed using PhoneGap or any web based mobile app. Ensure that you respect your users privacy and dont send any other data to Google Analytics. Besides you should also adhere to Google Analytics privacy policy. Heres how to do it. http://www.the4thdimension.net/2011/11/using-google-analytics-with-html5-or.html
unknown
d15767
val
You forgot to wrap your React App within BrowserRouter or some router. Go to index.js in src folder. Wrap it like this. <BrowserRouter> <App /> </BrowserRouter> Then, add some Route. For example, like this. <BrowserRouter> <Routes> <Route element={<Home/>} path={"/"} /> <Route element={<Another />} path={"/another}/> </Routes> </BrowserRouter>
unknown
d15768
val
print(time_convert(time_lapsed)) Is your problem. The tine_convert method doesn't return anything. So by encapsulating the function in a print function it just prints none. Try returning a string in the end of your method like: Return "test"
unknown
d15769
val
You are not drawing your content relative to canvas but to screen which could result in a very different offset. If your canvas is lets say 200 pixels wide and high and your screen is 1920x1080 then half of that would draw the clock from center point 960, 540, ie. way outside the limits of the canvas of (here) 200x200. Instead of this: context.arc(screen.availWidth/2,screen.availHeight/2, hours_radius, 0, RADcurrentTime.hours); use something like this (assuming canvas is square size): context.arc(canvas.width/2, canvas.height/2,hours_radius,0,RADcurrentTime.hours); ^^^^^^^^^^^^ ^^^^^^^^^^^^^ You may also get some useful input from this answer.
unknown
d15770
val
You should create a different server handler for each item, with each one pointing to a different callback function.
unknown
d15771
val
Add two lines before tflite_model = converter.convert() in save_tflite() function like this converter.experimental_enable_resource_variables = True converter.experimental_new_converter = True tflite_model = converter.convert()
unknown
d15772
val
You can just try some javaScript to prevent the form submission if those fields fails to fulfill that condition. Please check my demo. **Note: It's just a demo. That's why didn't put any authentication. window.onload = function() { let submit = document.querySelector("#submit"); function validateAge(minAge, maxAge) { let min = parseInt(minAge, 10); let max = parseInt(maxAge, 10); return min >= max ? false : true; } function validateSkill(minSkill, maxSkill) { let min = parseInt(minSkill, 10); let max = parseInt(maxSkill, 10); return min >= max ? false : true; } submit.onclick = function() { let minAge = document.querySelector("#minage").value; let maxAge = document.querySelector("#maxage").value; let radios = document.querySelectorAll('input[type="radio"]:checked'); let minSkill = radios[0].value; let maxSkill = radios[1].value; if(validateAge(minAge, maxAge) && validateSkill(minSkill, maxSkill)) return true; else { alert("Invalid data"); return false; } } } <form id="myForm" action = "/events_success" method=post > Minimum Age:<br> <input type="text" name="minage" id="minage" required> <br> Maximum Age:<br> <input type="text" name="maxage" id="maxage" required> <br> Minimum Skill Level:<br> <input type = "radio" name = "minskill" value = "1" required> 1 <input type = "radio" name = "minskill" value = "2"> 2 <input type = "radio" name = "minskill" value = "3"> 3 <input type = "radio" name = "minskill" value = "4"> 4 <input type = "radio" name = "minskill" value = "5"> 5 <br> Maximum Skill Level:<br> <input type = "radio" name = "maxskill" value = "1" required> 1 <input type = "radio" name = "maxskill" value = "2"> 2 <input type = "radio" name = "maxskill" value = "3"> 3 <input type = "radio" name = "maxskill" value = "4"> 4 <input type = "radio" name = "maxskill" value = "5"> 5 <br> <br> <input type="submit" value="Send" id="submit"> </form> A: You can use some common PHP validation techniques. These are more beneficial as less risky to injection and other exploits. PHP: if (empty($_POST["code"])) { $errcode = "Verify that you're human"; } else { $code = test_input($_POST["code"]); if (!$_POST['code'] < $string) { $errcode = "Make code greater than string"; } } HTML: <p><label for="code">Scrambled code: </label><input type="text" name="code" id="code" /><span class="error"> * <?php echo $errcode;?></span></p>
unknown
d15773
val
Python 3 now exposes the methods to directly set the affinity >>> import os >>> os.sched_getaffinity(0) {0, 1, 2, 3} >>> os.sched_setaffinity(0, {1, 3}) >>> os.sched_getaffinity(0) {1, 3} >>> x = {i for i in range(10)} >>> x {0, 1, 2, 3, 4, 5, 6, 7, 8, 9} >>> os.sched_setaffinity(0, x) >>> os.sched_getaffinity(0) {0, 1, 2, 3} A: After some more googling I found the answer here. It turns out that certain Python modules (numpy, scipy, tables, pandas, skimage...) mess with core affinity on import. As far as I can tell, this problem seems to be specifically caused by them linking against multithreaded OpenBLAS libraries. A workaround is to reset the task affinity using os.system("taskset -p 0xff %d" % os.getpid()) With this line pasted in after the module imports, my example now runs on all cores: My experience so far has been that this doesn't seem to have any negative effect on numpy's performance, although this is probably machine- and task-specific . Update: There are also two ways to disable the CPU affinity-resetting behaviour of OpenBLAS itself. At run-time you can use the environment variable OPENBLAS_MAIN_FREE (or GOTOBLAS_MAIN_FREE), for example OPENBLAS_MAIN_FREE=1 python myscript.py Or alternatively, if you're compiling OpenBLAS from source you can permanently disable it at build-time by editing the Makefile.rule to contain the line NO_AFFINITY=1 A: This appears to be a common problem with Python on Ubuntu, and is not specific to joblib: * *Both multiprocessing.map and joblib use only 1 cpu after upgrade from Ubuntu 10.10 to 12.04 *Python multiprocessing utilizes only one core *multiprocessing.Pool processes locked to a single core I would suggest experimenting with CPU affinity (taskset).
unknown
d15774
val
The problem is that the OnCreateView() method of the fragment is called after the setTimer() is called. An easy way to solve this is to first call fragment.setTimerValue(value) when you create the fragment. void setTimerValue(int value){ this.timerValue = value; } Then at the end of OnCreateView() method do: OnCreateView(){ ... setTimer(timerValue); return rootView; }
unknown
d15775
val
Is your database set to use uft8_unicode_ci charset? A: Solved: I had to change the my.cnf file my MySQL [client] default-character-set=utf8 [mysql] default-character-set=utf8 [mysqld] collation-server = utf8_unicode_ci init-connect='SET NAMES utf8' character-set-server = utf8
unknown
d15776
val
You have the lot of inefficiences in code that is detracting from an issue at hand. Ex: jsonDump = json.dumps(jsonData) actualJson = json.loads(jsonDump) What is the point? To equal just as: actualJson = jsonData Or even: actualJson = jsonData.copy() Next: finalObject = {} finalObject['CompanyId'] = actualJson.get("CompanyId") This can be to: finalObject = {'CompanyId' : actualJson.get("CompanyId") } Then: if (i.get("period").get("instant")): But i.get if not there, is None, so I think for in case your error, then don't handle as such: if (i["period"].get("instant")): And then also: f"{property}" Specifically, here: mList.append({f"{property}": final[f"{property}"]}) But what is property? I think it's just a string: property So: mList.append({property: final[property]}) A: What I see from your data: We know that a dictionary does not have duplicate keys: I want to show with an example: d={} list_of_dict=[{1:'a',2:'b'},{1:'c'}] Now, when you apply update: for x in list_of_dict: d.update(x) Now, you will get: #{1: 'c', 2: 'b'} You see update() will override the the value of key 1 from 'a' to 'c'. This is what exactly happening in your code
unknown
d15777
val
var css_shake={ right: '225px', left: 'auto', position: 'fixed', bottom:'50px' } jQuery.fn.shake = function() { this.each(function(i) { jQuery(this).css(css_shake); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); }); return this; } A: You are using absolute left values for your animation rather than relative values. Try using this syntax: jQuery(this).animate({ left : '+=25px' }, 10).animate({ left : '-=25px' }, 10) ; currently you are bouncing the element around absolute position -25 to 25, and leaving it up against the left border.
unknown
d15778
val
From what I can see you are already converting it to a JSON with var obj = JSON.parse(cont1); So you already have a JSON, it's just that how you're printing it is wrong. To it with a comma instead of +. console.log('data as json', obj) The + is doing a string concatenation, and it's attempting to concatenate a string with an object A: After String concat it prints data as json [object object]. if you put , instead of + will print that object correctly. In the snippet, you can see the difference. var jsonstr = '{"id":4006,"mid":1,"cid":41,"wid":7138,"oid":null,"status":null,"options":null,"starttime":"2018-08-15T06:08:55.000Z","duration":null,"ordertotal":50,"counter":null,"closetime":null}'; console.log(JSON.parse(jsonstr)); console.log('data as json' , JSON.parse(jsonstr)); console.log('data as json' + JSON.parse(jsonstr)); A: console.log just the object; if you want log object and a string use , instead of + jsonString = '{"key1":"value1","key2":"value2"}' jsonObject = JSON.parse(jsonString) console.log(jsonObject) // logging just the object console.log('jsonObjectName' , jsonObject) // logging object with string console.log('jsonObject.key1 : ' + jsonObject.key1 ) // this may come handy with certain IE versions function parseJSON(resp){ if (typeof resp === 'string') resp = JSON.parse(resp); else resp = eval(resp); return resp; }
unknown
d15779
val
in your component personalInfoForm=new formGroup({ firstname:new FormControl('',[Validators.required]) }) your HTML <form [formGroup]="personalInfoForm" novalidate [ngClass]="{submitted: formSumitAttempt}"> <div class="row"> <div class="col-lg-6"> <label for="firstName" class="userID control-label">First Name</label> <input type="text" class="form-control" id="firstName" placeholder="Name" formControlName="firstName" required> <div *ngIf ="personalInfoForm.controls['firstname'].hasError('required')" class="alert alert-danger"> Name is required </div> </div></div>
unknown
d15780
val
I figured out the issue. You need to add <ion-overlay></ion-overlay> to your app.html. I saw that no where in the documentation.
unknown
d15781
val
Set navigationController?.navigationBar.isTranslucent = false. You can also achieve this by unchecking Translucent from storyboard. A: Change navigation bar to Opaque instead of Translucent. Swift self.navigationController?.navigationBar.isTranslucent = true Objective-C [[UINavigationBar appearance] setTranslucent:YES]; Please find in image. And if you are setting navigations background color then change navigation background color instead of tint color.
unknown
d15782
val
You can use the aggregate function MAX in having: select client.name from client inner join stayed on client.client_id = stayed.client_id inner join room on stayed.room_id= room.room_id Group by name having MAX(room.price) < 5000 A: I recommend not exists for this: select c.name from client c where not exists (select 1 from stayed s join room r on s.room_id = r.room_id where c.client_id = s.client_id and r.price >= 500 ); This is almost a directly translation of your question. Note: If you attempt inner joins for this, then you will miss clients who have stayed in no rooms at all. According to your question, you would miss these clients in the result set. A: This is another approach SELECT c.Name FROM client WHERE c.client_id NOT IN ( SELECT s.client_id FROM stayed s INNER JOIN room r ON s.room_id = r.room_id WHERE r.price > 5000)
unknown
d15783
val
If forgot to use the (SELECT ATTRIBUTES_DE_AT FROM DUAL) subquery inside the XMLTYPE... SELECT DISTINCT P.SKU, SUBSTR(X.ATTRIBUTENAME, 14, 3) ATTRIBUTECODE, X.ATTRIBUTEVALUE FROM PRODUCT@ISPSTAG2 P, XMLTABLE('/attrs/attr' PASSING XMLTYPE(REGEXP_REPLACE(**(SELECT ATTRIBUTES_DE_AT FROM DUAL)**, '<attr name="longDescription">.*?<\/attr>')) COLUMNS ATTRIBUTENAME VARCHAR2(50) PATH '@name', ATTRIBUTEVALUE VARCHAR2(4000) PATH '/string' ) X WHERE X.ATTRIBUTENAME LIKE 'Z_CA%' AND DN(DOMAINID) = 'AT' AND SKU NOT LIKE 'OFF_%' AND SKU NOT LIKE 'PDT%' AND (SELECT ATTRIBUTES_DE_AT FROM DUAL) IS NOT NULL; The thing I don't understand is that when don't use the subquery in the IS NOT NULL filter I have the the ORA-22992 error (using distant LOB), so why I have a different error not using the dual subquery, which is the same distant LOB ? Anyway for you for your time/help :)
unknown
d15784
val
You can't really do anything -- I guess Isilon's SMB implementation doesn't support certain things (that would've preserved timestamps). I simply added FlushFileBuffers() before SetFileInformationByHandle() and made sure there are no related race conditions in my code.
unknown
d15785
val
You can send invites between android and iOS. They are linked using the developer console (console.developers.google.com). Both the android app and the iOS app need to be in the same console project. If there is only one of each, then when sending across platforms it's unambiguous which to choose and you can just send an invite. The app invite service will send the proper short links(goo.gl/...) to install/launch the proper app per platform. If there are multiple instances of a iOS and/or Android apps in the console project, then the client ID must be sent with the invite using Api call setOtherPlatformsTargetApplication(...) so that app invite service knows which of the console apps should be selected. For same platform, i.e. android to android, the app selected will match the app that sent the invitation, so same platform is not ambiguous.
unknown
d15786
val
Perhaps "export option" instead of "export searchBar". A: Try this code: #!/bin/bash -x func() { echo " Choose 1 - Option 1 2 - Option 2 " echo -n " Enter selection: " read select case $select in 1 ) echo " Option 1 chosen" OPTION=one export OPTION ./genScript.sh ;; 2 ) echo " Option 2 chosen" OPTION=two export OPTION ./genScript.sh ;; esac } clear func #!/bin/bash func2() { if [ ${OPTION} == "one" ] ; then echo "Option one" else echo "Option two" fi } func2 and finally run the configScript.sh with this command: . ./configScript.sh from the shell. A: I wonder if you actually have a comment line before your shebang line: #! must be the first 2 characters in the file. I also wonder if you're actually executing these scripts with sh instead of bash. Change [ "$option" == "one" ] to [[ $option == "one" ]] Instead of exporting, the config script needs to store the value: declare -p OPTION > ~/.my_config And then the other script can do . ~/.my_config if [[ $OPTION == "one" ]]; ...
unknown
d15787
val
To get two types of access you either need to combine two containers... or reuse a library that combines containers for you. Boost.MultiIndex was invented for precisely this kind of needs. The basics page shows an example that has employees accessible by id (unique) and sorted by name (non-unique), which is pretty much what you are going for. The key extractors are perhaps not obvious. Supposing that your thread ressemble: class Thread { public: std::size_t id() const; std::size_t priority() const; ... }; You should be able to write: #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/const_mem_fun.hpp> #include <boost/multi_index/member.hpp> // define a multiply indexed set with indices by id and name typedef multi_index_container< Thread, indexed_by< ordered_unique< const_mem_fun<Thread, std::size_t, &Thread::id> >, ordered_non_unique< const_mem_fun<Thread, std::size_t, &Thread::priority> > > > ThreadContainer; Which defines a container of thread uniquely identified by their id() and sorted according to their priority(). I encourage you to play around with the various indexes. Also, if you provide friend access to your class or specific getters that return mutable references, then using mem_fun instead of const_mem_fun you will be able to update your objects in place (for example, change their priority). It's a very complete (if daunting) library. A: Best solution is possibly std::map,, providing you a key / value pair. In your scenario the key has the type of your _id and the value the type Thread (assuming this is the name of your class). By copying all values to a std::vector you can sort by _priority with std::sort and a predicate. A: An easy solution would be to keep the std::unordered_map to provide the key --> thread lookup, and then use a std::set to implement your priority queue.
unknown
d15788
val
Due to the \, make emits the recipe as a single line. This confuses the shell. Try this instead, using ; in place of the line terminator: for i in a.h b.h ; \ do \ echo $i ; \ cp $i somedir ; \ done
unknown
d15789
val
ratchet freak is right, it is a shallow copy. You can see the source to the dup function in dmd2/src/druntime/src/rt/lifetime.d. The function is called _adDupT. It is a pretty short function where the main work is a call to memcpy(). Above the function, you can see a representation of an array: struct { size_t length; void* ptr; } A jagged array would be an array of arrays, so the memory would look like [length0, ptr0, length1, ptr1, length2, ptr2....] Since memcpy over those pointers doesn't follow them, that means slice.dup is a shallow copy. This is generally true with anything that copies slices, it is always shallow copies unless you do something yourself. So struct A {char[] str; } A a, b; a = b; would also shallow copy, so assert(a.str is b.str). If you want to do a deep copy, the simplest way is to just loop over it: T[][] newArray; foreach(item; oldArray) newArray ~= item.dup; (you can also preallocat newArray.length = oldArray.length and assign with indexes if you want to speed it up a bit) A deep copy of a struct could be done with compile time reflection, though I prefer to write a clone method or something in there since it is a bit more clear. I'm not aware of a phobos function with this premade.
unknown
d15790
val
Your code will have bad performance if there will be many records in master detail table. Because you will have masterRecordCount * DetailRecordCount nested loop. So it will be better if you group and join in one query var calculatedlist = from I in _entities.Investments join IL in _entities.Investment_Line on I.ID equals IL.ParentID group IL by new { I.ID } into g select new { InvestmentID = g.Key, RefNo = g.Max(m => m.I.RefNo), UserID = g.Max(m => m.I.UserID) , InvestedAmount = g.Max(m => m.I.InvestedAmount) , TotalAmount = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount), Calculate = g.Max(m => m.I.InvestedAmount) + g.Max(m => m.I.ProfitAmount) - g.Sum(m => m.IL.Amount) };
unknown
d15791
val
At some point someone has changed your code from making a POST request to making a GET. GET puts all the data into the URL instead of putting it in the request body. URLs have a length limit. Go back to using POST and this problem will go away. Refer to the documentation for your HTTP client library to find out how to do this.
unknown
d15792
val
I think you just want conditional aggregation: select week, count(*) as total, sum(case when pp = 'T' then 1 else 0 end) as num_pp, sum(case when sen = 'T' then 1 else 0 end) as num_sen from t group by week; A: In powerquery, something like this let Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content], #"Added Custom" = Table.AddColumn(Source, "Total", each "1"), #"Unpivoted Other Columns" = Table.UnpivotOtherColumns(#"Added Custom", {"week"}, "Attribute", "Value"), #"Changed Type1" = Table.TransformColumnTypes(#"Unpivoted Other Columns",{{"Value", type text}}), #"Replaced Value" = Table.ReplaceValue(#"Changed Type1","T","1",Replacer.ReplaceText,{"Value"}), #"Replaced Value1" = Table.ReplaceValue(#"Replaced Value","F","0",Replacer.ReplaceText,{"Value"}), #"Changed Type" = Table.TransformColumnTypes(#"Replaced Value1",{{"Value", type number}}), #"Pivoted Column" = Table.Pivot(#"Changed Type", List.Distinct(#"Changed Type"[Attribute]), "Attribute", "Value", List.Sum) in #"Pivoted Column"
unknown
d15793
val
I would suggest in stead of adding the array list after you clear you instead do this @Override protected void publishResults(CharSequence constraint, FilterResults results) { filteredShoppingList = (ArrayList<ShoppingListModel>)filterResults.values; if (filterResults.count > 0) { notifyDataSetChanged(); } else { notifyDataSetInvalidated(); } }
unknown
d15794
val
The body has: min-height: 2000px; that's why there is extra space..
unknown
d15795
val
I'd like to generate the result like this: from collections import Counter age = [1,1,1,1,1,1,1,1,1,1.1,1.1,1.1,1.1,1.1,1.1,1.1,1.2,1.2,1.2] c = Counter(age) result = [[k]*v for k,v in c.items()] print(result) # Result would be: # [[1, 1, 1, 1, 1, 1, 1, 1, 1], [1.1, 1.1, 1.1, 1.1, 1.1, 1.1, 1.1], [1.2, 1.2, 1.2]] Line 3 means: * *Group the list according to the content of list, *the item of Counter result looks like a dict, the key is age, while the value is frequency of each age. Line 4 means: * *Iterate the item of Counter result, get the keys(k) and values(v) *Create list of same value by [k]*v
unknown
d15796
val
For caching data I would stick it in a file in IsolatedStorage. It is a little more work, but you can write a simple enough wrapper around it. It is conceivable that IsolatedStorageSettings.ApplicationSettings will one day be synced between devices using SkyDrive, this is the direction Microsoft are taking with Windows 8. So you should stick to using it for it's purpose which is application based settings.
unknown
d15797
val
Our friend @AngocA seems to check into SO often but hasn't been checking this dangling question even though he did something to close it. Let's at least put his answer in here so folk know it's CLOSED by user. :) Courtesy of tonight's Point Pimp. :-D "The problem was in another db2cmd session where there was an infinitive loop. This created a scenario when new db2cmd session blocked because the first session used the whole CPU. – AngocA"
unknown
d15798
val
-2 is getting converted to unsigned integer. This will be equal to UINT_MAX - 1, which is definitely greater than 2. Hence, the condition fails and -1 is printed.
unknown
d15799
val
just make vbo of points and then ... glVertexAttribPointer(.., 1, GL_FLOAT, GL_FALSE, 0, (void*)0); glDrawArrays(GL_POINTS,0,.. ); Use math you have to assign each. But it's not so easy. I think it can be done with deploy of second pair of shaders /vao. OpenGL multiple draw calls with unique shaders gives blank screen
unknown
d15800
val
I found I can eliminate this problem simply by calling myPropertyGrid.ExpandAll(TRUE) at the end of the code where I initialize the property grid (InitPropertyGrid() for me). This seems to force all the properties to expand.
unknown