qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
26,642,767
I am trying to insert some rows to a PRODUCT table and I get an ORA\_00913: too many values at first and third line, column 13 insert into PRODUCT (prod\_id, group\_id, prod\_name, price) values ('000004', '0000045666', 'lampaan', 95,15); insert into PRODUCT (prod\_id, group\_id, prod\_name, price) values ('000005', '0000045667', 'golvlampaan', 111,55); Could anyone help me? Thanks!!
2014/10/29
[ "https://Stackoverflow.com/questions/26642767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4062211/" ]
You want to place the last condition at the top. ``` //CHECK EACH ONE AND ADD IT TO THE APPROPRIATE BUCKET while (scoreFile >> score) { if (score < 0 || score > 200) bucket[8]++; else if (score <= 24) bucket[0]++; else if (score <= 49) bucket[1]++; else if (score <= 74) bucket[2]++; else if (score <= 99) bucket[3]++; else if (score <= 124) bucket[4]++; else if (score <= 149) bucket[5]++; else if (score <= 174) bucket[6]++; else if (score <= 200) bucket[7]++; scoreRow++; } ```
8,424,819
I'm deploying to a Debian 6 server, with Apache, Passenger, Ruby1.9.1 When I run "cap deploy" or "cap deploy:migrations" I get this error: ``` [out :: ip.address] Could not find multi_json-1.0.3 in any of the sources ** [out :: ip.address] Run `bundle install` to install missing gems. ** [out :: ip.address] command finished in 1037ms *** [deploy:update_code] rolling back * executing "rm -rf /var/www/releases/20111208004427; true" servers: ["ip.address"] [ip.address] executing command command finished in 489ms failed: "sh -c 'cd /var/www/releases/20111208004427 && /usr/bin/rake1.9.1 RAILS_ENV=production RAILS_GROUPS=assets assets:precompile'" on ip.address ``` Note the `run bundle install to install missing gems` and `failed sh -c ...` part. I already tried this `export PATH=/var/lib/gems/1.9.1/bin:${PATH}` and tried many other possible solutions but nothing seems to work. By the way, NO rvm.
2011/12/08
[ "https://Stackoverflow.com/questions/8424819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/912895/" ]
Make sure that your `config/deploy.rb` file is including Bundler's capistrano tasks with this line: ``` require 'bundler/capistrano' ``` This will tell it to run `bundle install` after updating your code, but before it runs other tasks like `rake assets:precompile`.
8,886,296
I have a Datagridview which I populate from a Dataset created from an XML file. This part works and I can get the entire contents of the Dataset to display in a datagrid. I have the added functionality to filter the datagridview based upon a date and sold flag. This also works OK as the datagridview updates as you cycle through the dates. However I need to do some calculations on the "filtered" datagridview. These calculations are need to convert various currencies into GBP. So after some research on the best way to do this I decided to loop through the visible datagridview and test each of the visible. This is the code I cam up with. Unfortunately when run it all the tests fail and it try to carry out the else clause which then fails with a "Input string was not in a correct format" Exception. However I do not think that is the issue as I put a watch on the Price and Currency values and they "Do not Exist in the current Context"...now im stuck and would appreciate some help. Perhaps im going about this wrong way... Thanks Harry ``` for (int i = 1; i < dataGridView1.Rows.Count; i++) { if (dataGridView1["currency", i].ToString() == "USD") { myCommission += double.Parse(dataGridView1["commission", i].ToString()) * (double.Parse(dataGridView1["price", i].ToString()) * UStoGB); } else if (dataGridView1["currency", i].ToString() == "EURO") { myCommission += double.Parse(dataGridView1["commission", i].ToString()) * (double.Parse(dataGridView1["price", i].ToString()) * EUtoGB); } else { myCommission += double.Parse(dataGridView1["commission", i].ToString()) * double.Parse(dataGridView1["price", i].ToString()); } } ```
2012/01/16
[ "https://Stackoverflow.com/questions/8886296", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1152667/" ]
`map.input.file` environment parameter has the file name which the mapper is processing. Get this value in the mapper and use this as the output key for the mapper and then all the k/v from a single file to go to one reducer. The code in the mapper. BTW, I am using the old MR API ``` @Override public void configure(JobConf conf) { this.conf = conf; } @Override. public void map(................) throws IOException { String filename = conf.get("map.input.file"); output.collect(new Text(filename), value); } ``` And use MultipleOutputFormat, this allows to write multiple output files for the job. The file names can be derived from the output keys and values.
1,039,031
HW Problem here, not sure where I'm messing up. Let $X$ be the amount won or lost in betting \$5 on red in roulette. Then $P(5) = \frac{18}{38}$ and $P(-5) = \frac{20}{38}$. If a gambler bets on red one hundred times, use the central limit theorem to estimate the probability that those wagers result in less than $50 in losses. So I calculated: $E(x) = 100\frac{18}{38} = \frac{900}{19}$ $var(x) = \frac{900}{19}\times\frac{20}{38} = \frac{9000}{361}$ $\sigma = \sqrt{\frac{9000}{361}} = 4.993...$ Then this is what I was thinking: $P(-\infty \leq x \lt 50) \rightarrow P(\frac{x - 50}{4.993} \lt 0)$ Which would give $\int\_{-\infty}^{0}{\left(\frac{1}{\sqrt{2\pi}}\right)\left(e^{\tfrac{-z^2}{2}}\right)}$ Which using the table should be $(0.0 - 3.09) = (.5 - .001) = .499$ However I know from the back of the book it should be $.6808$. So where am I going wrong? EDIT: I see from the comments and from one answer that I have my $E(x)$ wrong, but I'm still stuck on how to finish it out. I would normally go into my teacher's office hours for this, but due to Thanksgiving, there won't be any.
2014/11/26
[ "https://math.stackexchange.com/questions/1039031", "https://math.stackexchange.com", "https://math.stackexchange.com/users/180176/" ]
Using the position occupied by the terms $1000$ we can write the determinant in a nicer way $$\left| \begin{array}{ccc} 1 & 1000 & 2 & 3 &4\\ 5 & 6 &7&1000 &8\\ 1000&9&8&7&6\\ 5 & 4&3&2&1000\\ 1&2&1000&3&4\\ \end{array} \right|=-\left| \begin{array}{ccc} 1000 & 1 & 2 & 3 &4\\ 6 & 5 &7&1000 &8\\ 9& 1000&8&7&6\\ 4 & 5&3&2&1000\\ 2&1&1000&3&4\\ \end{array} \right|\\=\left| \begin{array}{ccc} 1000 & 3 & 2 & 3 &4\\ 6 & 1000 &7&5 &8\\ 9& 7 &8&1000&6\\ 4 & 2&3&5&1000\\ 2&3&1000&1&4\\ \end{array} \right|=-\left| \begin{array}{ccc} 1000 & 3 & 3 & 2 &4\\ 6 & 1000 &5&7 &8\\ 9& 7 &1000&8&6\\ 4 & 2&5&3&1000\\ 2&3&1&1000&4\\ \end{array} \right|\\=\left| \begin{array}{ccc} 1000 & 3 & 3 & 4 &2\\ 6 & 1000 &5&8 &7\\ 9& 7 &1000&6&8\\ 4 & 2&5&1000&3\\ 2&3&1&4&1000\\ \end{array} \right|=10^{15}+x.$$ Now, having in mind that in a determinant of a matrix of order $5$ there are $120$ terms and one of them is $10^{15}$ we can bound $x.$ Indeed, we have that $$x>-119 \cdot 1000^3\cdot 9\cdot 8= -8568\cdot 10^9.$$ So, $$10^{15}+x>10^{15}-8568\cdot 10^9>0.$$
29,914,585
Using Jquery How can I select an option by either its value or text in 1 statement? ``` <select> <option value="0">One</option> <option value="1">Two</option> </select> ``` I can do these 2 statements individually but how can I combine the following 2 statements into 1 select OR statement? ``` $('select option[text="Two"]'); //This selects by text $('select option[value="4"]'); //This selects by value ```
2015/04/28
[ "https://Stackoverflow.com/questions/29914585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3658423/" ]
The simplest way is: ``` import React, { Component } from 'react'; import { Dimensions, View, Text } from 'react-native'; export default class Home extends Component { constructor(props) { super(props); this.state = { width: Dimensions.get('window').width, height: Dimensions.get('window').height, } this.onLayout = this.onLayout.bind(this); } onLayout(e) { this.setState({ width: Dimensions.get('window').width, height: Dimensions.get('window').height, }); } render() { return( <View onLayout={this.onLayout} style={{width: this.state.width}} > <Text>Layout width: {this.state.width}</Text> </View> ); } } ```
4,185,231
I had to extract the 2nd parameter (array) from an onclick attribute on an image, but jQuery just returned a function onclick and not its string value as expected. So I had to use a native method. A quick search says it **may** work some browsers like FF, but not IE. I use Chrome. ``` <img src="path/pic.png" onclick="funcName(123456,[12,34,56,78,890]);" /> ``` I thought this would work, but **it does not**: ``` var div = $('div_id'); var onclick_string = $(div).find('img').eq(0).attr('onclick'); var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit) ``` **This works** ``` var div = $('div_id'); var onclick_string = $(div).find('img')[0].getAttributeNode('onclick').value; var onclick_part = $(onclick_string).match(/funcName\([0-9]+,(\[.*\])/)[1]; // for some reason \d doesnt work (digit) ``` Is there another way of getting the 2nd parameter ?
2010/11/15
[ "https://Stackoverflow.com/questions/4185231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52025/" ]
Why not store it in the data property? ``` <img src="path/pic.png" onclick="funcName(123456);" data-mydata='12,34,56,78,890' /> var div_data = $('div_id').data('mydata').split(','); ```
39,443,875
Is there a way to create/define a variable available to all php files(like superglobals) > > Example: > > > i define a variable in **file1.php** `$car = ferrari` > > > then in **file2.php** i write `echo $car;` > > > then it will output `ferrari` > > > how can i define a variable in file1.php and access it in file2.php **EDIT:** The answers is good, but do is there another alternative?because i will have multiple php files in multiple directories, do i have to create its own php file for each directory?if thats the only way, then i'll do it.
2016/09/12
[ "https://Stackoverflow.com/questions/39443875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4619900/" ]
* create init.php in your project's root directory. If you need constant variable (so, you can't edit it) - create constants.php in your project's root dir. If you need editable variable - create globals.php in your project's root dir. **constants.php** ``` <?php define('CAR', 'ferrari'); ``` **globals.php** ``` <?php class Globals { public static $car = 'ferrari'; } ``` include **constants.php** and **globals.php** to **init.php**. ``` <?php require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'constants.php'); require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'globals.php'); ``` include **init.php** to php sources. ``` <?php require_once(dirname(__FILE__).DIRECTORY_SEPARATOR.'init.php'); ``` If you need variable for long use, not only one pageload, then use session. (user logins, settings, ...) ``` <?php $_SESSION['car'] = 'ferrari'; ``` In your php sources, you can use constant and global variables: Example: ``` <?php echo CAR; //ferrari echo Globals::$car; //ferrari Globals::$car = 'renault'; //set your global variable echo Globals::$car; //renault ``` **Refs:** > > <http://php.net/manual/en/language.oop5.static.php> > > > <http://php.net/manual/en/function.define.php> > > > <http://php.net/manual/en/function.dirname.php> > > > <http://php.net/manual/en/reserved.variables.session.php> > > >
1,947,650
Find all positive integers $x,y$ such that $7^{x}-3^{y}=4$. It is the problem I think it can be solve using theory of congruency. But I can't process somebody please help me . Thank you
2016/09/30
[ "https://math.stackexchange.com/questions/1947650", "https://math.stackexchange.com", "https://math.stackexchange.com/users/342519/" ]
Let us go down the rabbit hole. Assume that there is a solution with $ x, y > 1 $, and rearrange to find $$ 7(7^{x-1} - 1) = 3(3^{y-1} - 1) $$ Note that $ 7^{x-1} - 1 $ is divisible by $ 3 $ exactly once (since $ x > 1 $): the contradiction will arise from this. Reducing modulo $ 7 $ we find that $ 3^{y-1} \equiv 1 $, and since the order of $ 3 $ modulo $ 7 $ is $ 6 $, we find that $ y-1 $ is divisible by $ 6 $, hence $ 3^{y-1} - 1 $ is divisible by $ 3^6 - 1 = 2^3 \times 7 \times 13 $. Now, reducing modulo $ 13 $ we find that $ 7^{x-1} \equiv 1 $, and since the order of $ 7 $ modulo $ 13 $ is $ 12 $, we find that $ x-1 $ is divisible by $ 12 $. As above, this implies that $ 7^{x-1} - 1 $ is divisible by $ 7^{12} - 1 $, which is divisible by $ 9 $. This is the desired contradiction, hence there are no solutions with $ x, y > 1 $. For an outline of the method I used here, see [Will Jagy](https://math.stackexchange.com/users/10400/will-jagy)'s answers to [this related question](https://math.stackexchange.com/questions/1941354/elementary-solution-of-exponential-diophantine-equation-2x-3y-7/).
55,114,017
I have a page with print button which prints a table. Now in Chrome or IE it works fine but in Firefox it does not show the table headers. Here are some screenshots of Chrome and Firefox. In Firefox: ![In Firefox](https://i.stack.imgur.com/VBUxh.png) In Chrome: ![In Chrome](https://i.stack.imgur.com/JgplS.png)
2019/03/12
[ "https://Stackoverflow.com/questions/55114017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4898967/" ]
try using AUTO or IDENTITY policy. like: ``` @GeneratedValue(strategy = GenerationType.IDENTITY) ```
8,036,691
This is just a question out of curiosity but I am looking at a database and pulling data from a table with a query on one of the columns. The column has four possible values `null`, `0`, `1`, `2`. When I run the query as: ``` SELECT * FROM STATUS WHERE STATE != '1' AND STATE != '2'; ``` I get the same results as running: ``` SELECT * FROM STATUS WHERE STATE = '0'; ``` I.e. rows with a null value in the top command in the queried column seem to be omitted from the results, does this always happen in SQL? I'm running my commands through Oracle SQL Developer.
2011/11/07
[ "https://Stackoverflow.com/questions/8036691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/982475/" ]
In several languages NULL is handled differently: Most people know about two-valued logic where `true` and `false` are the only comparable values in boolean expressions (even is false is defined as 0 and true as anything else). In Standard SQL you have to think about [three-valued logic](http://en.wikipedia.org/wiki/Three-valued_logic). NULL is not treated as a real value, you could rather call it "unknown". So if the value is unknown it is not clear if in your case `state` is 0, 1, or anything else. So `NULL != 1` results to `NULL` again. This concludes that whereever you filter something that may be NULL, you have to treat NULL values by yourself. Note that the syntax is different as well: NULL values can only be compare with `x IS NULL` instead of `x = NULL`. See Wikipedia for a truth table showing the results of logic operations.
36,259,849
I am using ViewPager to hold my Fragments. I have two Fragments with different Parse Queries. One of My Fragment has grid view layout. I have created and Adapter for the GridView to load images. This is my fragment ``` public class FeedsFragment extends Fragment { GridView gridview; List<ParseObject> ob; FeedsGridAdapter adapter; private List<ParseFeeds> phonearraylist = null; View rootView; public static final String TAG = FeedsFragment.class.getSimpleName(); @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { rootView = inflater.inflate(R.layout.feeds_layout, container, false); new RemoteDataTask().execute(); return rootView; } private class RemoteDataTask extends AsyncTask<Void,Void,Void> { @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected Void doInBackground(Void... params) { // Create the array phonearraylist = new ArrayList<ParseFeeds>(); try { // Locate the class table named "SamsungPhones" in Parse.com ParseQuery<ParseObject> query = new ParseQuery<ParseObject>( "AroundMe"); // Locate the column named "position" in Parse.com and order list // by ascending // query.whereEqualTo(ParseConstants.KEY_RECIPIENT_IDS, ParseUser.getCurrentUser().getUsername()); query.orderByAscending("createdAt"); ob = query.find(); for (ParseObject country : ob) { ParseFile image = (ParseFile) country.get("videoThumbs"); ParseFeeds map = new ParseFeeds(); map.setPhone(image.getUrl()); phonearraylist.add(map); } } catch (ParseException e) { Log.e("Error", e.getMessage()); e.printStackTrace(); } return null; } @Override protected void onPostExecute(Void result) { // Locate the gridview in gridview_main.xml gridview = (GridView) rootView.findViewById(R.id.gridview); // Pass the results into ListViewAdapter.java adapter = new FeedsGridAdapter(FeedsFragment.this.getActivity(), phonearraylist); // Binds the Adapter to the ListView gridview.setAdapter(adapter); } } } ``` The Adapter I created to load the images into ``` public static final String TAG = FeedsGridAdapter.class.getSimpleName(); // Declare Variables Context context; LayoutInflater inflater; ImageLoader imageLoader; private List<ParseFeeds> phonearraylist = null; private ArrayList<ParseFeeds> arraylist; public FeedsGridAdapter(Context context, List<ParseFeeds> phonearraylist) { this.context = context; this.phonearraylist = phonearraylist; inflater = LayoutInflater.from(context); this.arraylist = new ArrayList<ParseFeeds>(); this.arraylist.addAll(phonearraylist); imageLoader = new ImageLoader(context); } public class ViewHolder { ImageView phone; } @Override public int getCount() { return phonearraylist.size(); } @Override public Object getItem(int position) { return phonearraylist.get(position); } @Override public long getItemId(int position) { return position; } public View getView(final int position, View view, ViewGroup parent) { final ViewHolder holder; if (view == null) { holder = new ViewHolder(); view = inflater.inflate(R.layout.feeds_layout, null); // Locate the ImageView in gridview_item.xml holder.phone = (ImageView) view.findViewById(R.id.videoThumb); view.setTag(holder); } else { holder = (ViewHolder) view.getTag(); } // Load image into GridView imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone); // Capture GridView item click view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View arg0) { // Send single item click data to SingleItemView Class Intent intent = new Intent(context, SingleVideoView.class); // Pass all data phone intent.putExtra("phone", phonearraylist.get(position) .getPhone()); context.startActivity(intent); } }); return view; } } ``` **Here its giving me NullPointerException on imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);** When I run the same code in another project with only one Fragment its working but when I use it in my current project with Two Fargments having different parse queries it gives me NullPointerException.Please help I wasted around 5 days on this to get it working tried everything possible at my end. Here is my ImageLoader Class ``` MemoryCache memoryCache = new MemoryCache(); FileCache fileCache; private Map<ImageView, String> imageViews = Collections .synchronizedMap(new WeakHashMap<ImageView, String>()); ExecutorService executorService; // Handler to display images in UI thread Handler handler = new Handler(); public ImageLoader(Context context) { fileCache = new FileCache(context); executorService = Executors.newFixedThreadPool(5); } // int stub_id = ; public void DisplayImage(String url, ImageView imageView) { imageViews.put(imageView, url); Bitmap bitmap = memoryCache.get(url); if (bitmap != null) imageView.setImageBitmap(bitmap); else { queuePhoto(url, imageView); imageView.setImageResource(R.drawable.camera_iris); } } private void queuePhoto(String url, ImageView imageView) { PhotoToLoad p = new PhotoToLoad(url, imageView); executorService.submit(new PhotosLoader(p)); } private Bitmap getBitmap(String url) { File f = fileCache.getFile(url); Bitmap b = decodeFile(f); if (b != null) return b; // Download Images from the Internet try { Bitmap bitmap = null; URL imageUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) imageUrl .openConnection(); conn.setConnectTimeout(30000); conn.setReadTimeout(30000); conn.setInstanceFollowRedirects(true); InputStream is = conn.getInputStream(); OutputStream os = new FileOutputStream(f); Utils.CopyStream(is, os); os.close(); conn.disconnect(); bitmap = decodeFile(f); return bitmap; } catch (Throwable ex) { ex.printStackTrace(); if (ex instanceof OutOfMemoryError) memoryCache.clear(); return null; } } // Decodes image and scales it to reduce memory consumption private Bitmap decodeFile(File f) { try { // Decode image size BitmapFactory.Options o = new BitmapFactory.Options(); o.inJustDecodeBounds = true; FileInputStream stream1 = new FileInputStream(f); BitmapFactory.decodeStream(stream1, null, o); stream1.close(); // Find the correct scale value. It should be the power of 2. final int REQUIRED_SIZE = 100; int width_tmp = o.outWidth, height_tmp = o.outHeight; int scale = 1; while (true) { if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE) break; width_tmp /= 2; height_tmp /= 2; scale *= 2; } // Decode with inSampleSize BitmapFactory.Options o2 = new BitmapFactory.Options(); o2.inSampleSize = scale; FileInputStream stream2 = new FileInputStream(f); Bitmap bitmap = BitmapFactory.decodeStream(stream2, null, o2); stream2.close(); return bitmap; } catch (FileNotFoundException e) { } catch (IOException e) { e.printStackTrace(); } return null; } // Task for the queue private class PhotoToLoad { public String url; public ImageView imageView; public PhotoToLoad(String u, ImageView i) { url = u; imageView = i; } } class PhotosLoader implements Runnable { PhotoToLoad photoToLoad; PhotosLoader(PhotoToLoad photoToLoad) { this.photoToLoad = photoToLoad; } @Override public void run() { try { if (imageViewReused(photoToLoad)) return; Bitmap bmp = getBitmap(photoToLoad.url); memoryCache.put(photoToLoad.url, bmp); if (imageViewReused(photoToLoad)) return; BitmapDisplayer bd = new BitmapDisplayer(bmp, photoToLoad); handler.post(bd); } catch (Throwable th) { th.printStackTrace(); } } } boolean imageViewReused(PhotoToLoad photoToLoad) { String tag = imageViews.get(photoToLoad.imageView); if (tag == null || !tag.equals(photoToLoad.url)) return true; return false; } // Used to display bitmap in the UI thread class BitmapDisplayer implements Runnable { Bitmap bitmap; PhotoToLoad photoToLoad; public BitmapDisplayer(Bitmap b, PhotoToLoad p) { bitmap = b; photoToLoad = p; } public void run() { if (imageViewReused(photoToLoad)) return; if (bitmap != null) photoToLoad.imageView.setImageBitmap(bitmap); else photoToLoad.imageView.setImageResource(R.drawable.camera_iris); } } public void clearCache() { memoryCache.clear(); fileCache.clear(); } } ```
2016/03/28
[ "https://Stackoverflow.com/questions/36259849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5958776/" ]
There is a NullPointerException `imageLoader.DisplayImage(phonearraylist.get(position).getPhone(), holder.phone);` Which leads to a suspiciously null `(ImageView) holder.phone`. **Why it must be null ?** Because it might not be lying inside the view you inflated to. **So** You should check if you are inflating a proper layout from resource and not making any of the most common mistakes like using activity/fragment's layout resource instead of using adapter's item layout. You're welcome.
33,549,067
I have successfully converted event to method (for use in ViewModel) using **EventTriggerBehavior** and **CallMethodAction** as shown in the following example (here picked a Page **Loaded** event for illustration). `<i:Interaction.Behaviors> <core:EventTriggerBehavior EventName="Loaded"> <core:CallMethodAction TargetObject="{Binding Mode=OneWay}" MethodName="PageLoadedCommand"/> </core:EventTriggerBehavior> </i:Interaction.Behaviors>` However, no success when it comes to the **CurrentStateChanged** event of **VisualStateGroup** as shown below (yes, nested within the `<VisualStateGroup>` block as **CurrentStateChanged** event belongs to **VisualStateGroup**): `<i:Interaction.Behaviors> <core:EventTriggerBehavior EventName="CurrentStateChanged"> <core:CallMethodAction MethodName="CurrentVisualStateChanged" TargetObject="{Binding Mode=OneWay}"/> </core:EventTriggerBehavior> </i:Interaction.Behaviors>` I suspect there may be issues with VisualStateGroup (or VisualStateManager) and the **CurrentStateChanged** event. I am saying this because, I can get this approach to work with other events. I have checked and rechecked the **CallMethodAction** method signatures (event arguments passing format) but no chance. If you managed to get **CurrentStateChanged** event triggering as above (or with an alternative approach), I would very much like to know.
2015/11/05
[ "https://Stackoverflow.com/questions/33549067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5525674/" ]
> > However, no success when it comes to the CurrentStateChanged event of VisualStateGroup as shown below > > > Yes, the EventTriggerBehavior won't work for VisualStateGroup.CurrentStateChanged event. The feasible way is to create a **custom Behavior** that specifically targets this scenario, please see [this blog](https://marcominerva.wordpress.com/2014/07/29/a-behavior-to-handle-visualstate-in-universal-apps-with-mvvm/) wrote by **Marco Minerva** This behavior can help us to monitor the current VisualStatus, in the Set method of custom property(ViewModelState type), calling method as you wish: ``` public class MainViewModel : ViewModelBase { public enum ViewModelState { Default, Details } private ViewModelState currentState; public ViewModelState CurrentState { get { return currentState; } set { this.Set(ref currentState, value); OnCurrentStateChanged(value); } } public RelayCommand GotoDetailsStateCommand { get; set; } public RelayCommand GotoDefaultStateCommand { get; set; } public MainViewModel() { GotoDetailsStateCommand = new RelayCommand(() => { CurrentState = ViewModelState.Details; }); GotoDefaultStateCommand = new RelayCommand(() => { CurrentState = ViewModelState.Default; }); } public void OnCurrentStateChanged(ViewModelState e) { Debug.WriteLine("CurrentStateChanged: " + e.ToString()); } } ``` **Please check my completed sample on [Github](https://github.com/Myfreedom614/UWP-Samples/tree/master/MvvmVisualStatesBehaviorUWPApp1/MvvmVisualStatesBehaviorUWPApp1)**
61,881
We have a Honeywell whole-house humidifier attached to the duct directly above the heating element/electronics of our furnace. A few possible pertinent facts: * The water intake is attached via a saddle valve. * The drainage line leads to a pump. The intake for the pump is a PVC pipe, which the drainage line rests inside. The drainage line for the pump resides in a sink in another room. * The humidistat is attached to the intake duct. Whenever we run the humidifier, we end up with a small amount of water on the floor. It doesn't tend to appear for some time, but it consistently appears within 4-8 hours. I have never actually observed the water exiting the humidifier, so I don't know where it's coming from precisely. Part of my concern (and the reason that we don't currently use the humidifier) is that the water is draining down the interior of the duct. I'm reasonably certain that the pump is not the reason for the leak. I've poured water directly into the pump's intake pipe and it proved capable of handling the water as fast as I supplied it. I've also changed the filter in the humidifier, but the leak persisted. The final wrinkle is that we had a plumber in for an unrelated issue who observed that the water pressure in our house is abnormally high (I believe he said it was 150 PSI, but I may remember incorrectly). My questions: 1. What are the likely reasons for the leak? 2. How can I definitively determine where the leak is originating from without watching the humidifier for hours? 3. Is the high water pressure a possible culprit?
2015/03/12
[ "https://diy.stackexchange.com/questions/61881", "https://diy.stackexchange.com", "https://diy.stackexchange.com/users/13047/" ]
I can only provide anecdotal answers to questions 2 & 3. 2. I have successfully used a few drops of concentrated food coloring, at different places I suspect for leaks in a water softener and its related valves and plumbing. I used 3 different colors if memory serves me right. We had a very slow/unnoticeable leak, apart from the puddle of course. I was able to determine which valve is was based on the color dye that showed up in the leak (blue in this case). 3. The failed water softener in this case did fail due to high water pressure. I would see if there is any manufacturers rating for the humidifier's working water pressure. There is no telling what parts, valves or plumbing inside the unit make be deforming/failing under such high pressure. Good luck in your troubleshooting and fix.
23,471,926
I know I can use `CASE` statement inside `VALUES` part of an insert statement but I am a bit confused. I have a statement like,
2014/05/05
[ "https://Stackoverflow.com/questions/23471926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2737135/" ]
You can try also a procedure: ``` create or replace procedure insert_XYZ (P_ED_MSISDN IN VARCHAR2, P_ED_OTHER_PARTY IN VARCHAR2) is begin INSERT INTO TABLE_XYZ ( ED_MSISDN, ED_OTHER_PARTY, ED_DURATION) VALUES (P_ED_MSISDN , P_ED_OTHER_PARTY , CASE WHEN P_ED_OTHER_PARTY = '6598898745' THEN '9999999' ELSE '88888' END); END; ```
22,739,757
//i want to display list items in list view i am put all the items in list i want to display all the items in listview it is displaying but getting same names where i keep the for loop in getview.Please help me how can i pshow the list items in listview. ``` public class Listjava extends Activity { /** Called when the activity is first created. */ int i = 0; List<Contact> contacts; MyBaseAdapter adapter; final DatabaseHandler db = new DatabaseHandler(this); @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); contacts = db.getAllContacts(); ListView list = (ListView) findViewById(R.id.listView1); adapter = new MyBaseAdapter(getApplicationContext(), contacts); list.setAdapter(adapter); } public class MyBaseAdapter extends BaseAdapter { private LayoutInflater inflater = null; public MyBaseAdapter(Context applicationContext, List<Contact> contacts) { // TODO Auto-generated constructor stub inflater = (LayoutInflater) getApplicationContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return contacts.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return null; } @Override public long getItemId(int position) { // TODO Auto-generated method stub return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View vi = convertView; if (convertView == null) { vi = inflater.inflate(R.layout.layoutlist, null); } for (Contact cn : contacts) { String log = "Id: " + cn.getID() + " ,Name: " + cn.getName() + " ,Phone: " + cn.getPhoneNumber(); // Writing Contacts to logsout System.out.println("log" + log); TextView title2 = (TextView) vi .findViewById(R.id.txt_ttlsm_row); // title // String song = title.get(position).toString(); title2.setText(cn.getName()); TextView title22 = (TextView) vi .findViewById(R.id.txt_ttlcontact_row2); // notice title22.setText(cn.getPhoneNumber()); } return vi; } } } ```
2014/03/30
[ "https://Stackoverflow.com/questions/22739757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3114723/" ]
Change the MyBaseAdapter class like below. ``` public class MyBaseAdapter extends BaseAdapter { private LayoutInflater inflater = null; List<Contact> contacts; public MyBaseAdapter(Context applicationContext, List<Contact> contacts) { // TODO Auto-generated constructor stub this.contacts = contacts;// Initialize here inflater = (LayoutInflater) getApplicationContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { // TODO Auto-generated method stub return contacts.size(); } @Override public Object getItem(int position) { // TODO Auto-generated method stub return contacts.get(position);// Changed } @Override public long getItemId(int position) { // TODO Auto-generated method stub return position; //Changed } @Override public View getView(int position, View convertView, ViewGroup parent) { // TODO Auto-generated method stub View vi = convertView; if (convertView == null) { vi = inflater.inflate(R.layout.layoutlist, null); } Contact cn = (Contact) getItem(position); TextView title2 = (TextView) vi .findViewById(R.id.txt_ttlsm_row); // title title2.setText(cn.getName()); TextView title22 = (TextView) vi .findViewById(R.id.txt_ttlcontact_row2); // notice title22.setText(cn.getPhoneNumber()); return vi; } } ```
64,125,262
I have a table with a list of folders and I want to return only the top level folders. For example, if the original table (tblFolders) has a single column (Fldrs) as below: **Fldrs** ``` C:\Folder1 C:\Folder1\Subfolder1 C:\Folder1\Subfolder2 C:\Folder2\Subfolder1 ``` I'd like to return: ``` C:\Folder1 C:\Folder2\Subfolder1 ``` Thanks in advance
2020/09/29
[ "https://Stackoverflow.com/questions/64125262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14362939/" ]
A standard SQL solution is to UNION all your dates ``` SELECT MyID, MAX(thedate ) AS maxdate, MIN(thedate ) AS mindate FROM ( SELECT MyID, Date1 AS thedate FROM table UNION ALL SELECT MyID, Date2 AS thedate FROM table UNION ALL SELECT MyID, Date3 AS thedate FROM table UNION ALL SELECT MyID, Date4 AS thedate FROM table ) T GROUP BY MyID ``` There might be better other solutions with window functions, depending on your RDBMS, which you haven't specified. But this one should work with any RDBMS.
56,573,278
I am trying to add some space between buttons in JavaFX using CSS. I know that separator element can do that, but I prefer to use it to separate logical groups of buttons. I have tried: ```xml <HBox id="buttonPanel" prefHeight="400.0" prefWidth="600.0" styleClass="buttonPanel" xmlns:fx="http://javafx.com/fxml/1" fx:controller="com.example.chart.buttons.ButtonPanelController"> <stylesheets> <URL value="@buttonpanel.css"/> </stylesheets> <Button text="INSTRUMENT"/> <Separator/> <Button text="F"/> <Button text="T"/> <Button text="SR"/> <Separator/> </HBox> ``` ```css .buttonPanel .button { -fx-spacing: 5; -fx-border-width: 0; -fx-padding: 1 2 1 2; /* Top Right Bottom Left */ } ``` But I do not get any result: [![enter image description here](https://i.stack.imgur.com/vdHGN.png)](https://i.stack.imgur.com/vdHGN.png)
2019/06/13
[ "https://Stackoverflow.com/questions/56573278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5328289/" ]
If you give an ID then try `#` ``` #buttonPanel { -fx-spacing: 5; -fx-border-width: 0; -fx-padding: 1 2 1 2; /* Top Right Bottom Left */ } ```
40,501,502
Its my first project using CodeIgniter and it is not as easy as it seems. I have to import different JSs and CSSs in different pages and I'm stuck. First of all, I've seen that hardcoding echos are not CI way of doing it so I made a simple class like ``` <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Fileload { public function loadjs($filename) { echo '<script language="javascript" type="text/javascript" src="'.$filename.'"></script>'; } public function loadcss($filename) { echo '<link rel="stylesheet" type="text/css" href="'.$filename.'" >'; } } ?> ``` And in my controller I used it like ``` <?php defined('BASEPATH') OR exit('No direct script access allowed'); class Main extends CI_Controller { /** * Index Page for this controller. * * Maps to the following URL * http://example.com/index.php/welcome * - or - * http://example.com/index.php/welcome/index * - or - * Since this controller is set as the default controller in * config/routes.php, it's displayed at http://example.com/ * * So any other public methods not prefixed with an underscore will * map to /index.php/welcome/<method_name> * @see https://codeigniter.com/user_guide/general/urls.html */ public function index() { $this->load->library('fileload'); $this->load->view('head'); $this->load->view('mainpage'); $this->fileload->loadjs('//cdn.jsdelivr.net/jquery.slick/1.6.0/slick.min.js'); $this->load->view('tail'); } } ``` But the slick library supposed to be at the bottom right above the 'tail' is at the top inside of head> tag, which is inside view('head'); It seems that the controllers' methods are not running in the sequence I've wrote it down. It should've echoed the script file first. Can anybody explain how this CodeIgniter controller works??
2016/11/09
[ "https://Stackoverflow.com/questions/40501502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4408351/" ]
Ok, so you tell Emacs to find-file some foo.py file, and Emacs reads it into a new `fundamental-mode` buffer and then calls `python-mode`. That's an autoload, so first it must load `python.el`, after which your eval-after-load kicks in and you start messing with the selected buffer. After that, `python-mode` is actually called -- but you've left some other buffer selected, so the mode gets enabled for that buffer, and foo.py remains in fundamental-mode. Wrapping your code in `save-current-buffer` would be a sensible start, but you might also want to be more explicit in your manipulations, rather than relying on `other-window` to do what you want.
29,642,188
Python 3. I am trying to return the function so that It would take a single word and convert it to Cow Latin. I want to get rid of the square bracket, the comma and single apostrophes when I run my function. My function is: ``` alpha = list("bcdfghjklmnpqrstvwxyz") def cow_latinify_word(word): if word[0].lower() in alpha: lista = (word.lower()) return lista[1:] + lista[0] + "oo" else: return word + "moo" def cow_latinify_sentence(sentence): words = sentence.split(); return [cow_latinify_word(word) for word in words] ``` when I test the function with ``` cow_latin = cow_latinify_sentence("Cook me some eggs") print(cow_latin) ``` I get `['ookcoo', 'emoo', 'omesoo', 'eggsmoo']` but I want `ookcoo emoo omesoo eggsmoo`
2015/04/15
[ "https://Stackoverflow.com/questions/29642188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4772905/" ]
Use `' '.join(list)` for concatenating the list elements into a string. In your code: ``` alpha = list("bcdfghjklmnpqrstvwxyz") def cow_latinify_word(word): if word[0].lower() in alpha: lista = (word.lower()) return lista[1:] + lista[0] + "oo" else: return word + "moo" def cow_latinify_sentence(sentence): words = sentence.split(); return ' '.join([cow_latinify_word(word) for word in words]) ```
47,913,649
I'm trying to access the Tensorboard for the `tensorflow_resnet_cifar10_with_tensorboard` example, but not sure what the url should be, the help text gives 2 options: > > You can access TensorBoard locally at <http://localhost:6006> or using > your SageMaker notebook instance proxy/6006/(TensorBoard will not work > if forget to put the slash, '/', in end of the url). If TensorBoard > started on a different port, adjust these URLs to match. > > > When it says access locally, does that mean the local container Sagemaker creates in AWS? If so, how do I get there? Or if I use `run_tensorboard_locally=False`, what should the proxy url be?
2017/12/20
[ "https://Stackoverflow.com/questions/47913649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3461257/" ]
Here is my solution: If URL of my sagemaker notebook instance is: ``` https://myinstance.notebook.us-east-1.sagemaker.aws/notebooks/image_classify.ipynb ``` And URL of accessing TensorBoard will be: ``` https://myinstance.notebook.us-east-1.sagemaker.aws/proxy/6006/ ```
37,458,388
We have a table with three columns: id, fieldName, fieldValue. This table has many records. We want to quickly access a list of the distinct fieldNames. When we create a view with a clustered index, we get this, but we have another problem: we have many processes that delete from the table by the id column. These have deadlocks, when multiple deletes run concurrently, since they are trying to update the index. If we create a view without an index, there are no deadlocks, but the view becomes very slow to use. Is there any way to create a view (or otherwise get the distinct fieldNames) that will work quickly, but also not lock on deletes? Adding data to the question, to answer some of the suggestions provided: We very rarely add new fieldNames, and deleting existing fieldNames is even rarer. Almost all new records use the existing fieldNames. There are few distinct fieldNames (about 30), but hundreds of millions of records in the table. We do have an index on fieldName in the table, but getting a list of the distinct fieldNames is still very slow if the view is not indexed.
2016/05/26
[ "https://Stackoverflow.com/questions/37458388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/50667/" ]
You don't need the view. Paul White blogged about how to find distinct values quickly in [Performance Tuning the Whole Query Plan](http://sqlperformance.com/2014/10/t-sql-queries/performance-tuning-whole-plan). He uses a recursive CTE to seek the next distinct value. Basically doing one seek per iteration/value jumping through the index. This will be faster for few distinct values but somewhere as the number of distinct values, compared to the number of rows in the table, increases there is a tipping point where a scan will be faster. In your case it would look something like this. Setup: ``` create table dbo.YourTable ( id int identity primary key, fieldName varchar(20) not null, fieldValue varchar(20) null ); go create index IX_YourTable_fieldName on dbo.YourTable(fieldName); go insert into dbo.YourTable(fieldName) values ('F1'), ('F1'), ('F1'), ('F2'), ('F2'), ('F2'), ('F3'); ``` Query: ``` with C as ( select top (1) T.fieldName from dbo.YourTable as T order by T.fieldName union all select R.fieldName from ( select T.fieldName, row_number() over (order by T.fieldName) as rn from dbo.YourTable as T inner join C on C.fieldName < T.fieldName ) as R where R.rn = 1 ) select C.fieldName from C option (maxrecursion 0); ``` Queryplan: [![enter image description here](https://i.stack.imgur.com/CSKL7.png)](https://i.stack.imgur.com/CSKL7.png)
36,064,401
I was trying to do something in Swift that would be easy in Objective-C using KVC. The new [Contacts framework](https://developer.apple.com/library/watchos/documentation/Contacts/Reference/Contacts_Framework/index.html) added in iOS9 is for the most part easier to use than the [old AddressBook API](https://developer.apple.com/library/ios/documentation/ContactData/Conceptual/AddressBookProgrammingGuideforiPhone/Introduction.html). But finding a contact by its mobile phone number seems to be difficult. The predicates provided for finding contacts are limited to the name and the unique identifier. In Objective-C you could get all the contacts and then use an NSPredicate to filter on a KVC query. The structure is: CNContact->phoneNumbers->(String, CNPhoneNumber->stringValue) Presume in the code below that I fetched the contacts via: ``` let keys = [CNContactEmailAddressesKey,CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)] let fetchRequest = CNContactFetchRequest(keysToFetch: keys) var contacts:[CNContact] = [] try! CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { ... ``` I want to compare the stringValue to a known value. Here's what I have so far from a playground: ``` import UIKit import Contacts let JennysPhone = "111-867-5309" let SomeOtherPhone = "111-111-2222" let AndAThirdPhone = "111-222-5309" let contact1 = CNMutableContact() contact1.givenName = "Jenny" let phone1 = CNPhoneNumber(stringValue: JennysPhone) let phoneLabeled1 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone1) contact1.phoneNumbers.append(phoneLabeled1) let contact2 = CNMutableContact() contact2.givenName = "Billy" let phone2 = CNPhoneNumber(stringValue: SomeOtherPhone) let phoneLabeled2 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone2) contact2.phoneNumbers.append(phoneLabeled2) let contact3 = CNMutableContact() contact3.givenName = "Jimmy" let phone3 = CNPhoneNumber(stringValue: SomeOtherPhone) let phoneLabeled3 = CNLabeledValue(label: CNLabelPhoneNumberMobile, value: phone3) contact3.phoneNumbers.append(phoneLabeled3) let contacts = [contact1, contact2, contact3] let matches = contacts.filter { (contact) -> Bool in let phoneMatches = contact.phoneNumbers.filter({ (labeledValue) -> Bool in if let v = labeledValue.value as? CNPhoneNumber { return v.stringValue == JennysPhone } return false }) return phoneMatches.count > 0 } if let jennysNum = matches.first?.givenName { print("I think I found Jenny: \(jennysNum)") } else { print("I could not find Jenny") } ``` This does work, but it's not efficient. On a device I would need to run this in a background thread, and it could take a while if the person has a lot of contacts. Is there a better way to find a contact by phone number (or email address, same idea) using the new iOS Contacts framework?
2016/03/17
[ "https://Stackoverflow.com/questions/36064401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2969719/" ]
If you are looking for a more Swift-y way to do it: ``` let matches = contacts.filter { return $0.phoneNumbers .flatMap { $0.value as? CNPhoneNumber } .contains { $0.stringValue == JennysPhone } } ``` `.flatMap` casts each member of `phoneNumbers` from type `CNLabeledValue` to type `CNPhoneNumber`, ignoring those that cannot be casted. `.contains` checks if any of these phone numbers matches Jenny's number.
7,318,402
I print hindi characters as string in java and I'm getting an error. I save the java file in notepad uing UTF-8. ``` public class MainClass { public static void main(String args[]) throws Exception { String s = "साहिलसाहिल"; System.out.print(s); } } ``` After compilation, I get 2 errors of illegal character. Why so?
2011/09/06
[ "https://Stackoverflow.com/questions/7318402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/290410/" ]
You have to specify the appropriate encoding : ``` javac -encoding utf8 MainClass.java ```
22,115,008
I am trying to get my edit to work I need the contact detail data to load when the user data loads. I have set the data in a similar manner to how I am retrieving the list of roles. I also don't know how to retrieve according to the model currently I was hard-coding it to retrieve 28. Would greatly appreciate any help provided. ``` public function edit($id = null) { //Populate roles dropdownlist $data = $this->User->Role->find('list', array('fields' => array('id', 'name'))); $this->set('roles', $data); $data2 = $this->User->ContactDetail->find('first', array( 'conditions' => array('ContactDetail.id' =>'28'))); $this->set('contactdetails', $data2); if (!$this->User->exists($id)) { throw new NotFoundException(__('Invalid user')); } if ($this->request->is(array('post', 'put'))) { if ($this->User->save($this->request->data)) { $this->Session->setFlash(__('The user has been saved.')); return $this->redirect(array('action' => 'index')); } else { $this->Session->setFlash(__('The user could not be saved. Please, try again.')); } } else { $options = array('conditions' => array('User.' . $this->User->primaryKey => $id)); $this->request->data = $this->User->find('first', $options); } } ``` my view is set up in the following manner ``` <?php echo $this->Form->create('User'); ?> <fieldset> <legend><?php echo __('Edit User'); ?></legend> <?php echo $this->Form->input('id'); echo $this->Form->input('username'); echo $this->Form->input('password'); echo $this->Form->input('role_id'); echo $this->Form->input('ContactDetail.name'); echo $this->Form->input('ContactDetail.surname'); echo $this->Form->input('ContactDetail.address1'); echo $this->Form->input('ContactDetail.address2'); echo $this->Form->input('ContactDetail.country'); echo $this->Form->input('ContactDetail.email'); echo $this->Form->input('ContactDetail.fax'); ?> <label>Are you interested in buying property in Malta?</label> <?php $interest_buy = array('0'=>'no','1' => 'yes'); echo $this->Form->input('ContactDetail.interest_buy_property',array('type'=>'radio','options'=>$interest_buy,'value'=>'0','legend'=>FALSE)); ?> <label>Are you interested in renting property in Malta?</label> <?php $interest_rent = array('0'=>'no','1' => 'yes'); echo $this->Form->input('ContactDetail.interest_rent_property',array('type'=>'radio','options'=>$interest_rent,'value'=>'0','legend'=>FALSE)); echo $this->Form->input('ContactDetail.mobile'); echo $this->Form->input('ContactDetail.phone'); echo $this->Form->input('ContactDetail.postcode'); echo $this->Form->input('ContactDetail.town'); echo $this->Form->input('ContactDetail.newsletter',array('type'=>'checkbox','label'=>'Would you like to register for the newsletter?' ,'checked'=>'1','legend'=>FALSE,)); ?> ?> </fieldset> <?php echo $this->Form->end(__('Submit')); ?> ``` **User Model** ``` public $primaryKey = 'id'; public $displayField = 'username'; public function bindNode($user) { return array('model' => 'Role', 'foreign_key' => $user['User']['role_id']); } public function beforeSave($options = array()) { $this->data['User']['password'] = AuthComponent::password( $this->data['User']['password'] ); return true; } public $belongsTo = array( 'Role' => array('className' => 'Role')); public $hasOne = array( 'ContactDetail' => array( 'foreignKey' => 'id')); public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false)); public function parentNode() { if (!$this->id && empty($this->data)) { return null; } if (isset($this->data['User']['role_id'])) { $roleId = $this->data['User']['role_id']; } else { $roleId = $this->field('role_id'); } if (!$roleId) { return null; } else { return array('Role' => array('id' => $roleId)); } } } ``` **ContactDetail Model** ``` public $primaryKey = 'id'; public $displayField = 'name'; ```
2014/03/01
[ "https://Stackoverflow.com/questions/22115008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/696406/" ]
`email` is being called on a nil `@user`, and `@user` is going to always be nil. Looking at this line: ``` unless @user_check = nil ``` Using a single equals is assignment, not an equality comparison. You'll want to do: ``` unless @user_check == nil ``` or the more idomatic Ruby: ``` unless @user_check.nil? ```
96,984
When another moderator sends a direct user message, the notification appears for all other moderators as a dropdown alert. This is somewhat distracting, and also impossible to get back to once it's closed. I feel like this type of alert makes more sense *for moderators* as a global inbox notification, since it's more of a "you should read this message" inbox type item. For users on the receiving end, it should probably be *both* a global inbox notification *and* a dropdown message, to ensure that they receive it.
2011/06/30
[ "https://meta.stackexchange.com/questions/96984", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/139837/" ]
The users **also typically get an email -- you know, a real, physical email in their email inbox** -- and that contains the text with a link to the moderator message URL, so I'm not sure I can agree with this. It is the default option when sending a moderator message.
18,899,045
What's the proper way to write this query? I have a column named TimeStamp in my customers table. I'm getting errors when trying to find customers who created an account in 2012. I've tried: ``` SELECT 'TimeStamp' AS CreatedDate FROM customers WHERE 'CreatedDate' >= '2012-01-01' AND 'CreatedDate' <= '2012-12-31' ``` and also ``` SELECT * FROM customers WHERE 'TimeStamp' >= '2012-01-01' AND 'TimeStamp' <= '2012-12-31' ``` and always get no results (there should be thousands)
2013/09/19
[ "https://Stackoverflow.com/questions/18899045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2795892/" ]
You must not use single quotes around column names as they are identifiers. ``` SELECT * FROM customers WHERE TimeStamp >= '2012-01-01' AND TimeStamp <= '2012-12-31' ``` If it happens that your column name is a reserved keyword, you can escape it by using `backtick` eg, ``` WHERE `select` .... -- SELECT is a reserved keyword ``` or use it along with the tableName ``` FROM tb WHERE tb.select .... -- SELECT is a reserved keyword ```
60,844,852
I am looking for a prettier way to delete some special characters (`{}[]()*?!^:|&"/\~`) if they exists in the first and the last position of a string called query. My way is pretty ugly but does the work. ```js while( query.charAt(1)==":" || query.charAt(1)=="{" || query.charAt(1)=="}" || query.charAt(1)=="[" || query.charAt(1)=="]" || query.charAt(1)=="*" || query.charAt(1)=="-" || query.charAt(1)=="^" || query.charAt(1)=="(" || query.charAt(1)==")" || query.charAt(1)=="|" || query.charAt(1)=='"' || query.charAt(1)=="/" || query.charAt(1)=="_" || query.charAt(1)=='"' || query.charAt(1)=="~" ){ query = query.slice(1); } while( query.charAt(query.length-1)=="!" || query.charAt(query.length-1)==":" || query.charAt(query.length-1)=="{" || query.charAt(query.length-1)=="}" || query.charAt(query.length-1)=="[" || query.charAt(query.length-1)=="]" || query.charAt(query.length-1)=="*" || query.charAt(query.length-1)=="?" || query.charAt(query.length-1)=="^" || query.charAt(query.length-1)=="(" || query.charAt(query.length-1)==")" || query.charAt(query.length-1)=="|" || query.charAt(query.length-1)=="&" || query.charAt(query.length-1)=='"' || query.charAt(query.length-1)=="/" || query.charAt(query.length-1)=="\\"|| query.charAt(query.length-1)=="~" ){ query = query.slice(0, -1); } ```
2020/03/25
[ "https://Stackoverflow.com/questions/60844852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12602828/" ]
Use a regular expression instead: ``` query = query.replace(/^[-:{}[\]*^()|"]+|[-:{}[\]*^()|"]+$/g, ''); ``` This pattern is composed of: ``` ^[CHARS]+|[CHARS]+$ ``` where `CHARS` are the characters you want to remove. * `^[CHARS]+` - Match one or more of those characters at the beginning of the string * `|` OR match * `[CHARS]+$` - one or more of those characters at the end of the string
18,785,399
If editors frequently work with show / hide dates for pages and content elements, there is an increasing number of outdated, hidden content in the Backend. For housekeeping, it would be nice to have an extension that lists such not-displayed content, maybe also hidden items. Is there something?
2013/09/13
[ "https://Stackoverflow.com/questions/18785399", "https://Stackoverflow.com", "https://Stackoverflow.com/users/160968/" ]
I'm not aware that there is any extension for this purpose. But you can use the list module for something similar. Place any kind of content on your "root" page. In the list module, you now see the table "Page Content". Click on the header cell to get only "Page Content" records. In the bottom of the list module, in the search part, perform a search "4 levels down" with an empty string. You then have all contents from the root page 4 levels down. In the field selector, select the "hidden" field. In the table, click the table head "Hide" twice to have all hidden elements on top. Then you can bookmark this view. Not exactly what you wanted, but it gives you some kind of overview.
53,433,285
I'm having this json stored in db ``` { "endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": { "foo": 1000, "bar": 2000, "baz": 3000 }, "anotherValue": 0 } ``` How can I rename `"oldKeyValue"` key to `"newKeyValue"` without knowing the index of the key in an `UPDATE` query? I'm looking for something like this ``` UPDATE `my_table` SET `my_col` = JSON() ``` NOTE: only the key needs to change, the values (i.e. `{"foo": 1000, "bar": 2000, "baz": 3000}`) should remain the same
2018/11/22
[ "https://Stackoverflow.com/questions/53433285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483422/" ]
There is no straightforward JSON function to do the same. We can use a combination of some JSON functions. We will remove the *oldKey-oldValue* pair using [`Json_Remove()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-remove) function, and then [`Json_Insert()`](https://dev.mysql.com/doc/refman/8.0/en/json-modification-functions.html#function_json-insert) the *newKey-oldValue* pair. [`Json_Extract()`](https://dev.mysql.com/doc/refman/8.0/en/json-search-functions.html#function_json-extract) function is used to fetch value corresponding to an input key in the JSON document. ``` UPDATE `my_table` SET `my_col` = JSON_INSERT( JSON_REMOVE(my_col, '$.oldKeyValue'), '$.newKeyValue', JSON_EXTRACT(my_col, '$.oldKeyValue') ); ``` **[Demo](https://www.db-fiddle.com/f/kHywwDrV1acnxb3x6HkWrT/0)** ``` SET @my_col := '{"endDate": "2018-10-10", "startDate": "2017-09-05", "oldKeyValue": {"foo": 1000, "bar": 2000, "baz": 3000}, "anotherValue": 0}'; SET @new_col := JSON_INSERT( JSON_REMOVE(@my_col, '$.oldKeyValue'), '$.newKeyValue', JSON_EXTRACT(@my_col,'$.oldKeyValue') ); SELECT @new_col; ``` **Result** ``` | @new_col | | ------------------------------------------------------------------------------------------------------------------------------- | | {"endDate": "2018-10-10", "startDate": "2017-09-05", "newKeyValue": {"bar": 2000, "baz": 3000, "foo": 1000}, "anotherValue": 0} | ``` --- As an alternative to `Json_Extract()`, we can also use `->` operator to access the Value corresponding to a given Key in the JSON doc. ``` UPDATE `my_table` SET `my_col` = JSON_INSERT( JSON_REMOVE(my_col, '$.oldKeyValue'), '$.newKeyValue', my_col->'$.oldKeyValue' ); ```
10,950,356
I have a quick question about Haskell. I've been following [Learn You a Haskell](http://learnyouahaskell.com/starting-out#tuples), and am just a bit confused as to the execution order / logic of the following snippet, used to calculate the side lengths of a triangle, when all sides are equal to or less than 10 and the total perimeter of the triangle is 24: `[(a,b,c) | c <- [1..10], b <- [1..c], a <- [1..b], a^2 + b^2 == c^2, a+b+c==24]` The part that is confusing to me is the upper expansion bound on the `b` and `a` binding. From what I gather, the `..c` and `..b` are used to remove additional permutations (combinations?) of the same set of triangle sides. When I run it with the `..c/b`, I get the answer: `[(6,8,10)]` When I don't have the `..c/b`: `[(a,b,c) | c <- [1..10], b <- [1..10], a <- [1..10], a^2 + b^2 == c^2, a+b+c==24]` as I didn't when I initially typed it in, I got: `[(8,6,10),(6,8,10)]` Which is obviously representative of the same triangle, save for the `a` and `b` values have been swapped. So, can someone walk me through the logic / execution / evaluation of what's going on here?
2012/06/08
[ "https://Stackoverflow.com/questions/10950356", "https://Stackoverflow.com", "https://Stackoverflow.com/users/420001/" ]
The original version considers all triplets (a,b,c) where c is a number between 1 and 10, b is a number between 1 and c and a is a number between 1 and b. (6,8,10) fits that criteria, (8,6,10) doesn't (because here a is 8 and b is 6, so a isn't between 0 and 6). In your version you consider all triplets (a,b,c) where a, b and c are between 1 and 10. You make no restrictions on how a, b and c relate to each other, so (8, 6, 10) is not excluded since all numbers in it are indeed between 1 and 10. If you think of it in terms of imperative for-loops, your version does this: ``` for c from 1 to 10: for b from 1 to 10: for a from 1 to 10: if a^2 + b^2 == c^2 and a+b+c==24: add (a,b,c) to the result ``` while the original version does this: ``` for c from 1 to 10: for b from 1 to c: for c from 1 to b: if a^2 + b^2 == c^2 and a+b+c==24: add (a,b,c) to the result ```
28,879,751
so here is the situation i currently am having trouble with. I want to check if a user has permission to view a page, with one single function. So I have an array with key/values where i store permissions in. ``` {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]}; ``` Stored in `service.currentUser`, which can be called by using `service.currentUser.authorities`. I have a function: ``` hasPermission: function (permission) { var role = { "role" : permission }; for(perm in service.currentUser.authorities) { var test = service.currentUser.authorities[perm]; if(test === role) { return (!!(service.currentUser) && true); } } return false; } ``` I created the `test` variable to debug its value. And the `permission` parameter has the value 'gebruikersbeheer'. Now i want to compare the value of the `perm` key with the `role` and check if it is true. Now i have searched along the internet to do so, and i only found solutions which are not viable for me nor implementable. When i start debugging my `perm` has an integer value. Why is it not the name of the key? (Which must be "role") Also, when i use Watch on the `role` and `test` variables they are completely the same but still i cant compare them and get a `true`. (Dont mind the return statement at this point.) Also i cannot modify the array. It is returned by spring security this way. Is there any (nicer) way to check if `authorities` contains `role`? It might be duplicate, but i couldnt find anything for my specific situation. Cheers.
2015/03/05
[ "https://Stackoverflow.com/questions/28879751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1863487/" ]
You currently are check a object with another object, is best check the string with the string, below show an little example of the same function but using the **some** method from arrays; ```js var currentUser = {"authorities":[{"role":"gebruikersbeheer"},{"role":"kijken"},{"role":"plannen"}]}; function hasPermission(permission) { return currentUser.authorities.some(function(v){ return v.role === permission; }); } alert("Have permission? "+ hasPermission("gebruikersbeheer")) ```
6,604,459
Is there an NSNotification we can observe for when the device is on/off the phone?
2011/07/07
[ "https://Stackoverflow.com/questions/6604459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/212559/" ]
The `NotificationCenter` doesn't send out any notifications abou this, but take a look at the `CTCallCenter` class introduced in iOS 4. It has a `callEventHandler` property that you can assign a block of code to, and gets called with call state info. There is a limitation in that the handler only gets called when your app is in the foreground (or being taken out of the foreground when a call comes in), but it tells you if the user is dialing (`CTCallStateDialing`), receiving a call (`CTCallStateIncoming`), answering/connecting (`CTCallStateConnecting`) or hanging up on a call (`CTCallStateDisconnected`).
71,032
I have a Ph.D. in pure math (interested in Harmonic analysis and operator theory). I am looking forward some proper references to lead me get the foundation of discrete/signal processing more and more. Actually, I had a review of the Heppenheim's books (both signal and digital ones) and (rather) got what he is saying in these (very nice) book. Now, I am going to develop my knowledge concerning this context and do need to cover some more advanced ones. Thanks in advances for you suggestions. Probably based on my own field, I would like to read on some texts whose approaches are focused on theoretical bases. However having some (proper) references which make me feel (realize) some real applications are in priority.
2020/10/23
[ "https://dsp.stackexchange.com/questions/71032", "https://dsp.stackexchange.com", "https://dsp.stackexchange.com/users/50574/" ]
You have already read those Oppenheim's Signals & Systems, and Discrete-Time Signal Processing books. I'm not sure what you mean by *foundations* but in some sense these two are also the foundations on signal processing. In other words, there are no (popular & successful) graduate level DSP books that discuss at an advanced level the *same topics* that are covered on them. However the following books (or subjects) will enhance your understanding, or broaden your appreciation of the subject. First of all, the very first graduate level course on DSP, Communications, and Control is called **Linear System Theory** which brings together all the undergraduate mathematical stuff from a new, advanced, deeper, and foundational point of view of the Hilbert (linear vector) Spaces, Linear Mappings, and Matrix theory. It does not have a definite book but a bunch of books on Linear Algebra & Matrices, Measure Theory, and Diferential Equations were used. Note that there's a control theory oriented bunch of Linear System Theory books (Desoer's crew) that I do not recommend for DSP, unless you will be designing control systems on the field. Signal processing does not make much use of state-space approach, unless it's absolutely necessary. Then the second refresher/deepener is on **Probability, Statistics and Random Processes**. Fortunately it has two very strongly recomended books though: * Statistical Digital Signal Procesing \_ Monson HAYES * Discrete RaNdom Signals and Statistical Signal Processing \_ THERRIEN The first book is a must read, the second one is following the style of Oppenheim series but is harder to follow, and less practical than the first. Then the following books / subjects will be awating you : * Adaptive Filter Theory \_ HAYKIN * Multiresolution Signal Decomposition \_ AKANSU * Multirate Digital Signal Processing \_ RABINER * Estimation & Detection Theory \_ KAY * Pattern Classification \_ DUDA * Theory and Applications of Digital Signal Processing \_ RABINER & GOLD Then the following applications will make your day : * Speech and Hearing for Communication - FLETCHER * Digital Processing of Speech \_ Rabiner * Speech and Audio Signal Processing \_ GOLD * Discrete-Time Processing of Speech \_ PROAKIS * Advances in Speech Coding \_ GERSHO * Two-Dimensional Signal and Image Processing \_ LIM * Digital Image Processing \_ GONZALES * Fundamentals of Image Processing \_ JAIN * Signal Compression\_JAYANT * Introduction to Data compression \_ SAYOOD Of course the list is by no means complete...
15,431,025
I have published a successful app on play, but after upgrading the app when I sign and align the app and install it on an emulator/real device it force closes and gives me `ClassNotFound` Exception. ``` 03-15 16:09:08.280: E/AndroidRuntime(7122): java.lang.RuntimeException: Unable to instantiate application william.shakespeare.MyBaseClass: java.lang.ClassNotFoundException: william.shakespeare.MyBaseClass 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.LoadedApk.makeApplication(LoadedApk.java:482) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.handleBindApplication(ActivityThread.java:3909) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.access$1300(ActivityThread.java:122) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1184) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.os.Handler.dispatchMessage(Handler.java:99) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.os.Looper.loop(Looper.java:137) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.ActivityThread.main(ActivityThread.java:4340) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.reflect.Method.invokeNative(Native Method) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.reflect.Method.invoke(Method.java:511) 03-15 16:09:08.280: E/AndroidRuntime(7122): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 03-15 16:09:08.280: E/AndroidRuntime(7122): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 03-15 16:09:08.280: E/AndroidRuntime(7122): at dalvik.system.NativeStart.main(Native Method) 03-15 16:09:08.280: E/AndroidRuntime(7122): Caused by: java.lang.ClassNotFoundException: william.shakespeare.MyBaseClass 03-15 16:09:08.280: E/AndroidRuntime(7122): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:61) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.ClassLoader.loadClass(ClassLoader.java:501) 03-15 16:09:08.280: E/AndroidRuntime(7122): at java.lang.ClassLoader.loadClass(ClassLoader.java:461) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.Instrumentation.newApplication(Instrumentation.java:942) 03-15 16:09:08.280: E/AndroidRuntime(7122): at android.app.LoadedApk.makeApplication(LoadedApk.java:477) 03-15 16:09:08.280: E/AndroidRuntime(7122): ... 11 more ``` This is my Manifest file: ``` <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="william.shakespeare" android:versionCode="2" android:versionName="1.1" > <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="14" /> <uses-permission android:name="android.permission.VIBRATE"/> <uses-permission android:name="android.permission.ACTION_SEND"/> <uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/> <uses-permission android:name="android.permission.BLUETOOTH"/> <user-permission android:name="android.permission.WRITE_SETTINGS" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/> <uses-permission android:name="android.permission.GET_TASKS"/> <application android:icon="@drawable/ic_launcher" android:theme="@android:style/Theme.Holo.NoActionBar" android:label="William Shakespeare Quotes" android:launchMode="singleInstance" android:name="william.shakespeare.MyBaseClass" > <activity android:name=".Splash_Screen" android:label="@string/title_activity_splash__screen" android:launchMode="singleInstance" android:screenOrientation="portrait" > <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <activity android:name=".AboutUs" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Biography" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Category_List" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Favourite_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Favourite_Single_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Help" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".MainMenu" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".MyCustomActionBar" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Quote_List" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".QuotesIn_Category" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".SearchFrom" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Settings" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name=".Single_Category" android:launchMode="singleInstance" android:screenOrientation="portrait"></activity> <activity android:name=".Single_Quote" android:launchMode="singleInstance" android:screenOrientation="portrait" ></activity> <activity android:name="com.google.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/> <receiver android:name=".Quote_Of_Day"/> <receiver android:name=".Notification_Quote"/> <receiver android:name=".Boot_Receiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver> </application> </manifest> ```
2013/03/15
[ "https://Stackoverflow.com/questions/15431025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1129047/" ]
ClassNotFound exception means that in your manifest file you have miss the Activity or may be you have not give correct name of the Activity.
6,163,166
I am trying to to understand **why Java's ArrayDeque is better than Java's LinkedList** as they both implement Deque interface. I hardly see someone using ArrayDeque in their code. If someone sheds more light into how ArrayDeque is implemented, it would be helpful. If I understand it, I will be more confident using it. I could not clearly understand the JDK implementation as to the way it manages head and tail references.
2011/05/28
[ "https://Stackoverflow.com/questions/6163166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/774521/" ]
Linked structures are possibly the worst structure to iterate with a cache miss on each element. On top of it they consume way more memory. If you need add/remove of the both ends, ArrayDeque is significantly better than a linked list. Random access each element is also O(1) for a cyclic queue. The only better operation of a linked list is removing the current element during iteration.
51,521,716
I have seen [this post](https://stackoverflow.com/questions/13258454/marking-specific-tiles-in-geom-tile-geom-raster), but I'm struggling to translate that to a logarithmic raster. For example: ``` library(tidyverse) a <- tibble(x = rep(10^seq(-2, 2), 5), y = rep(10^seq(-2, 2), each = 5), z = runif(25)) a %>% ggplot(aes(x, y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() ``` How do I now get for example a box around the row with `y = 0.1`? Or a box around just one tile? I know that the half-point between two points on a logarithmic scale is calculated by the geometric mean. **Update:** For the example above, the solution seems to work but not if `x` and `y` look a little different, e.g.: ``` n_x <- 10^seq(log10(6), log10(24*365), by = 0.1)/365 n_y <- 10^seq(-1, 3, by = 0.1) a <- tibble(x = rep(n_x, length(n_y)), y = rep(n_y, each = length(n_x)), z = runif(length(n_x)*length(n_y))) h <- a$y[which.min(abs(a$y - 1.14*24))] h.tb <- a %>% dplyr::filter(y == h) a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10(breaks = c(1, h, 100), labels = c('1', 'h', '100')) + geom_tile(data = h.tb, fill = NA, colour = "black", size = 2) ``` Interestingly, `h.tb` contains the correct data.
2018/07/25
[ "https://Stackoverflow.com/questions/51521716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1704801/" ]
Assuming for example that you want to mark tiles in the y = 0.1 row, for x < 10, adding `geom_tile()` like the following could work: ``` p1 <- a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() + geom_tile(data = . %>% filter(y == 0.1 & x < 10), # filter dataset for desired tiles fill = NA, # make tiles transparent colour = "black", size = 2) # aesthetic choices p1 ``` [![plot](https://i.stack.imgur.com/QPsnP.png)](https://i.stack.imgur.com/QPsnP.png) If you want the tiles to form a single rectangle, I can't think of an equally straightforward method, but it can be done. ``` # continuing from above, using the geom_tile layer from p1 to # obtain the correct tile dimensions, then transform all measures # back to the non-log form p1.data <- layer_data(p1, 2) %>% summarise(xmin = min(xmin), xmax = max(xmax), ymin = min(ymin), ymax = max(ymax)) %>% mutate_all(function(x) 10^x) > p1.data xmin xmax ymin ymax 1 0.003162278 3.162278 0.03162278 0.3162278 # replace the geom_tile() layer earlier with geom_rect() & the new data a %>% ggplot(aes(x = x, y = y)) + geom_raster(aes(fill = z)) + scale_x_log10() + scale_y_log10() + geom_rect(data = p1.data, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax), inherit.aes = FALSE, fill = NA, colour = "black", size = 2) ``` [![plot2](https://i.stack.imgur.com/yeuwN.png)](https://i.stack.imgur.com/yeuwN.png)
49,290,741
We are designing a system for conducting a survey in which it askes user a about 72 questions (Multiple Choice questions) And when the user submits this will be posted to php page which will save the answer in a MySQL table. Its works fine and perfectly well when we doing the test with a small number of user But I observed the when a large amount of users are submitting not all data reaches the server only a part of some users answer (around 65 answer) only reaches the server.But i get data from my all users but some answers aren't compete. Am using MySql engine : MyISAM What would be the problem or how can i solve this. is it the problem with some php configuration or mysql (large number of insert statement) What is the best way to handle larger amount data from a form submission php Thanks in Advance
2018/03/15
[ "https://Stackoverflow.com/questions/49290741", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4941350/" ]
There is a limit on `POST` request size in PHP. You can adjust [`post_max_size`](http://php.net/ini.core.php#ini.post-max-size) in your `php.ini`. As for database, I don't know how you are saving them in the database, but there are character/storage limitation on the database as well. Whenever I'm dealing with large `POST` data like sending numerous field values through forms, using ajax does wonders! Try using jQuery [`$.post()`](https://api.jquery.com/jquery.post/), which is the shorthand for [`$.ajax()`](https://api.jquery.com/jQuery.ajax/). It's quite easy to use, even if you're not that familiar with jQuery :)
271,524
I'm building a mansion to impress my friends. I've seen pictures of armor stands with ARMS. I searched how to summon one but all of them were either 1.9 or beta. (?how?) What command do i use to summon one that works?
2016/06/27
[ "https://gaming.stackexchange.com/questions/271524", "https://gaming.stackexchange.com", "https://gaming.stackexchange.com/users/151855/" ]
You can watch [this tutorial](https://www.youtube.com/watch?v=LoLRLKyswTI) (by Sethbling) to see how to show arms and more But if you want to show arms, try: `/summon ArmorStand ~ ~ ~ {ShowArms:1}` If you already spawned a ArmorStand and want to add arms (show arms), you can do: `/entitydata @e[r=2,type=ArmorStand] {ShowArms:1}` (tested).
40,057,611
I'm trying to draw a set of rectangles, each with a fill color representing some value between 0 and 1. Ideally, I would like to use any standard colormap. Note that the rectangles are not placed in a nice grid, so using `imagesc`, `surf`, or similar seems unpractical. Also, the `scatter` function does not seem to allow me to assign a custom marker shape. Hence, I'm stuck to plotting a bunch of Rectangles in a for-loop and assigning a `FillColor` by hand. What's the most efficient way to compute RGB triplets from the scalar values? I've been unable to find a function along the lines of `[r,g,b] = val2rgb(value,colormap).` Right now, I've built a function which computes 'jet' values, after inspecting `rgbplot`(jet). This seems a bit silly. I could, of course, obtain values from an arbitrary colormap by interpolation, but this would be slow for large datasets. So, what would an efficient `[r,g,b] = val2rgb(value,colormap)` look like?
2016/10/15
[ "https://Stackoverflow.com/questions/40057611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7022877/" ]
You can use `complete` from package `tidyr` : ``` library("tidyr") data %>% complete(area, year, fill = list(population.served = 0)) # # A tibble: 16 × 3 # area year population.served # <fctr> <fctr> <dbl> # 1 Cambridge Year.1 200 # 2 Cambridge Year.2 202 # 3 Cambridge Year.3 204 # 4 Cambridge Year.4 207 # 5 Edinburgh Year.1 0 # 6 Edinburgh Year.2 0 # 7 Edinburgh Year.3 0 # 8 Edinburgh Year.4 210 # ..... ```
34,523,149
I've developed app that takes screenshot. But it only takes snapshot of app. I want to take snapshot out of app. I've researched answers but I don't find answer yet. Here is my code. ``` View view = getWindow().getDecorView().getRootView(); view.setDrawingCacheEnabled(true); Bitmap bitmap = Bitmap.createBitmap(view.getDrawingCache()); view.setDrawingCacheEnabled(false); saveImageToAppFolder(bitmap); ``` saveImagetoAppFolder is function that saves image to app folder. That's not problem. Is there anyway to take snapshot of screen?
2015/12/30
[ "https://Stackoverflow.com/questions/34523149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5729314/" ]
To take screen shot of the device screen, **Only if you have root** call the screencap binary like: ``` Process sh = Runtime.getRuntime().exec("su", null,null); OutputStream os = sh.getOutputStream(); os.write(("/system/bin/screencap -p " + Environment.getExternalStorageDirectory()+ "/img.png").getBytes("ASCII")); os.flush(); os.close(); sh.waitFor() ``` And to load that file into a bitmap,Use ``` public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) { // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeFile(path, options); // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; return BitmapFactory.decodeFile(path, options); } public static int calculateInSampleSize( BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { final int halfHeight = height / 2; final int halfWidth = width / 2; // Calculate the largest inSampleSize value that is a power of 2 and keeps both // height and width larger than the requested height and width. while ((halfHeight / inSampleSize) > reqHeight && (halfWidth / inSampleSize) > reqWidth) { inSampleSize *= 2; } } return inSampleSize; } ```
16,878,544
Want search every word in a dictionary what has the same character exactly at the second and last positon, and one times somewhere middle. examples: ``` statement - has the "t" at the second, fourth and last place severe = has "e" at 2,4,last abbxb = "b" at 2,3,last ``` wrong ``` abab = "b" only 2 times not 3 abxxxbyyybzzzzb - "b" 4 times, not 3 ``` my grep is not working ``` my @ok = grep { /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/ } @wordlist; ``` e.g. the ``` perl -nle 'print if /^(.)(.)[^\2]+(\2)[^\2]+(\2)$/' < /usr/share/dict/words ``` prints for example the ``` zarabanda ``` what is wrong. What should be the correct regex? EDIT: And how to i can capture the enclosed groups? e.g. for the ``` statement - want cantupre: st(a)t(emen)t - for the later use my $w1 = $1; my w2 = $2; or something like... ```
2013/06/02
[ "https://Stackoverflow.com/questions/16878544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/632407/" ]
This is the regex that should work for you: ``` ^.(.)(?=(?:.*?\1){2})(?!(?:.*?\1){3}).*?\1$ ``` ### Live Demo: <http://www.rubular.com/r/bEMgutE7t5>
56,804,266
We are using [KubeDB](https://kubedb.com/docs/0.10.0/guides/redis/) in our cluster to manage our DB's. So Redis is deployed via a [KubeDB Redis object](https://kubedb.com/docs/0.10.0/concepts/databases/redis/) and KubeDB attaches a PVC to the Redis pod. Unfortunately KubeDB doesn't support any restoring or backing up of Redis dumps (yet). For the backup our solution is to have a CronJob running which copies the `dump.rdb` from the Redis pod into the job pod and then uploads it to S3. For the restoring of the dump I wanted to do the same, just the other way around. Have a temporary pod which downloads the S3 backup and then copies it over to the Redis pod into the `dump.rdb` location. The `redis.conf` looks like this: ``` .... # The filename where to dump the DB dbfilename dump.rdb # The working directory. # # The DB will be written inside this directory, with the filename specified # above using the 'dbfilename' configuration directive. # # The Append Only File will also be created inside this directory. # # Note that you must specify a directory here, not a file name. dir /data .... ``` The copying works. The `dump.rdb` is in the correct location with the correct permissions. I verified this by starting a second redis-server in the Redis pod using the same `redis.conf`. The `dump.rdb` is being loaded into the server without a problem. However, since I don't want to manually start a second redis-server, I restarted the Redis pod (by kubectl delete pods) for the pod to pickup the copied `dump.rdb`. Everytime I delete the pod, the `dump.rdb` is deleted and a new `dump.rdb` is being created with a much smaller size (93 bytes). I don't believe it is a PVC issue since I have created a few files to test whether they are deleted as well. They are not. Only the `dump.rdb`. Why does this happen? I am expecting Redis to just restore the DB from the `dump.rdb` and not create a new one. EDIT: Yeah, size of `dump.rdb` is around 47 GB. Redis version is 4.0.11.
2019/06/28
[ "https://Stackoverflow.com/questions/56804266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2591194/" ]
Sooo, a few hours later, my teammate remembered that Redis executes a save to dump on [shutdown](https://redis.io/commands/shutdown). Instead of deleting the pod using `kubectl delete pod` I now changed the code to run a `SHUTDOWN NOSAVE` using the `redis-cli`. ``` kubectl exec <redis-pod> -- /bin/bash -c 'redis-cli -a $(cat /usr/local/etc/redis/redis.conf | grep "requirepass " | sed -e "s/requirepass //g") SHUTDOWN NOSAVE' ```
38,138,478
I have a print table code fiddle [LINK](http://jsfiddle.net/9DbEP/1060/) Check my code: ``` function printData() { var divToPrint=document.getElementById("printTable"); console.log(divToPrint.outerHTML); newWin= window.open(""); newWin.document.write(divToPrint.outerHTML); newWin.print(); newWin.close(); } ``` I have added `background-color` to that as red as you can see in fiddle. I tried to print it. But in print the color not coming and all other things works fine. I have researched about `@media print` and all but unable to crack it. please guide me and an updated fiddle will be awesome you can give me. Cheers!
2016/07/01
[ "https://Stackoverflow.com/questions/38138478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4387657/" ]
Please find chrome driver here <https://sites.google.com/a/chromium.org/chromedriver/downloads>
43,917
I am traveling from Stockholm to Dubai and Dubai to Nairobi using two different airlines. I have Kenyan nationality and can't go through Immigration because I don't have a Dubai visa. How I will get my luggage?
2015/02/27
[ "https://travel.stackexchange.com/questions/43917", "https://travel.stackexchange.com", "https://travel.stackexchange.com/users/27260/" ]
If your luggage is not checked through, then I am afraid you will have to collect it and to do that you'll need a visa as the baggage carousels are *after* the immigration counters. The sequence is: 1. De-plane. 2. Depending on the terminal, you'll have a long walk (and then go down a few flights of stairs) or a short one, or really no walk at all (if you are at Terminal 2, as the bus will drop you right at the immigration counter). 3. The bank counter where you pay for the on-arrival visa will be on your right (Terminal 3, 2), or on your left (Terminal 1). 4. Go through immigration, then turn right to go through the metal detectors where they will scan your carryon luggage (in Terminal 3 its a straight walk). 5. Collect your baggage. 6. Go through either the Green Channel or the Red Channel (depending on what you have to declare). 7. Welcome to Dubai. I'm afraid you'll need a visa - the good news is a transit visa is available at the counter if you can show a continuing ticket/itinerary.
2,595,871
Are there any libraries to parse Textile (Textile to HTML) which will work in an Objective C iPhone app? C libraries will work too. **Update:** I couldn't find any sufficiently developed libraries in C/Obj-C, but I did find one written in Javascript, which I used through an invisible UIWebView. Link: [Javascript textile parser](http://jrm.cc/extras/live-textile-preview.php)
2010/04/07
[ "https://Stackoverflow.com/questions/2595871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/173781/" ]
Of course a method can return NSRange. But returning structures require special attention to the compiler because how the method is invoked is usually different (`objc_msgSend_stret` vs. `objc_msgSend`). Please make sure you declare `phrase` as ``` Phrase* phrase = ...; ``` so that the compiler knows `-rangeInString:…` is returning an NSRange, instead of ``` id phrase = ...; ``` (Also, since you don't show which line the compiler errors, make sure the function using `return … == -1;` is returning a BOOL not NSRange.)
57,546,243
I have this data's is there a way to get all of these? already tried `this._data.forEach` but it is not working thanks! ``` data() { return { childData: '', credit: '', company: '', email: '', first_name: '', middle_name: '', terms: '', last_name: '', phone: '', mobile: '', fax: '', street: '', city: '', country: '', state: '', zip_code: '', as_of: '', account_number: '', website:'', open_balance: '', notes: '', files: null, } ```
2019/08/18
[ "https://Stackoverflow.com/questions/57546243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10022569/" ]
try this perhaps: ``` =QUERY(IMPORTXML(B4, "//*[@id='historical-data']/div/div[2]/table/tbody/tr/td[2]"), "limit 100", 0) ```
45,589,463
i've read a lot of blogs, tutorials & co but i don't get something about the dynamic binding in java. When i create the object called "myspecialcar" it's creates an object from the class "car" as type of the class vehicle as a dynamic binding right? So java know that when i execute the method *myspecialcar.getType()* i have a car object and it execute the method from the class car. But why i got the *type* from the class vehicle? Is that because the variable from the class vehicle (type) is a static binding? Regards, Code: ``` public class vehicle { String type = "vehicle"; public String getType(){ return type; } } ``` ``` public class car extends vehicle { String type = "car"; public String getType(){ return type; } } ``` ``` public class test { public static void main (String[] args){ vehicle myvehicle = new vehicle(); // static binding car mycar = new car(); // static binding vehicle myspecialcar = new car(); //dynamic binding System.out.println(myspecialcar.getType()); System.out.println(myspecialcar.type); System.out.println(myspecialcar.getClass()); } } ``` Output: ``` car vehicle class car ```
2017/08/09
[ "https://Stackoverflow.com/questions/45589463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5747959/" ]
You faced the [fields hiding](http://docs.oracle.com/javase/tutorial/java/IandI/hidevariables.html). > > Within a class, a field that has the same name as a field in the > superclass hides the superclass's field, even if their types are > different. Within the subclass, the field in the superclass cannot be > referenced by its simple name. Instead, the field must be accessed > through super, which is covered in the next section. Generally > speaking, we don't recommend hiding fields as it makes code difficult > to read. > > >
23,434
A friend of a friend has on multiple occasions aggressively asked how my self-study for software engineering interviews is going. Most recently I answered very briefly, because I find it too nosy and the person to be arrogant and presumptuous. I don't like for example that he's convinced that I seem too calm about the job interview preparation process and that I don't push myself hard enough. Initially I just listened to him rant over the phone, and after he realized he was doing all the talking he then asked for my input and I answered honestly. Then he would "check in" with me over Messenger or when I ran into him at a party it would be the first topic of conversation. Since he didn't change, one thing I did when he was doing the same to someone else right in front of me was I asked "What do you mean?" and he simply acknowledged he was rambling. I've been distancing myself from him as of late which is tricky since he's in a few of my friend groups - I have no desire to "win." How do I convey that I'm not interested in him essentially interrogating me and opining in career-related matters?
2019/11/11
[ "https://interpersonal.stackexchange.com/questions/23434", "https://interpersonal.stackexchange.com", "https://interpersonal.stackexchange.com/users/4886/" ]
It sounds like you have already figured out this person's *motivation* for asking you questions - they want to give you advice. "Advice-giver" is a [recognised personality trait](https://www.psychologytoday.com/gb/blog/evolution-the-self/201308/what-you-should-know-about-advice-givers), and many do it for their own ego gratification. As the opportunity to give advice is evidently what is prompting the questions, if you stop fuelling him by answering them, the advice will hopefully stop. [This article](https://www.psychologytoday.com/gb/blog/fulfillment-any-age/201506/9-ways-handle-nosy-people) on Psychology Today suggests various ways of dealing with nosy people. Two of those ways are: 1. **Tell the truth** This could be the best approach if you don't want to be rude to the person. Answer their questions, but severely limit what you tell them. If they ask how it is going, you could just say "*it's going great, thanks*". Give yes/no answers to their questions if you think that will cut him short. If he persists then you could cut it short by saying something like "*that's a lot of questions, shall we talk about something else?*" 2. **Deflection** If you are comfortable being more direct in telling them that you don't want to talk about this, this approach is about not answering any questions at all. Change the subject - perhaps say "*I'm bored with study, I'd rather talk about something else"*. Other techniques include stating your discomfort about the questions, but that may send the message that your self-study is not going too well, and that may not be the message you want to send. Ultimately though, not allowing an 'advice-giver' to give you advice is like starving them of their oxygen. They will not be interested in pursuing you for answers if they aren't getting what they want out of it.
10,840,872
I am currently going through a tutorial using Visual Studio 11 beta. When trying to set the max length of a field value in one of my classes: ``` [MaxLength(50)] public string LastName { get; set; } ``` It errors out and wont let me compile because the `MaxLength()` function exists in two places: > > Error 4 The type '**System.ComponentModel.DataAnnotations**.MaxLengthAttribute' exists in both 'c:\Users\me\Documents\Visual Studio 11\ContosoUniversity\packages\EntityFramework.4.1.10331.0\lib\net40\EntityFramework.dll' and 'c:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.5\System.ComponentModel.DataAnnotations.dll' > > > I have tried to remove both files but that just causes more issues because other code in my project is dependent upon them. Is there a way I can tell it to use one or the other? **All of these approaches don't seem to be working for me.. Refer to the comments under the answers.. Any other ideas?** Thanks
2012/05/31
[ "https://Stackoverflow.com/questions/10840872", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1022305/" ]
Use using at the top of your code: ``` using MaxLength = System.ComponentModel.DataAnnotations ```
609,275
I administer a large number of ESXi hosts, and in order to do that efficiently, I pretty much need to have SSH allowed into the hosts at all times, as it's just far too burdensome to enable and disable SSH access through vCenter/vSphere on every host every time I need to log into a host and view the CLI or SCP files between hosts, or whatever else. However, the problem I'm facing is that the default behavior in vSphere is to display a warning icon and nag-banner on any host for which SSH access is enabled. [![enter image description here](https://i.stack.imgur.com/VB6W2.png)](https://i.stack.imgur.com/VB6W2.png) More than just being annoying, this makes it impossible to see from a quick visual scan if there's a warning condition I actually care about on any of my hosts, like high CPU or memory usage, or low disk space, loss of redundancy, etc. So, how do I get rid of this warning icon (and if possible, the nag banner as well)?
2014/07/01
[ "https://serverfault.com/questions/609275", "https://serverfault.com", "https://serverfault.com/users/118258/" ]
This particular alert can be controlled in the `Advanced Settings` under the `Configuration` tab for the host in question. Once there, go to the `UserVars` category and scroll down to `UserVars.SuppressShellWarning`. Change the value from `0` to `1`, and you will no longer be warned that the host in question is allowing SSH access. [![enter image description here](https://i.stack.imgur.com/fuHss.png)](https://i.stack.imgur.com/fuHss.png)
127,635
I need to monitor open and closed ports on dozens of hosts. I've found a [Nagios](http://en.wikipedia.org/wiki/Nagios) plugin that does what I need, but I would have to use this script through [NRPE](http://en.wikipedia.org/wiki/Nagios#Nagios_Remote_Plugin_Executor). Some of the hosts are powered by Linux and they all have Perl installed. But some of them are Windows machines, and it's not convenient for me to install Perl on every one of them. That's why I can not use this plugin. I hope that there's Nagios plugin that uses [Nmap](http://en.wikipedia.org/wiki/Nmap), or something similar, so it could check ports on every host remotely, without installing plugins on remote hosts, only on the server.
2010/03/30
[ "https://serverfault.com/questions/127635", "https://serverfault.com", "https://serverfault.com/users/14850/" ]
What do you mean to check ports on hosts remotely? Do you just want to connect to the port to see if it is open? The check\_tcp plugin will do that, if, that's what you want to do. Not quite sure what you mean.
29,442,424
The following is code that I have put together with some help from SO. I am trying to be able to implement the `$select` statement, as well as the `$search` statement on the same page. The `$select` statement works fine, but I do not know how to call the `$search` statement to execute when the user searches using the form within the code. Does anyone know how to do this, or can you redirect me to a good tutorial with how forms interact with php? ``` <?php require 'db/connect.php'; $select = $db->query("SELECT * FROM customers ORDER BY id DESC"); $search = $db->query("SELECT * FROM customers WHERE FName LIKE '%$_REQUEST[q]%' OR LName LIKE '%$_REQUEST[q]%' ORDER BY id DESC"); ?> <!DOCTYPE html> <html lang="en"> <head> <link rel="stylesheet" href="styles.css"> </head> <body> <div id="wrapper"> <h1>Customers</h1> <p><a class="btn create" href="createcustomer.php">CREATE</a></p> <?php if (!$select->num_rows) { echo '<p>', 'No records', '</p>'; }else{ ?> <table border="1" width="100%"> <thead> <tr> <th>First Name</th> <th>Last Name</th> <th>Phone</th> <th>Alt Phone</th> <th>Job Address</th> <th>Billing Address</th> <th>Email</th> <th>Alt Email</th> </tr> </thead> <tbody> <?php while ($row = $select->fetch_object()) { ?> <tr> <td><?php echo $row->FName;?></td> <td><?php echo $row->LName;?></td> <td><?php echo $row->Phone;?></td> <td><?php echo $row->AltPhone;?></td> <td><?php echo $row->JobAddress;?></td> <td><?php echo $row->BillingAddress;?></td> <td><?php echo $row->Email;?></td> <td><?php echo $row->AltEmail;?></td> <td><a class="btn read" href="viewcustomer.php?id=<?php echo $row->id; ?>">READ</a>&nbsp;<a class="btn update" href="editcustomer.php?id=<?php echo $row->id; ?>">UPDATE</a>&nbsp;<a class="btn delete" href="deletecustomer.php?id=<?php echo $row->id; ?>">DELETE</a></td> </tr> </tbody> <tbody> <?php } ?> </table> <?php } ?> # Search form that needs tied to $search <input type="text" name="q" /> <input type="submit" name="search" /> </div> </body> </html> ```
2015/04/04
[ "https://Stackoverflow.com/questions/29442424", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4564055/" ]
You can you `touchesBegan` for that. Here is example code for you: ``` override func touchesBegan(touches: NSSet, withEvent event: UIEvent) { for touch: AnyObject in touches{ let location = touch.locationInNode(self) if self.nodeAtPoint(location) == self.playButton{ //your code } } } ```
967,261
Why isn't this script working? ``` $(function() { var isbn = $('input').val(); $('button').click(function() { $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); }); ``` As you can see, I'm trying to do an extremely simple ISBN lookup field for a demo web site. The script is supposed to take the value of the input and insert it into the URL. Why isn't it working? Also, is there a better way to accomplish this end? I realize, of course, that iframes are rubbish, but I just want to keep it simple right now.
2009/06/08
[ "https://Stackoverflow.com/questions/967261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/97939/" ]
It's not clear when your code gets called, but is this line: ``` var isbn = $('input').val(); ``` only called once at page-load time, whereas it should be within the click handler: ``` $('button').click(function() { var isbn = $('input').val(); $("#data").html('<iframe height="500" width="1000" src="http://books.google.com/books?vid=ISBN' + isbn + '" />'); }); ```
55,710,561
i need some help to validate a jwt signature with a ECDSA public key. I'm reading the key from a .pem file with bouncy castle and using jjwt to do the validation. I'm getting an error while validating the signature. ``` Security.addProvider(new BouncyCastleProvider()); String jwt = "eyJ0eXAiOiJKV1QiLCJhbGciOiJFUzI1NiJ9.eyJtc2kiOiI5NzE1NTA5ODc2NTUiLCJmZWEiOiJzaWdudXAtZGF0YSIsImlzcyI6IkNEUCIsImV4cCI6MTU1NDU2NjMzNiwiaWF0IjoxNTU0MzkzNTM2LCJzaWQiOiIwNDI0MDMwMDg5NzI4MTg3QG5haS5lcGMubW5jMTMwLm1jYzMxMC4zZ3BwbmV0d29yay5vcmcifQ.RwxoGmFd1_dQPeGN-0gnWIW79xXvGHoyJKBbCKajgO75UooceS6tskxwqViEuP1gZD66UE8Bd2L0FaeI2aS_IA"; PemReader pemReader = new PemReader(new FileReader("/publickey.pem")); X509EncodedKeySpec spec = new X509EncodedKeySpec(pemReader.readPemObject().getContent()); KeyFactory kf = KeyFactory.getInstance("ECDSA","BC"); PublicKey publicKey = kf.generatePublic(spec); Jws<Claims> claims = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(jwt); ``` I'm getting a Signature Exception with: Unable to verify Elliptic Curve signature using configured ECPublicKey. error decoding signature bytes.
2019/04/16
[ "https://Stackoverflow.com/questions/55710561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2343794/" ]
This will work as well without mentioning any algorithm. ``` public boolean isTokenValid(String token) { try { String certificate = "GET_YOUR_PUBLIC_CERTIFICATE_HERE"; //Either from REST call or reading from a cert file. getPublicKeyAndParseToken(token, certificate); return true; } catch (IOException e) { log.error("", e); } catch (Exception e) { log.error("", e); log.error("JWT Not-Verified"); } return false; } private void getPublicKeyAndParseToken(String token, String certificate) throws IOException, CertificateException { log.debug("Certificate:: " + certificate); //Only for debugging purpose InputStream is = new ByteArrayInputStream(certificate.getBytes(StandardCharsets.UTF_8)); CertificateFactory cf = CertificateFactory.getInstance("X.509"); Certificate cert = cf.generateCertificate(is); PublicKey publicKey = cert.getPublicKey(); Jws parsedClaimsJws = Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token); log.debug("Header:: " + parsedClaimsJws.getHeader()); //Only for debugging purpose log.debug("Body:: " + parsedClaimsJws.getBody()); //Only for debugging purpose } ``` Don't forget to use version '0.9.x' of jjwt library. I've below dependency in my build.gradle: ``` compile('io.jsonwebtoken:jjwt:0.9.1') ```
19,243,837
I am new to use Autolayouts, even this is my first try. Whatever I do with it, I end with a white screen as result. Here is my attempt. I have a `UIView`, let me say a `parentView` of frame `(60, 154, 200, 200)`. It is a subview to `self.view`. Then I have a dynamic view, say `dynamicView` of frame `(0, 0, 260, 100)` and a `label` of frame `(15, 25, 230, 50)` which is a subview to `dynamicView`. When I add the `dynamicView` as subview to the `parentView`, it goes out of `parentView`'s bounds. So, I'd like to adjust the size of the `dynamicView` and its child(`label`) so that its position is center to the `parentView` and `dynamicView` is inside `parentView`'s bounds. My first attempt was setting `clipsToBounds`, its not working in Xcode5, iOS7. So the next option is to achieve this using `NSLayoutConstraint`. I have no idea on it. I welcome your ideas.
2013/10/08
[ "https://Stackoverflow.com/questions/19243837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/500625/" ]
i'll just address the dyanmicView being part of the parentView issue, then let you go from there **first**: if you are creating the view dynamically, then you're good to go, but if you've created it from storyboard, you'd have to detach it from it's parent then reattach it.. that's how you get rid of it's previous NSConstraints (that usually the storyboard introduces) that may conflict with your new ones. you also gotta set it's `setTranslatesAutoresizingMaskIntoConstraints` to NO b/c that also can interfere with your nsconstraints. I usually do those last two steps like so, using [mapObjectsUsingBlock](https://github.com/abbood/NSArray-Addons) to make the whole tedious process of creating constraints a bit more pleasant and natural: ``` [@[view_1, view_2, /../, view_n] mapObjectsApplyingBlock:^(UIView *view) { [view removeFromSuperview]; [view setTranslatesAutoresizingMaskIntoConstraints:NO]; [view setHidden:NO]; [superView addSubview:view]; }]; ``` **then** before applying nsconstraints, you gotta make sure that the view you want the constraints to apply to is *already* attached to it's parent: ``` [parentView addSubview:dynamicView]; ``` **then** you want to create a bindings dictionary: ``` NSDictionary *buttonBindingsDictionary = @{ @"parentView" : parentView, @"dynamicView" : dynamicView}; ``` then you want to add the constraints using the [visual format language](https://developer.apple.com/library/mac/documentation/UserExperience/Conceptual/AutolayoutPG/Articles/formatLanguage.html#//apple_ref/doc/uid/TP40010853-CH3).. I also use `mapObjectsUsingBlock` here (i'll explain each constraint in english): ``` NSArray *buttonConstraints = [@[@"V:|-[dynamicView(>=200)]-|", @"|-[dynamicView(>=260)]-|", ] mapObjectsUsingBlock:^id(NSString *formatString, NSUInteger idx){ return [NSLayoutConstraint constraintsWithVisualFormat:formatString options:0 metrics:nil views:buttonBindingsDictionary]; }]; ``` `V:|-[dynamicView(>=200)]-|` means that vertically speaking.. the upper and lower distance between `dynamicView` and it's parent should be equal.. also `dynamicView's` height should be no less than `200` `|-[dynamicView(>=260)]-|` means that horizontally speaking.. the left and right distance between `dyanmicview` and it's parent should be equal.. also `dyanmicView's` width should be no less than `260` *note:* you can do the math yourself and set exactly how much the left/right/bottom/top distance between `dyanicView` and it's parent.. this is just simpler.. but sometimes nsconstraints messes up and I gotta do it myself. in that case it would look something like this where `x` is the distance you came up with: ``` V:|-x-[dynamicView(>=200)]-x-| |-x-[dynamicView(>=260)]-x-| ``` then you gotta add the constraints to the parent view: ``` [parentView addConstraints:[buttonConstraints flattenArray]]; ``` notice here i used [flatten array](https://github.com/abbood/NSArray-Addons), again that's a method from my library b/c i want to feed it a one level array, not an array of arrays. and you're good to go! **note:** i know that this may not work perfectly.. but it gives you the idea of what to do + some helper files. It takes some practice, and you should look at some of the [tutorials](http://www.raywenderlich.com/20881/beginning-auto-layout-part-1-of-2) for sure.. i suggest you start with nsconstraints using storyboard (you can select a view.. then go editor>pin>.. then chose something.. get some immediate visual feedback.. also you can simulate what your views will look like in 3.5" displays vs 4.0" displays immediately on the storyboard by selecting the view controller, then going to attributes inspector and selecting different sizes under simulated metrics) take your time bud, but one thing for sure: once you go nsconstraints you will never look back! it's totally worth it! p.s. you can also [animate](https://stackoverflow.com/questions/12622424/how-do-i-animate-constraint-changes) views using nsconstraints as well.. just in case you were wondering.
441,419
I’m curious if I have a legitimate concern or if I’m just being overly paranoid. I have a rechargeable Lithium-Polymer battery (prismatic shaped) rated for a max charging temperature of 45 °C. The battery rests against a circuit board that I know can generate some heat when charging the battery (500 mA current via an MCP73831 IC). It can get up to around 49 °C in a single location on the board (say about 1/4”x1/4” in size) and a dissipated temperature around that (I even measured 63 °C once on the hot spot but haven’t been able to reproduce it). That is for the back of the board where the battery rests (the front side can get up to 80 °C at the charger IC). Is there any legitimate concern that this will heat the battery during charging? There is nothing between the LiPo and the board. Using a thermal camera, it doesn’t seem like any heat really transfers well to the battery, so it seems like it should be okay, but I’m no expert in heat transfer, especially if it remained in the described state/position for a few hours. The battery and board would sit inside a plastic enclosure.
2019/06/01
[ "https://electronics.stackexchange.com/questions/441419", "https://electronics.stackexchange.com", "https://electronics.stackexchange.com/users/77406/" ]
Lithium-Polymer service life is seriously degraded at high temperatures, especially when fully charged. The cooler you can keep the battery the better. I suggest using a more efficient switch-mode charging IC such as the TP5000.
472,937
When running msbuild.exe with ANT's exec task, errors in the .net code do not result in the build process failing. Why would this be?
2009/01/23
[ "https://Stackoverflow.com/questions/472937", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I use Nant to run some MSBuild tasks. Every time I use the `failonbuild` attribute of that task, it fails for me. Looking at Apache's documentation for Ant, it would appear the same attribute is there as well. Are you using this attribute?
40,049,978
I'm trying to get the currently displayed `ViewController` using the following: ``` let currentViewController = UIApplication.sharedApplication().keyWindow!.rootViewController?.presentedViewController ``` This property gives me the `TabBarController`. The only property after `presentedViewController` is "`childViewControllers`". How could I use this to attain the currently displayed `ViewController`?
2016/10/14
[ "https://Stackoverflow.com/questions/40049978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6758725/" ]
I would use a computed property instead of a filter and a method. I'd go through each cast member and if any of their groups is in `selected_groups` I'd allow it through the filter. I'd so this using `Array.some`. ``` results: function() { var self = this return self.cast.filter(function(person) { return person.groups.some(function(group) { return self.selected_groups.indexOf(group) !== 1 }) }) }, ``` Here's a quick demo I set up, might be useful: <http://jsfiddle.net/crswll/df4Lnuw6/8/>
2,721,502
The challenge ------------- The shortest code by character count that will output the numeric solution, given a number and a valid string pattern, using the [Ghost Leg](http://en.wikipedia.org/wiki/Ghost_Leg) method. Examples -------- ``` Input: 3, "| | | | | | | | |-| |=| | | | | |-| | |-| |=| | | |-| |-| | |-|" Output: 2 Input: 2, "| | |=| | |-| |-| | | |-| | |" Output: 1 ``` Clarifications -------------- 1. Do not bother with input. Consider the values as given somewhere else. 2. Both input values are valid: the column number corresponds to an existing column and the pattern only contains the symbols `|`, `-`, `=` (and [space], [LF]). Also, two adjacent columns cannot both contain dashes (in the same line). 3. The dimensions of the pattern are unknown (min 1x1). Clarifications #2 ----------------- 1. There are two invalid patterns: `|-|-|` and `|=|=|` which create ambiguity. The given input string will never contain those. 2. The input variables are the same for all; a numeric value and a string representing the pattern. 3. Entrants must produce a function. Test case --------- ``` Given pattern: "|-| |=|-|=|LF| |-| | |-|LF|=| |-| | |LF| | |-|=|-|" |-| |=|-|=| | |-| | |-| |=| |-| | | | | |-|=|-| Given value : Expected result 1 : 6 2 : 1 3 : 3 4 : 5 5 : 4 6 : 2 ``` **Edit: corrected expected results**
2010/04/27
[ "https://Stackoverflow.com/questions/2721502", "https://Stackoverflow.com", "https://Stackoverflow.com/users/180243/" ]
JavaScript: 169 158 148 141 127 125 123 122 Characters ------------------------------------------------------ **Minified and Golfed:** ``` function g(n,s){for(l=s.split('\n'),n*=2;k=l.shift();)for(j=3;j;)n+=k[n-3]==(c=--j-1?'=':'-')?-2:k[n-1]==c?2:0;return n/2} ``` **Readable Version:** ``` function g(n, str) { var c, i, j; var lines = str.split('\n'); n = (n * 2) - 2; for (i = 0; i < lines.length; i++) { for (j = 0; j < 3; j++) { c = (j == 1) ? '-' : '='; if (lines[i].charAt(n-1) == c) n-=2; // Move left else if (lines[i].charAt(n+1) == c) n+=2; // Move right } } return 1+n/2; } ``` **Explanation:** 1. `str` is split into an array of lines. 2. `n` is scaled to cover the number of characters in each line, starting from 0. 3. Iterate three times over each line: one time for each layer. Imagine each line is divided into 3 layers: The top and bottom layers are where the legs of the of the `=` sign are attached. The middle layer is for the legs of the `-` signs. 4. Move `n` either left or right according to the adjacent signs. There is only one possible move for every layer of each line. Therefore `n` could move up to 3 times in a line. 5. Return `n`, normalized to start from 1 to the number of vertical lines. **Test Cases:** ``` var ghostLegs = []; ghostLegs[0] = "|-| |=|-|=|\n" + "| |-| | |-|\n" + "|=| |-| | |\n" + "| | |-|=|-|"; ghostLegs[1] = "| | | | | | | |\n" + "|-| |=| | | | |\n" + "|-| | |-| |=| |\n" + "| |-| |-| | |-|"; ghostLegs[2] = "| | |=| |\n" + "|-| |-| |\n" + "| |-| | |"; ghostLegs[3] = "|=|-|"; for (var m = 0; m < ghostLegs.length; m++) { console.log('\nTest: ' + (m + 1) + '\n'); for (var n = 1; n <= (ghostLegs[m].split('\n')[0].length / 2) + 1; n++) { console.log(n + ':' + g(n, ghostLegs[m])); } } ``` **Results:** ``` Test: 1 1:6 2:1 3:3 4:5 5:4 6:2 Test: 2 1:1 2:3 3:2 4:4 5:5 6:6 7:8 8:7 Test: 3 1:3 2:1 3:4 4:2 5:5 Test: 4 1:3 2:2 3:1 ```
5,533
I'm aware there are floppy emulators that are installed to 3.5″ bays where disk images are stored on a flash drive. But what I need now is the opposite: essentially a USB dongle that emulates the floppy drive hardware with a disk inside. Something that older OS installers would recognize. The need came up when I tried to install Windows XP on a laptop. The only way to load the AHCI drivers is via a floppy drive. I have a USB floppy drive, but no disks at the moment :( and obviously there is no 3.5″ bay to install the typical emulator in a laptop. I know I can always just buy some floppies, and in fact I have some on the way, but given the reliability of floppies over time, I still feel that what I'm describing would often come in handy. Does anyone make/sell these?
2018/01/20
[ "https://retrocomputing.stackexchange.com/questions/5533", "https://retrocomputing.stackexchange.com", "https://retrocomputing.stackexchange.com/users/7758/" ]
I don't think anyone sells something like that in one piece. There are, however, components on the market that should allow you to build that from scratch: 1. A GoTek or HxC that behaves like a "real" floppy 2. An *old* Floppy-to-USB adapter that was used to connect "real" floppies over USB. I don't think they're still made, so you would need to source one from eBay. Newer USB floppy drives no longer have this as I have learned from answers to [this](https://retrocomputing.stackexchange.com/questions/5428/is-there-anything-useful-for-a-retro-in-these-cheap-chinese-floppy-drives) question. 3. Some sort of external power supply, as the GoTek/HxC will not be willing to live from the USB power supply. Putting it all together would end you up with something that behaves like a real floppy, connected over USB. This is, however, never going to be a full replacement for a "real" floppy disk drive. Old computer's abilities to for example boot from USB floppies have always been very limited (even if they could always boot very well from standard floppy drives). Once you find one that does this, it will most probably also boot from a standard USB flash stick. You'd probably be much better off by buying a bunch of HD disks and storing them well. Another, entirely different, but possibly long-term method to make Windows XP think it has a floppy drive would be a *[virtual floppy driver](http://vfd.sourceforge.net)*. This just emulates a floppy based on an image stored on hard disk and could be a solution for many problems. You'd obviously need to have a drive and disk first in order to pull the images from "real" disks.
519,832
I want to write the following sentence in a compact way: "The difference between the old scheme and the new scheme lies in..." Which one of the following is correct? 1. The difference between the old and **new scheme** lies in... 2. The difference between the old and **new schemes** lies in... 3. The difference between the old and **the new scheme** lies in... 4. The difference between the old and **the new schemes** lies in... Option 1 sounds more natural to me but I cannot explain why. More important, English is not my mother tongue. In other words, I would like to know: * Is it necessary to repeat the definite article for each element of the list? * Does the common object (in this case, the scheme) become plural when it is listed multiple times with different pre-modifiers (in this case, old and new)?
2019/12/04
[ "https://english.stackexchange.com/questions/519832", "https://english.stackexchange.com", "https://english.stackexchange.com/users/368826/" ]
All are variations of parallelism, with two distinct wrinkles: * Whether the determiner or article must be repeated or not * Whether the head noun is singular or plural All four constructions are valid, but produce slight differences in emphasis. --- > > The difference between **the old and new** scheme lies in... > > > The difference between **the old** and **the new** scheme lies in... > > > In the first example, *the* is a determiner modifying "old and new scheme." Readers will generally understand that it breaks down into "the old scheme and the new scheme." The second example repeats the determiner and further emphasizes it. Generally, readers will still understand "the old scheme and the new scheme." In this case, the difference is slight because no other modifiers are interrupted when the determiner repeats. Fiction editor Beth Hill, in a post on this subject at [The Editor's Blog](https://theeditorsblog.net/2015/08/08/one-adjective-paired-with-multiple-nouns-a-readers-question/), shows how repeating the determiner can mark a further difference between two items: > > **The flat footballs and soccer balls** had been stored in the basement for a long time. (Both footballs and soccer balls are flat.) > > > **The flat footballs and the stained soccer balls** had been stored in the basement for a long time. (Only the footballs are flat—the soccer balls are stained but not flat, at least not that we know of.) > > > **The flat footballs and the soccer balls** had been stored in the basement for a long time. (We have no clues about the condition of the soccer balls. From this wording—with just the addition of the article the—we can’t assume that they’re flat.) > > > Repeating **the** is a clue that other premodifiers like "flat" may only pertain to the first noun. In your case, that is not relevant since the only premodifiers for "scheme" are already distinguished by "and." --- > > The difference between the old and new **scheme** lies in... > > > The difference between the old and new **schemes** lies in... > > > Both work, but with some caveats. Plural signals that there are *two or more* schemes, at least one is old, and at least one is new. It does not limit the potential number - there could be two old and three new schemes. If the existence of only two schemes is evident from context (you've only been discussing two schemes so far in your text), it should provide no confusion. Singular is acceptable because readers will understand that the two adjectives are mutually exclusive, such that it is not one scheme that is both old and new, but two: *the old scheme* and *the new scheme*. Take note: if the adjectives could both describe the same noun, this might be confusing: > > The difference between the hot and wet car lies in ... > > > Some readers might expect "the hot and wet car" to be followed by a second item, like "the cold and dry car," since technically a single car could be both hot and wet. In this case, adding the article avoids the issue ("the hot and the wet car"), since the duplicated determiner could only pertain to a second car. (As described above, duplicating the determiner helps mark further differences between items.) Confusion can also be avoided when using mutually exclusive adjectives (e.g. user-centric and network-centric).
62,006,211
Having worked through a course on Pluralsight (.NET Logging Done Right: An Opinionated Approach Using Serilog by Erik Dahl) I began implementing a similar solution in my own ASP.Net Core 3.1 MVC project. As an initial proof of concept I downloaded his complete sample code from the course and integrated his logger class library into my project to see if it worked. Unfortunately, everything seems to work apart from one critical element. In the Configure method of my project's Startup.cs file rather than `app.UseExceptionHandler("/Home/Error");` I now have `app.UseCustomExceptionHandler("MyAppName", "Core MVC", "/Home/Error");` - in theory this is meant to hit some custom middleware, passing in some additional data for error logging, then behave like the normal exception handler and hit the error handling path. In practice, it doesn't hit the error handling path and users are shown the browser's error page. The comments on the middleware code say this code is: ``` // based on Microsoft's standard exception middleware found here: // https://github.com/aspnet/Diagnostics/tree/dev/src/ // Microsoft.AspNetCore.Diagnostics/ExceptionHandler ``` This link no longer works. I found the new link but it's in a GitHub archive and it didn't tell me anything useful. I am aware that there were changes to the way routing works between .Net Core 2.0 and 3.1, but I'm not sure whether these would cause the issue I am experiencing. I do not think the issue is in the code below that gets called from Startup.cs. ``` public static class CustomExceptionMiddlewareExtensions { public static IApplicationBuilder UseCustomExceptionHandler( this IApplicationBuilder builder, string product, string layer, string errorHandlingPath) { return builder.UseMiddleware<CustomExceptionHandlerMiddleware> (product, layer, Options.Create(new ExceptionHandlerOptions { ExceptionHandlingPath = new PathString(errorHandlingPath) })); } } ``` I believe the issue is likely to be in the Invoke method in the actual CustomExceptionMiddleware.cs below: ``` public sealed class CustomExceptionHandlerMiddleware { private readonly RequestDelegate _next; private readonly ExceptionHandlerOptions _options; private readonly Func<object, Task> _clearCacheHeadersDelegate; private string _product, _layer; public CustomExceptionHandlerMiddleware(string product, string layer, RequestDelegate next, ILoggerFactory loggerFactory, IOptions<ExceptionHandlerOptions> options, DiagnosticSource diagSource) { _product = product; _layer = layer; _next = next; _options = options.Value; _clearCacheHeadersDelegate = ClearCacheHeaders; if (_options.ExceptionHandler == null) { _options.ExceptionHandler = _next; } } public async Task Invoke(HttpContext context) { try { await _next(context); } catch (Exception ex) { WebHelper.LogWebError(_product, _layer, ex, context); PathString originalPath = context.Request.Path; if (_options.ExceptionHandlingPath.HasValue) { context.Request.Path = _options.ExceptionHandlingPath; } context.Response.Clear(); var exceptionHandlerFeature = new ExceptionHandlerFeature() { Error = ex, Path = originalPath.Value, }; context.Features.Set<IExceptionHandlerFeature>(exceptionHandlerFeature); context.Features.Set<IExceptionHandlerPathFeature>(exceptionHandlerFeature); context.Response.StatusCode = 500; context.Response.OnStarting(_clearCacheHeadersDelegate, context.Response); await _options.ExceptionHandler(context); return; } } private Task ClearCacheHeaders(object state) { var response = (HttpResponse)state; response.Headers[HeaderNames.CacheControl] = "no-cache"; response.Headers[HeaderNames.Pragma] = "no-cache"; response.Headers[HeaderNames.Expires] = "-1"; response.Headers.Remove(HeaderNames.ETag); return Task.CompletedTask; } } ``` Any suggestions would be really appreciated, I've been down so many rabbit holes trying to get this working over the last few days to no avail, and quite aside from my own project, I'd love to be able to leave a comment on the Pluralsight course for anyone else trying to do this to save them having to go through the same struggles as I have.
2020/05/25
[ "https://Stackoverflow.com/questions/62006211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7801941/" ]
You can use `trackBy` on **\*ngFor** to deal with changes. It allows you to check each element and rerenders only the ones that are new. You can use an id or another unique elements to check them. Template : ```js <tr *ngFor="let element of objects$ | async; trackBy: trackByFunction"> </tr ``` Component : ```js trackByFunction(index: number; element: MyClass) { return element.id; // or another unique property } ``` Here is an example i made few days ago on [Stackblitz](https://stackblitz.com/edit/ng-sample-performance-trackby?file=src%2Fapp%2Fapp.component.ts) (with a message on new elements to tag them)
13,537,503
Can I please have a design suggestion for the following problem: I am using Codeigniter/Grocery\_CRUD. My system is multi tenanted - different autonomous sites - within the same client. I have quite a few instances of tables that have unique logical keys. One such table structure is: equip\_items id (pk) equip\_type\_id (fk to equip\_types) site\_id (fk to sites) name Where (equip\_type\_id, site\_id, name) together are a unique key in my db. The issues is that when using a grocery\_CRUD form to add or edit a record that breaks this database rule - the add or edit fails (due to the constraints in the db) but I get no feedback. I need a variation on the is\_unique form\_validation rule by which I can specify the field\*s\* that must be unique. The issues: How to specify the rule? set\_rules() is for a given field and I have multiple fields that the rule will apply to. Does that mean I should abandon the Form\_validation pattern? Or do I follow the 'matches' rule pattern and somehow point to the other fields? Perhaps a callback function would be better but this would mean writing a custom function in each model where I have this problem at last count this is 9 tables. It seems far better to do this in one place (extending form\_validation). Am I missing something already in codeigniter or grocery\_CRUD that has already solved this problem? Any suggestion/advice you might have would be appreciated. **EDIT:** Actually it appears the solution Johnny provided does not quite hit the mark - it enforces each field in unique\_fields() being independently unique - the same as setting is\_unique() on each one. My problem is that in my scenario those fields are a composite unique key (but not the primary key). I don't know if it is significant but further to the original problem statement: 1) site\_id is a 'hidden' field\_type - I don't want my users concerned they are on a different site so I'm dealing with site\_id behind the scenes. 2) Same deal with an equip\_status\_id attribute (not part of the unique key). And 3) I have set\_relations() on all these foreign key attributes and grocery\_CRUD kindly deals with nice drop downs for me. **EDIT 2** I have solved this using a callback.
2012/11/24
[ "https://Stackoverflow.com/questions/13537503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1228116/" ]
**UPDATE:** This code is now part of grocery CRUD version >= 1.4 and you don't need to use an extension anymore. For more see the documentation for [unique\_fields](http://www.grocerycrud.com/documentation/options_functions/unique_fields) I will try to explain it as easy as I can: **1.** First of all for those who have grocery CRUD lower or equal to 1.3.3 has to use this small change: <https://github.com/scoumbourdis/grocery-crud/commit/96ddc991a6ae500ba62303a321be42d75fb82cb2> **2.** Second create a file named grocery\_crud\_extended.php at application/libraries **3.** Copy the below code at your file application/libraries/grocery\_crud\_extended.php ``` <?php class grocery_CRUD_extended extends grocery_CRUD { protected $_unique_fields = array(); public function unique_fields() { $args = func_get_args(); if(isset($args[0]) && is_array($args[0])) { $args = $args[0]; } $this->_unique_fields = $args; return $this; } protected function db_insert_validation() { $validation_result = (object)array('success'=>false); $field_types = $this->get_field_types(); $unique_fields = $this->_unique_fields; $add_fields = $this->get_add_fields(); if(!empty($unique_fields)) { $form_validation = $this->form_validation(); foreach($add_fields as $add_field) { $field_name = $add_field->field_name; if(in_array( $field_name, $unique_fields) ) { $form_validation->set_rules( $field_name, $field_types[$field_name]->display_as, 'is_unique['.$this->basic_db_table.'.'.$field_name.']'); } } if(!$form_validation->run()) { $validation_result->error_message = $form_validation->error_string(); $validation_result->error_fields = $form_validation->_error_array; return $validation_result; } } return parent::db_insert_validation(); } protected function db_update_validation() { $validation_result = (object)array('success'=>false); $field_types = $this->get_field_types(); $unique_fields = $this->_unique_fields; $add_fields = $this->get_add_fields(); if(!empty($unique_fields)) { $form_validation = $this->form_validation(); $form_validation_check = false; foreach($add_fields as $add_field) { $field_name = $add_field->field_name; if(in_array( $field_name, $unique_fields) ) { $state_info = $this->getStateInfo(); $primary_key = $this->get_primary_key(); $field_name_value = $_POST[$field_name]; $ci = &get_instance(); $previous_field_name_value = $ci->db->where($primary_key,$state_info->primary_key) ->get($this->basic_db_table)->row()->$field_name; if(!empty($previous_field_name_value) && $previous_field_name_value != $field_name_value) { $form_validation->set_rules( $field_name, $field_types[$field_name]->display_as, 'is_unique['.$this->basic_db_table.'.'.$field_name.']'); $form_validation_check = true; } } } if($form_validation_check && !$form_validation->run()) { $validation_result->error_message = $form_validation->error_string(); $validation_result->error_fields = $form_validation->_error_array; return $validation_result; } } return parent::db_update_validation(); } } ``` **4.** Now you will simply have to load the grocery\_CRUD\_extended like that: ``` $this->load->library('grocery_CRUD'); $this->load->library('grocery_CRUD_extended'); ``` and then use the: ``` $crud = new grocery_CRUD_extended(); ``` instead of: ``` $crud = new grocery_CRUD(); ``` **5.** Now you can simply have the unique\_fields that it works like this: ``` $crud->unique_fields('field_name1','field_name2','field_name3'); ``` In your case: ``` $crud->unique_fields('equip_type_id','site_id'); ``` Pretty easy right? This is checking if the field is unique or not without actually change the core of grocery CRUD. You can simply use the grocery\_CRUD\_extended instead of grocery\_CRUD and update grocery CRUD library as normal. As I am the author of the library I will try to include this to grocery CRUD version 1.4, so you will not have to use the grocery\_CRUD\_extended in the future.
16,329
I have some basic questions about my 1-year-old pug. 1. How much should he eat? Typically he should eat 2 times, but he always keeps some food in his bowl and whenever he wants he eats. Is this a good practice? (I use Royal Canin Mini Adult) 2. Now-a-days he always wants what I'm eating. How to stop this? I'm too new (being my first pet) in this area, so your views are appreciated.
2017/02/08
[ "https://pets.stackexchange.com/questions/16329", "https://pets.stackexchange.com", "https://pets.stackexchange.com/users/8839/" ]
1. As Gone2 has stated, you should definitely regulate your pug's intake by removing the food after 15-20 minutes with each feeding. All kibble has feeding directions on the back, so you should follow the feeding recommendations on the bag for his weight unless otherwise directed by a veterinarian. Dogs should generally have a thin layer over their midsection but not so thick you can't feel their ribs. The ribs also shouldn't be visible while they're relaxed. 2. For begging, you can try redirecting by rewarding him when he doesn't beg. Or teach him a down stay. Another method is to give him a toy, himalayan chew, or bully stick to work on while you eat in peace.
15,043,674
I do something like this in my code ``` S s; s.a=1 s.b=2 v.push_back(s) ``` Now that C++ has forwarding can i write something like ``` v.push_back(1,2) ``` fyi visual studio supports forwarding as the below works as expected ``` //http://herbsutter.com/gotw/_102/ template<typename T, typename ...Args> std::unique_ptr<T> make_unique( Args&& ...args ) { return std::unique_ptr<T>( new T( std::forward<Args>(args)... ) ); } ```
2013/02/23
[ "https://Stackoverflow.com/questions/15043674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
You can use `std::vector::emplace_back` which will create the object inplace with the fitting constructor. This of course requires that you have such a constructor defined. ``` v.emplace_back(1,2); ``` As of C++11 every std-container offers an emplace-like function which gives the above described behavior. Compatibility-note: MSVC probably doesn't support this yet as it only supports variadic templates as of the CTP which doesn't affect the standard library and gcc's libstd++ is still missing the emplace member functions in the associative containers.
33,840
Consider our world at 18-19 centuries. Our civilization knows how to print books, build steam machines, we have made first experiments on electricity. And one day the [Mad God Sheogorath](http://elderscrolls.wikia.com/wiki/Sheogorath) is emerged. He can bend the reality by his will. For example, he can violate the principles of conservation of energy - build Perpetuum Mobile just to irritate scientists. He can convert Darwin back into the monkey just to help him prove his theory. He can make forgery of dinosaur skeletons, so we have found caterpillar riding tankosaurus instead of diplodocus. He can resurrect people. And, do a lot of things we are not aware. So, in potential he can spoil every scientific acquired experiments result in a way, that is hard to see. So, the question is: is scientific method still possible in this world? UPD: after 20 years Sheogorath have just vanished. Can we undo his trickery and restore science methods?
2016/01/21
[ "https://worldbuilding.stackexchange.com/questions/33840", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/2763/" ]
**Caveat**: I've made some assumptions in order to make this work as a potential world. Like many have pointed out, a truly mad god acting without care would probably manage to kill off the human race pretty quickly if they acted often enough to have a tangible effect on the world (by triggering a catastrophic imbalance in the environment). The only way to make this really work as an interesting world would be if Sheogorath was particularly careful in what he did, and only set out to mess with the experiments of scientists and their inventions, and changing the laws of physics/reality over very focused areas, rather than screwing with reality at random. --- Scientific method relies on consistent results, and to a large extent on statistical modelling and probabilities; if I perform 1,000,000 tests of a hypothesis and all come out true, I can say with pretty reasonably probability that it is correct. If Sheogorath's influence is obvious, or at least discernable without *too* much effort (As in, I can tell when something was caused by him rather than being natural), then it would make scientific advancement (or indeed pretty much anything relying on facts) cripplingly slow - I would have to double and triple check every experiment to ensure that no "spoiled" data made it into the calculations, and I'd have to ensure that the calculations themselves weren't spoiled, and every time I read a book I'd have to ensure that the words/results hadn't been changed since they were written down. In other words, everything would take forever. **In this case, scientific method would be possible, but very, very slow**. If his influence is impossible to distinguish from "reality", then all scientific research would be virtually impossible — whenever I get a result, I have no idea whether it's real or Sheogorath is screwing with me. All you could do is note hypotheses and keep as much data as possible, hoping that some day it might be useful. In this case, **Scientific Method would be impossible**. The damage on society is hard to predict. There's a chance that society would fall apart completely depending on whether people are aware that it is the Mad God's doing, or whether they think reality is ending. Then there's the Monotheistic religious crisis, the fact that noone can trust anything they see... theoretically all of civilisation could fall apart if critical things are warped. If he's just messing with science however, and we ignore the other effects on society he would have, then yes, science would recover, probably. 20 years isn't that long a time - people would still be alive that remembered how the methods worked. It's long enough to give up, but not long enough to have forgotten. So long as it is obvious that he is gone, Scientific Method would pick up again. Of course, you'd have to contend with the thought of whether he'd be back. Some people would probably give up saying that there isn't a point, maybe all of them, but I would think that it's likely that at least **SOME** people would take the risk. EDIT: The point of Scientific Study would depend largely on the level of change being effected by Sheogorath: * If major changes were made to reality constantly, society would effectively collapse for those 20 years, if it survived at all. Daily life would be hard enough to predict, let alone finding the time to perform and log scientific experiments. * If minor/minimal changes were made, reality would be deterministic enough that scientific development could probably still be deemed worthwhile. If enough people repeat the experiment, the chances are that eventually there will be enough data to make a probable correct statement. It might be wrong, but it's worth a try... provided Sheogorath doesn't then on a whim decide to make it the opposite just because you've made the discovery. * In an increasing range between the two extremes, Scientific discoveries would be increasingly more unlikely, because everything would be increasingly untrustworthy.
8,051,394
Could anybody help me out to get nested tabs through ajax calls. Description: I am having Jquery Tabs with ajax option CODE: ``` $( ".has_ajax_tabs" ).tabs({ ajaxOptions: { error: function( xhr, status, index, anchor ) { $( anchor.hash ).html("<h3>OOPS...Something went wrong!</h3> Couldn't load this tab at this time. Please try again later."); } }, spinner: "Loading...", fxSlide: true }); ``` HTML CODE: ``` <div id="tabs" class="has_ajax_tabs"> <ul> <li><a href="#tabs-1">Profile Details</a></li> <li><a href="nestedTabsLink.php">Users</a></li> </ul> <div id="tabs-1"> Profile Details form here </div> </div> ``` nestedTabsLink.php loaded by Ajax call ``` <div id="tabs-nested" class="has_ajax_tabs"> <ul> <li><a href="#tabs-inner1">Inner Tab1</a></li> <li><a href="#tabs-inner2">Inner Tab2</a></li> </ul> <div id="tabs-inner1"> Nested Tabs1 </div> <div id="tabs-inner2"> Nested Tabs2 </div> </div> ``` ERROR: The loaded nestedTabsLink.php file also having tabs which is not working if loaded by Ajax. Without Ajax it works perfect. Can anybody help me to get the code snippet/guidelines? Thanks
2011/11/08
[ "https://Stackoverflow.com/questions/8051394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
That's a bad idea. The lifetime of a threadpool thread is determined by the code it executes, preferably short and snappy. This is *not* the rule for an STA thread, it must stay active and pump a message loop as long as the COM objects that were created on that thread are not finalized. A requirement that's very incompatible with a TP thread. Trying to do this anyway will just buy you never-ending misery with "COM object that has been separated from its underlying RCW cannot be used" exceptions as well as deadlock. This is why a .NET tp thread is always MTA. You must use a regular Thread.
16,660
I'm currently building a functional Lego escalator that is minifigure-scaled and with staircases transitioning from flat platform to stairwell. Here's my progress so far: [![escalator slope design](https://i.stack.imgur.com/OOvDG.png)](https://i.stack.imgur.com/OOvDG.png) But with the design of the staircases hopefully out of the way for now, I've come into an issue with the slope as it is seemingly improbable to build. I tried multiple iterations: technic bricks, technic beams, snot, … but there's only so much I can do on Mecabricks. I don't have the necessary bricks available at my disposal, nor does my local area has any retails which offers the Pick-a-Brick service, therefore I couldn't physically test this build out. Is there any way of building a framework for this slope to hold up at a precise angle of 39.5 degrees? Preferably one that is legal or at least doesn't cause immense stress on the bricks, due to the technical nature of this build? EDIT: Extra images for elaboration: [![Isometric perspective of escalator design](https://i.stack.imgur.com/gmcxy.jpg)](https://i.stack.imgur.com/gmcxy.jpg) [![Design of stair consists of 2 3M shafts, plate 1x2 with holder (vertical), and plate 1x1 with upright holder](https://i.stack.imgur.com/g30r0.jpg)](https://i.stack.imgur.com/g30r0.jpg) I aim to have this escalator to be roughly 4 bricks in width and its height will be dependent on how tall a story might be (probably 9 bricks tall). I don't intend to use the new dedicated escalator piece because I want to design an escalator that is flat at the base and transition into a moving stairwell then back into a flat platform at the top (and vice versa). Basically something of [this](https://www.youtube.com/watch?v=VAjFw7v8QhE) complexity , but at a minifigure scale. EDIT 2: These are the results I yielded when I tried hinge pieces for building a slope: [![Iteration 1](https://i.stack.imgur.com/WSkiJ.png)](https://i.stack.imgur.com/WSkiJ.png) [![Iteration 2](https://i.stack.imgur.com/k4Vvq.png)](https://i.stack.imgur.com/k4Vvq.png) Connector peg with [plate 1x2 with pinhole on bottom](https://www.bricklink.com/v2/catalog/catalogitem.page?P=18677&name=Plate,%20Modified%201%20x%202%20with%20Pin%20Hole%20on%20Bottom&category=%5BPlate,%20Modified%5D#T=C) or any other hinge designs yield the same results. Maybe it could work but since I don't have local access to Bricklink and the likes, I couldn't physically test this out and have only Mecabricks to work with.
2021/10/15
[ "https://bricks.stackexchange.com/questions/16660", "https://bricks.stackexchange.com", "https://bricks.stackexchange.com/users/19067/" ]
Could this work in you case? Using snot brick to build it vertically. [![Slope 45°](https://i.stack.imgur.com/9mNeE.jpg)](https://i.stack.imgur.com/9mNeE.jpg) EDIT 1: The only way I managed to get your angle and snap it correctly is like that. I used stud.io with collision turned on to be sure it could work. I hope this can help you. [![39.5](https://i.stack.imgur.com/Nyvem.png)](https://i.stack.imgur.com/Nyvem.png) [![39.5°](https://i.stack.imgur.com/L6vPG.png)](https://i.stack.imgur.com/L6vPG.png) EDIT 2: I found another solution using bar and bar with clip. This one is much more modulable but maybe less stable. Let me know what you think. [![enter image description here](https://i.stack.imgur.com/K7UNh.png)](https://i.stack.imgur.com/K7UNh.png) EDIT 3: Adapted to use technic beam. [![beam setup](https://i.stack.imgur.com/uJpO7.png)](https://i.stack.imgur.com/uJpO7.png) [![with beam](https://i.stack.imgur.com/2xxMy.png)](https://i.stack.imgur.com/2xxMy.png)
330,170
I learned British English, but I work exclusively with Americans. I'll often say "Fat lot of good X did for us", and I get confused looks from others. For example, the other day, I said "I think we should have had them take the web development course; fat lot of good the algorithms course did for them" and people have no idea what I mean. A coworker told me that what I'm saying sounds like what someone British would say, and I'm not sure how to Americanize this statement. First: Am I using the term "Fat lot of good" incorrectly? Second: How should I say this in American English?
2022/12/30
[ "https://ell.stackexchange.com/questions/330170", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/151216/" ]
**Just leave out the fat**, in speech, and use a sarcastic tone. "I think we should have had them take the web development course; a lot of good the algorithms course did for them." The fact is that this is an idiomatic expression. And **many Americans** *would in fact understand* "a fat lot of good". Who cares what a coworker says? The expression is not essentially British at all. It's in Merriam Webster like this: a (fat) lot of good idiom informal : no use or help at all "I've brought an umbrella." "A (fat) lot of good that will do now that it's stopped raining!" [Merriam Webster](https://www.merriam-webster.com/dictionary/a%20%28fat%29%20lot%20of%20good)
3,599,278
I must develop a simple web application to produce reports. I have a single table "contract" and i must return very simple aggregated values : number of documents produced in a time range, average number of pages for documents and so on . The table gets filled by a batch application, users will have roles that will allow them to see only a part of the reports (if they may be called so ). My purpose is : 1. develop a class, which generates the so called reports, opened to future extension (adding new methods to generate new reports for different roles must be easy ) 2. decouple the web graphic interface from the database access I'm evaluating various patterns : decorator, visitor, ... but being the return data so simple i cannot evaluate which apply or even if its the case to use one. Moreover i must do it i less than 5 days. It can be done if i make a so called "smart gui" but as told at point 1, i don't want to get troubles when new roles or method will be added. --- thank you for your answers. I'm sorry, i realize i haven't provided too much infos. I live in a Dilbert world. at the moment i've got the following info : db will be oracle (the concrete db doesn't exist yet) , so no EF, maybe linqtodataset (but i'm new to linq). About new features of the application,due to pravious experiences, the only thing i wish is not to be obliged to propagate changes over the whole application, even if it's simple. that are the reasons i've thougth to design patterns (note i've said "if it's the case" in my question) . I'll KISS it and then will refactor it if needed , as suggested by ladislav mrnka, but i still appreciate any suggestion on how to keep opened to extension the data gathering class
2010/08/30
[ "https://Stackoverflow.com/questions/3599278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
KISS - keep it simple and stupid. You have five days. Create working application and if you have time refactor it to some better solution.
14,055,690
can i get the whole `linearlayout` or other layouts converted to bitmap. my code is this : ``` LinearLayout view = (LinearLayout)findViewById(R.id.linear_parent); view.setDrawingCacheEnabled(true); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); ByteArrayOutputStream bytes = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 40, bytes); ``` the problem is if layout is larger than the screen size only i get whats on screen & not the whole contents e.g. textview etc. which are currently not on screen but are part of layout. Any suggestions geeks out there. this is way to urgent and important.
2012/12/27
[ "https://Stackoverflow.com/questions/14055690", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1882012/" ]
After lot of googling, I found a good solution of my problem ``` TextView textView =new TextView(this); SpannableStringBuilder ssb = new SpannableStringBuilder( "Here's a smiley how are you " ); Bitmap smiley = BitmapFactory.decodeResource( getResources(), R.drawable.movie_add ); ssb.setSpan( new ImageSpan( smiley ), ssb.length()-1, ssb.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE ); textView.setText( ssb, BufferType.SPANNABLE ); ``` **With the help of above code, you can add image any where in Textview.**
16,326,527
Windows 7, Java jdk1.6.0\_32, Ant 1.9 User & System variables: **JAVA\_HOME**:C:\Program Files\Java\jdk1.6.0\_32 **PATH**:C:\Program Files\Java\jdk1.6.0\_32;c:\ant\bin; ``` ANT_HOME:c:\ANT Run command prompt as administrator Microsoft Windows [Version 6.1.7601] Copyright (c) 2009 Microsoft Corporation. All rights reserved. H:\>c: C:\>w: W:\>cd webadvisor W:\WebAdvisor>cd wasql* W:\WebAdvisor\WASQLTEST3>c:\ant\bin\ant Buildfile: W:\WebAdvisor\WASQLTEST3\build.xml init: prepare: [echo] Preparing Update... [copy] Copying 208 files to W:\WebAdvisor\WASQLTEST3\temp [copy] Copying 129 files to W:\WebAdvisor\WASQLTEST3\temp [copy] Copying 49 files to W:\WebAdvisor\WASQLTEST3\temp splitdocs: merge-cleanup: [delete] Deleting: W:\WebAdvisor\WASQLTEST3\custom\WEB-INF\web.xml findwebxml: merge: datatelxmloverride: mergeDefault: BUILD FAILED W:\WebAdvisor\WASQLTEST3\build.xml:112: The following error occurred while executing this line: W:\WebAdvisor\WASQLTEST3\build.xml:165: The following error occurred while executing this line: W:\WebAdvisor\WASQLTEST3\build.xml:173: java.lang.NoClassDefFoundError: org/apache/xml/serialize/OutputFormat at org.codehaus.cargo.module.webapp.WebXmlIo.writeWebXml(WebXmlIo.java:256) at org.codehaus.cargo.module.webapp.WebXmlIo.writeWebXml(WebXmlIo.java:225) at org.apache.cactus.integration.ant.WebXmlMergeTask.execute(WebXmlMergeTask.java:120) at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:291) at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source) at ```
2013/05/01
[ "https://Stackoverflow.com/questions/16326527", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1985765/" ]
Your class path is missing the required jar for ``` org/apache/xml/serialize/OutputFormat ``` Check if you have `xercesImpl.jar` in your classpath **EDIT** : This you can set by including the required jars in ant compile target and put all the required jars in the lib folder. ``` <target name="compile" depends="" description="compile the java source files"> <javac srcdir="." destdir="${build}"> <classpath> <fileset dir="${lib}"> <include name="**/*.jar" /> </fileset> </classpath> </javac> ```
8,798,985
I have encountered a problem of socket communication on linux system, the communication process is like below: client send a message to ask the server to do a compute task, and wait for the result message from server after the task completes. But the client would hangs up to wait for the result message if the task costs a long time such as about 40 minutes even though from the server side, the result message has been written to the socket to respond to the client, but it could normally receive the result message if the task costs little time, such as one minute. Additionally, this problem only happens on customer environment, the communication process behaves normally in our testing environment. I have suspected the cause to this problem is the default timeout value of socket is different between customer environment and testing environment, but the follow values are identical on these two environment, and both Client and server. ``` getSoTimeout:0 getReceiveBufferSize:43690 getSendBufferSize:8192 getSoLinger:-1 getTrafficClass:0 getKeepAlive:false getTcpNoDelay:false ``` the codes on CLient are like: ``` Message msg = null; ObjectInputStream in = client.getClient().getInputStream(); //if no message readObject() will hang here while ( true ) { try { Object recObject = in.readObject(); System.out.println("Client received msg."); msg = (Message)recObject; return msg; }catch (Exception e) { e.printStackTrace(); return null; } } ``` the codes on server are like, ``` ObjectOutputStream socketOutStream = getSocketOutputStream(); try { MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile ); socketOutStream.writeObject(msgJobComplete); }catch(Exception e) { e.printStackTrace(); } ``` in order to solve this problem, i have added the flush and reset method, but the problem still exists: ``` ObjectOutputStream socketOutStream = getSocketOutputStream(); try { MessageJobComplete msgJobComplete = new MessageJobComplete(reportFile, outputFile ); socketOutStream.flush(); logger.debug("AbstractJob#reply to the socket"); socketOutStream.writeObject(msgJobComplete); socketOutStream.reset(); socketOutStream.flush(); logger.debug("AbstractJob#after Flush Reply"); }catch(Exception e) { e.printStackTrace(); logger.error("Exception when sending MessageJobComplete."+e.getMessage()); } ``` so do anyone knows what the next steps i should do to solve this problem. I guess the cause is the environment setting, but I do not know what the environment factors would affect the socket communication? And the socket using the Tcp/Ip protocal to communicate, the problem is related with the long time task, so what values about tcp would affect the timeout of socket communication? After my analysis about the logs, i found after the message are written to the socket, there were no exceptions are thrown/caught. But always after 15 minutes, there are exceptions in the objectInputStream.readObject() codes snippet of Server Side which is used to accept the request from client. However, socket.getSoTimeout value is 0, so it is very strange that the a Timed out Exception was thrown. ``` {2012-01-09 17:44:13,908} ERROR java.net.SocketException: Connection timed out at java.net.SocketInputStream.socketRead0(Native Method) at java.net.SocketInputStream.read(SocketInputStream.java:146) at sun.security.ssl.InputRecord.readFully(InputRecord.java:312) at sun.security.ssl.InputRecord.read(InputRecord.java:350) at sun.security.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:809) at sun.security.ssl.SSLSocketImpl.readDataRecord(SSLSocketImpl.java:766) at sun.security.ssl.AppInputStream.read(AppInputStream.java:94) at sun.security.ssl.AppInputStream.read(AppInputStream.java:69) at java.io.ObjectInputStream$PeekInputStream.peek(ObjectInputStream.java:2265) at java.io.ObjectInputStream$BlockDataInputStream.peek(ObjectInputStream.java:2558) at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2568) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1314) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:368) ``` so why the Connection Timed out exceptions are thrown?
2012/01/10
[ "https://Stackoverflow.com/questions/8798985", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1124954/" ]
This problem is solved. using the `tcpdump` to capture the messages flows. I have found that while in the application level, `ObjectOutputStream.writeObject()` method was invoked, in the tcp level, many times `[TCP ReTransmission]` were found. So, I concluded that the connection is possibly be dead, although using the `netstat -an` command the tcp connection state still was `ESTABLISHED`. So I wrote a testing application to periodically sent Testing messages as the heart-beating messages from the Server. Then this problem disappeared.
70,973,755
iOS 15 Swift 5.5 Trying to understand preferences, but struggling with GeometryReader I crafted this code reading a tutorial, but it doesn't work correctly. The green box should appear over the red dot, the first one. But it is over the centre one. When I tap on the dot, it moves to the third...it feels like SwiftUI drew the whole thing and then changed its mind about the coordinates. Sure I could change the offsets, but that is a hack. Surely SwiftUI should be updating the preferences if the thing moves. ``` import SwiftUI struct ContentView: View { @State private var activeIdx: Int = 0 @State private var rects: [CGRect] = Array<CGRect>(repeating: CGRect(), count: 12) var body: some View { ZStack { RoundedRectangle(cornerRadius: 15).stroke(lineWidth: 3.0).foregroundColor(Color.green) .frame(width: rects[activeIdx].size.width, height: rects[activeIdx].size.height) .offset(x: rects[activeIdx].minX, y: rects[activeIdx].minY) HStack { SubtleView(activeIdx: $activeIdx, idx: 0) SubtleView(activeIdx: $activeIdx, idx: 1) SubtleView(activeIdx: $activeIdx, idx: 2) } .animation(.easeInOut(duration: 1.0), value: rects) }.onPreferenceChange(MyTextPreferenceKey.self) { preferences in for p in preferences { self.rects[p.viewIdx] = p.rect print("p \(p)") } }.coordinateSpace(name: "myZstack") } } struct SubtleView: View { @Binding var activeIdx:Int let idx: Int var body: some View { Circle() .fill(Color.red) .frame(width: 64, height: 64) .background(MyPreferenceViewSetter(idx: idx)) .onTapGesture { activeIdx = idx } } } struct MyTextPreferenceData: Equatable { let viewIdx: Int let rect: CGRect } struct MyTextPreferenceKey: PreferenceKey { typealias Value = [MyTextPreferenceData] static var defaultValue: [MyTextPreferenceData] = [] static func reduce(value: inout [MyTextPreferenceData], nextValue: () -> [MyTextPreferenceData]) { value.append(contentsOf: nextValue()) } } struct MyPreferenceViewSetter: View { let idx: Int var body: some View { GeometryReader { geometry in Rectangle() .fill(Color.clear) .preference(key: MyTextPreferenceKey.self, value: [MyTextPreferenceData(viewIdx: self.idx, rect: geometry.frame(in: .named("myZstack")))]) } } } ``` Tried moving the onPreferences up a level, down a level..attaching it to each view... but still doesn't update...what did I miss here=
2022/02/03
[ "https://Stackoverflow.com/questions/70973755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3069232/" ]
This is an example using `AsyncValue` - It eliminates the `repository` Have your service.dart file like this: ``` final blogServiceProvider = Provider<BlogService>((ref) => BlogService()); class BlogService { Future<AsyncValue<List<BlogPost>>> getBlogPost() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/'); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); return AsyncData(list); } catch (e) { return AsyncError("Something went wrong"); } } } ``` And your provider like so: ``` final blogNotifierProvider = StateNotifierProvider<BlogNotifier, AsyncValue<List<BlogPost>>>((ref){ BlogService _service = ref.read(blogServiceProvider); return BlogNotifier(_service); }); class BlogNotifier extends StateNotifier<AsyncValue<List<BlogPost>>> { BlogNotifier(this._service) : super(AsyncLoading()) { getPosts(); } final BlogService _service; void getPosts() async { state = await _service.getBlogPost(); } } ``` Edit: To merge existing posts with new ones, try this: ``` class BlogService { List<BlogPost> _posts = []; Future<AsyncValue<List<BlogPost>>> getBlogPost() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/'); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); _posts = list; return AsyncData(list); } catch (e) { return AsyncError("Something went wrong"); } } Future<AsyncValue<List<BlogPost>>> morePosts() async { try { var dio = Dio(); Response response = await dio.get('https://wordpress-site.com/wp-json/wp/v2/posts/?offset=' + length.toString()); var posts = (response.data as List); List<BlogPost> list = posts.map<BlogPost>((post) => BlogPost.fromJson(post)).toList(); _posts.addAll(list); return AsyncData(_posts); } catch (e) { return AsyncError("Something went wrong"); } } } ``` And the notifier class would be: ``` class BlogNotifier extends StateNotifier<AsyncValue<List<BlogPost>>> { BlogNotifier(this._service) : super(AsyncLoading()) { getPosts(); } final BlogService _service; void getPosts() async { state = await _service.getBlogPost(); } void morePosts() async { state = await _service.morePosts(); } } ```
2,727,480
Let $(D,\prec) $ be a directed set. Is there a "cofinal chain" in $D $? By chain I mean a $D'\subset D $ such that for all $\lambda,\gamma \in D'$, then $\lambda\prec \gamma $ or $\gamma\prec \lambda $. By cofinal chain I mean a chain $D'$ for which, for every $\gamma\in D $, there is some $\lambda \in D'$ such that $\gamma\prec \lambda $.
2018/04/08
[ "https://math.stackexchange.com/questions/2727480", "https://math.stackexchange.com", "https://math.stackexchange.com/users/177211/" ]
Take $X$ to be your favorite uncountable set. Now take $D$ to be the finite subsets of $X$, ordered by inclusion. Easily, this set is directed. But there are no chains with order type longer than $\omega$, and so no chain can have an uncountable union, and in particular, no chain is cofinal. (If you choose $X$ wisely, then no choice is needed either. And by wisely I just mean not a countable union of finite sets.)
46,774,880
I must be doing something wrong, but the following commented code returns false. Note that WP is returning 'admin' as the 'user\_login', but when that user\_login is used for the `get_user_by()` function it simply returns false. Am I missing something? ``` $user = get_userdata(1); // (admin ID is 1) var_dump($user->user_login); // string(5) 'admin' var_dump(get_user_by('user_login', $user->user_login)); // bool(false) ``` I am running WordPress 4.8.2
2017/10/16
[ "https://Stackoverflow.com/questions/46774880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5433458/" ]
I believe you'll need to use "login" rather by "user\_login" in the get\_user\_by call. See the posssible accepted values of the function here: <https://developer.wordpress.org/reference/functions/get_user_by/>
3,098,881
Ive looked and tried but I can't find an answer. In PHP, is it possible to call a class' member function (when that class requires a constructor to receive parameters) without instantiating it as an object? A code example (which gives errors): ``` <?php class Test { private $end=""; function __construct($value) { $this->end=$value; } public function alert($value) { echo $value." ".$this->end; } } //this works: $example=new Test("world"); $example->alert("hello"); //this does not work: echo Test("world")::alert("hello"); ?> ```
2010/06/23
[ "https://Stackoverflow.com/questions/3098881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/373039/" ]
Unfortunately PHP doesn't have support to do this, but you are a creative and look guy :D You can use an "factory", sample: ``` <?php class Foo { private $__aaa = null; public function __construct($aaa) { $this->__aaa = $aaa; } public static function factory($aaa) { return new Foo($aaa); } public function doX() { return $this->__aaa * 2; } } Foo::factory(10)->doX(); // outputs 20 ```
49,148,842
I am working on a show page based on the `match.params` from react router 4. For some reason, some functions runs 3 times which gives me the first 2 times undefined and the third time the result I want. So I have this Show component which have the props "projects" from the main component. In this show component I do a find function on the array with the props projects inside of it. This must return a 1 item with the `project.id` equel to `match.params.id`. This is going good, and If I visit the page by clicking on a button (through the application) I get the page with the right project and properties (e.g. `project.name`). But If I do a reload or visit the page by using an url in the browser, I get an error saying property name is undefined. If I look in the console I see that my console.logs are fired 3 times. Like I said, the first 2 are undefined and the third is giving me the result I want. I guess the first 2 are resulting in the error I get. My Show component ``` import React from 'react' import { Button } from 'reactstrap' const Show = ({match, projects}) => { let project = projects.find((project) => { //Return project with the id equel to the match.params.id return project.id == match.params.id; }); //Both these console.logs runs 3 times when visiting a link by url console.log(project); //this one gives me 2 times undefined, third time is the right item console.log(match.params.id) return( <div className="container p-40"> <div className="projects-header"> {/* If I echo project.name it will gives me 'cannot read property 'name' of undefined' */} <h2>Project '{match.params.id}' {/* {project.name} */}</h2> <Button className="btn btn-primary" onClick={() => console.log('save')}>Save</Button> </div> <div className="project-edit"> </div> </div> ); }; export default Show; ``` The route in the parent component ``` <Route exact path="/projects/show/:id" render={(props) => <Show {...props} projects={this.state.projects} />} /> ``` Someone with a good solution for this problem? I find it a problem that my users can't route by the url. I don't know why my show component fires 3 times either by url/reload. Edit (Added parent component): ``` //Import react import React, { Component } from 'react'; //Import custom components import Sidebar from './components/js/Sidebar' import Dashboard from './components/js/Dashboard' import Projects from './components/js/Projects' import Show from './components/js/projects/Show' //Import styles import './App.css'; //3rd party deps import { BrowserRouter as Router, Route } from "react-router-dom"; import axios from 'axios' class App extends Component { constructor() { super(); this.state = { //Times / Time tracking times: [], timer: false, currentTimer: 0, //Current task currentTask: { id: 3, title: '', project_id: { id: '', name: '', color: '' }, date: '', time_total: '' }, //Projects projects: [] } this.addTask = this.addTask.bind(this); this.startTimer = this.startTimer.bind(this); this.stopTimer = this.stopTimer.bind(this); this.addProject = this.addProject.bind(this); } addTask = (task) => { let newArray = this.state.times.slice(); newArray.push(task); this.setState({times: newArray, currentTimer: 0, timer: false}); clearInterval(this.timerID); } addProject = (project) => { let newArray = this.state.projects.slice(); newArray.push(project); this.setState({ projects: newArray }); } startTimer() { let sec = this.state.currentTimer; const start = Date.now(); this.setState({ timer: true }); this.timerID = setInterval(() => { let time = new Date() - (start - sec * 1000); this.setState({ currentTimer: Math.round(time / 1000)}); }, 1000); } stopTimer() { this.setState({ timer: false }); console.log('stopped'); clearInterval(this.timerID); //Clear interval here } componentDidMount() { // Make a request for a user with a given ID axios.get('/Sample.json') .then((response) => { this.setState({times: response.data}); }); axios.get('/Projects.json') .then((response) => { this.setState({projects: response.data}); }); } render() { return ( <Router> <div className="page-wrapper"> <Sidebar /> <Route exact path="/" render={() => <Dashboard times={this.state.times} timer={this.state.timer} startTimer={this.startTimer} stopTimer={this.stopTimer} currentTimer={this.state.currentTimer} addTask={this.addTask} />} /> <Route exact path="/projects" render={() => <Projects projects={this.state.projects} addProject={this.addProject} />} /> <Route exact path="/projects/show/:id" render={(props) => <Show {...props} projects={this.state.projects} />} /> </div> </Router> ); } } export default App; ```
2018/03/07
[ "https://Stackoverflow.com/questions/49148842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5503094/" ]
Without altering the order of your data, we can do the following: ``` import pandas as pd from io import StringIO data = StringIO('''id,user,timestamp,song 0,user_000001,05-05-09 12:08,The Start of Something 1,user_000001,04-05-09 14:54,My Sharona 2,user_000001,04-05-09 14:52,Caught by the river 3,user_000001,04-05-09 14:42,Swim 19,user_000001,03-05-09 15:56,Cover me 20,user_000001,03-05-09 15:50,Oh Holy Night 1048550,user_000050, 25-01-07 8:51,I Hung My Head 1048551,user_000050, 25-01-07 8:48,Slider 1048552,user_000050,24-01-07 22:57,Joy 1048553,user_000050,24-01-07 22:53,Crazy Eights 1048554,user_000050,24-01-07 22:48,Steady State 1048555,user_000050,24-01-07 22:42,Maple Leaves (7" Version)''') def time_elapsed(grp, session_length): grp['MinsElapsed'] = (grp['timestamp'] - grp['timestamp'].shift(-1)) / pd.Timedelta(minutes=1) grp['Session'] = (grp['MinsElapsed'] > session_length)[::-1].astype(int).cumsum()[::-1] return grp df = pd.read_csv(data) df['timestamp'] = pd.to_datetime(df['timestamp']) df = df.groupby('user').apply(time_elapsed, session_length=20) print(df) ``` We group by user, and work out the time difference between the row below (`.shift(-1)`) in minutes. We then check if this column returns a value larger than the session length, convert that to an integer and apply a cumulative sum. As the times are in descending order, to get this to work properly we have to reverse the entire column before doing the cumulative sum, and then reset it afterwards. This gives us: ``` id user timestamp song MinsElapsed Session 0 0 user_000001 2009-05-05 12:08:00 The Start of Something 43034.0 2 1 1 user_000001 2009-04-05 14:54:00 My Sharona 2.0 1 2 2 user_000001 2009-04-05 14:52:00 Caught by the river 10.0 1 3 3 user_000001 2009-04-05 14:42:00 Swim 44566.0 1 4 19 user_000001 2009-03-05 15:56:00 Cover me 6.0 0 5 20 user_000001 2009-03-05 15:50:00 Oh Holy Night NaN 0 6 1048550 user_000050 2007-01-25 08:51:00 I Hung My Head 3.0 1 7 1048551 user_000050 2007-01-25 08:48:00 Slider 591.0 1 8 1048552 user_000050 2007-01-24 22:57:00 Joy 4.0 0 9 1048553 user_000050 2007-01-24 22:53:00 Crazy Eights 5.0 0 10 1048554 user_000050 2007-01-24 22:48:00 Steady State 6.0 0 11 1048555 user_000050 2007-01-24 22:42:00 Maple Leaves (7" Version) NaN 0 ``` **EDIT:** To get the first and last times on songs in the session and the length of the session, we can do the following: ``` session_length = df.groupby(['user', 'Session'])['timestamp'] \ .agg(['min', 'max']) \ .reset_index() session_length['Length (mins)'] = (session_length['max'] -session_length['min']) / pd.Timedelta(minutes=1) ``` Which gives us: ``` user Session min max Length (mins) 0 user_000001 0 2009-03-05 15:50:00 2009-03-05 15:56:00 6.0 1 user_000001 1 2009-04-05 14:42:00 2009-04-05 14:54:00 12.0 2 user_000001 2 2009-05-05 12:08:00 2009-05-05 12:08:00 0.0 3 user_000050 0 2007-01-24 22:42:00 2007-01-24 22:57:00 15.0 4 user_000050 1 2007-01-25 08:48:00 2007-01-25 08:51:00 3.0 ```
30,669,015
I have a tkinter 'Text' and 'Scrollbar' working fine. In my program in the text window automatically lines will keep on adding. So When a new line of text is inserted and data reached out of limit I would like the text and scrollbar to be scrolled to the bottom automatically, so that the latest line of text is always shown. How to do this? Also how to link the scroll of text window and scroll bar, because when I do scrolling over the text window scroll wont happen. Only way I observed is to drag the scroll bar. ``` scrollbar = Tkinter.Scrollbar(group4.interior()) scrollbar.pack(side = 'right',fill='y') Details1 = Output() outputwindow = Tkinter.Text(group4.interior(), yscrollcommand = scrollbar.set,wrap = "word",width = 200,font = "{Times new Roman} 9") outputwindow.pack( side = 'left',fill='y') scrollbar.config( command = outputwindow.yview ) outputwindow.yview('end') outputwindow.config(yscrollcommand=scrollbar.set) outputwindow.insert('end',Details1) ``` In the program the function output() will continuously send data, which should scroll Thanks in advance,
2015/06/05
[ "https://Stackoverflow.com/questions/30669015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4946244/" ]
You can cause the text widget to scroll to any location with the `see` which takes an index. For example, to make the last line of the widget visible you can use the index `"end"`: ``` outputwindow.see("end") ``` Here's a complete working example: ``` import time try: # python 2.x import Tkinter as tk except ImportError: # python 3.x import tkinter as tk class Example(tk.Frame): def __init__(self, *args, **kwargs): tk.Frame.__init__(self, *args, **kwargs) self.text = tk.Text(self, height=6, width=40) self.vsb = tk.Scrollbar(self, orient="vertical", command=self.text.yview) self.text.configure(yscrollcommand=self.vsb.set) self.vsb.pack(side="right", fill="y") self.text.pack(side="left", fill="both", expand=True) self.add_timestamp() def add_timestamp(self): self.text.insert("end", time.ctime() + "\n") self.text.see("end") self.after(1000, self.add_timestamp) if __name__ == "__main__": root =tk.Tk() frame = Example(root) frame.pack(fill="both", expand=True) root.mainloop() ```
30,591,025
I have a problem similar to this one: [SFINAE tried with bool gives compiler error: "template argument ‘T::value’ involves template parameter"](https://stackoverflow.com/questions/7776448/sfinae-tried-with-bool-gives-compiler-error-template-argument-tvalue-invol) I want to define a trait that tells if a complex representation is an array of structs, where real values are never AoS hence no user defined specilization should be required, but for complex you'd always need one: ``` /** * Evaluates to a true type if the given complex type is an Array of Structs, false otherwise * Defaults to false for Real values */ template< typename T, bool T_isComplex = IsComplex<T>::value > struct IsAoS: std::false_type{}; /** * Undefined for (unknown) complex types */ template< typename T > struct IsAoS< T, true >; ``` Specializations are done in the std-way by deriving from std::true/false\_type. The problem is: With this implementation I get the "template argument involves template parameter(s)" error (which is explained in the linked question) but if i switch to types (ommit "::value" in first template and change true to true\_type in 2nd) Complex types won't match the 2nd template anymore because the only derive from std::true\_type and ARE NOT std::true\_type. Only solution I can think of is using expression SFINAE and change the 2nd parameter of the main template to default void and an enable\_if for the real case (isComplex==false). Anything better?
2015/06/02
[ "https://Stackoverflow.com/questions/30591025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1930508/" ]
On the assumption that `IsAoS<T>`'s desired behavior is: * If `IsComplex<T>::value` is `false`, it defaults to `false_type`; * Otherwise, it is an error unless the user provides a specialization. It's straightforward to implement with a `static_assert`; no default template argument needed: ``` template< typename T > struct IsAoS: std::false_type { static_assert(!IsComplex<T>::value, "A user specialization must be provided for Complex types"); }; ``` --- If you want the default argument trickery, just use a wrapper layer: ``` namespace detail { template< typename T, bool T_isComplex = IsComplex<T>::value > struct IsAoS_impl: std::false_type{}; /** * Undefined for (unknown) complex types */ template< typename T > struct IsAoS_impl< T, true >; } template<class T> struct IsAoS : detail::IsAoS_impl<T> {}; ``` Users should just specialize `IsAoS`.
34,481,610
I'm working on an iOS app, that should work fine with both iphones and ipads. As I know we can build the app as universal or convert iphone storyboard into ipad storyboard.What I want to know is, what is the best way from these and, when we launch app to app store, is it a problem to have two storyboards one for iphone and another for ipad.
2015/12/27
[ "https://Stackoverflow.com/questions/34481610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5680499/" ]
You can do a linear search with steps that are often greater than 1. The crucial observation is that if e.g. `array[i] == 4` and 7 hasn't yet appeared then the next candidate for 7 is at index `i+3`. Use a while loop which repeatedly goes directly to the next viable candidate. Here is an implementation, slightly generalized. It finds the first occurrence of `k` in the array (subject to the +=1 restriction) or `-1` if it doesn't occur: ``` #include <stdio.h> #include <stdlib.h> int first_occurence(int k, int array[], int n); int main(void){ int a[] = {4,3,2,3,2,3,4,5,4,5,6,7,8,7,8}; printf("7 first occurs at index %d\n",first_occurence(7,a,15)); printf("but 9 first \"occurs\" at index %d\n",first_occurence(9,a,15)); return 0; } int first_occurence(int k, int array[], int n){ int i = 0; while(i < n){ if(array[i] == k) return i; i += abs(k-array[i]); } return -1; } ``` output: ``` 7 first occurs at index 11 but 9 first "occurs" at index -1 ```
698,478
I have to run Mac OS on virtual box for a class and it keeps giving me errors stating "VT-x/AMD-V hardware acceleration not available on your system. Certain guests (e.g. OS/2 and QNX) require this feature and will fail to boot without it." If there is a solution, I am not used to windows 8.1 and will need detailed instructions on how to fix it. Thank you
2014/01/08
[ "https://superuser.com/questions/698478", "https://superuser.com", "https://superuser.com/users/287753/" ]
Do you have Hyper-V installed? For example it may have been added if you installed the Windows Phone emulators which come with Visual Studio 2012 & 2013. If so, then there is a known conflict between Hyper-V and VirtualBox - [Hardware Virtualisation support not detected if Hyper-V installed](https://www.virtualbox.org/ticket/12350). A similar problem occurs trying to use Intel HAXM to accelerate Android x86 Virtual Devices - [Windows 8 - How to install Intel HAXM after installing Hyper-V](http://forums.ouya.tv/discussion/82/windows-8-how-to-install-intel-haxm-after-installing-hyper-v). Uninstalling the Windows Phone emulators and turning Hyper-V off in `Control Panel >> Programs and Features >> Turn Windows features on or off` seems to be the only workaround for the moment.
10,315,793
Okay, you may call me a noob but I'm realling confused. My ex classmate paid me to write a program in C. She gave me the task and it said something like "blah blah blah make at least TWO CLASSES, write at least ONE CONSTRUCTOR and rewrite at least ONE METHOD" it says that word by word. And then I told her "this is C++ not C" she said "but we're learning C" I ignored it and wrote the program in c++ and sent to her as I thought she didn't know what she was talking about. She said "it doesn't work on code blocks, and wtf is cout <<" and then she sent me a chunk of code that they write and instead of cout and cin there was printf and scanf. It had to be C. So, I rewrote the program with printf and scanf and she still says codeblocks throw errors (I still left classes as task demanded). I want to ask wtf? Does C have classes? Or is there a misunderstanding or something? EDIT: I've come back to the question after so many years and noticed some a\*\*\*\*\*es took time to remove 99% text from the question. Get a life, this is not 1984 yet.
2012/04/25
[ "https://Stackoverflow.com/questions/10315793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1289097/" ]
No, C doesn't have classes. That said, there are ways of simulating object-oriented programming in C - a quick Google search should yield some useful results.
80,774
I recently switched to a new PC at work, one with two (identical, Dell 23") monitors. I'm running Linux Mint 15 64bit / Cinnamon. Is there a way to set it up in such a way that, instead of both monitors sharing the same huge workspace, they are on separate smaller ones? E.g. left monitor on workspace 1, right monitor on workspace 2, and I could switch either monitor to workspace 3 if needed? Failing that, is there a way to duplicate the bottom panel onto the second monitor? Currently it is only displayed on the left one.
2013/06/26
[ "https://unix.stackexchange.com/questions/80774", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/41904/" ]
Short answer: yes, you can do this. I have my (Fedora) desktop set up this way, each monitor is an independent display. It is the same 'desktop', in the X sense, but there are some limitations to typical desktop functionality with this setup versus the 'single desktop spread over two monitors' configuration. [For example, you can't drag a window from one monitor to the other, or even drag a file from a folder on one monitor and drop it in a folder displayed on the other monitor.] Still, I prefer independent displays. For me it is natural to cycle workspaces on one monitor independently of the workspace displayed on the other monitor. I will warn you - some people are pretty zealous about which way is the 'correct way', so prepare to wade through a lot of noise and ranting if you research how to do what you want to do. I have had many people dismiss my efforts to achieve this setup because they felt it was pointless and "no sane person would want things to work that way". As another user has pointed out, some desktop environments support independent displays and others do not. I was happily using Gnome as my desktop, for ten years or more, until the 3.0 series of Gnome (which lost the capability to support independent X displays on a single desktop ... and it appears that the Gnome development community do not have an interest in resurrecting this capability). Earlier versions of Cinnamon Desktop had this capability, but with Fedora 19 or 20 I can longer achieve it with Cinnamon. I am stuck with Xfce at the moment. In order to achieve independent X displays, I had to carefully craft an xorg.conf file. For my hardware, using the proprietary nvidia driver, the key seems to be to identify multiple Devices using the same BusID, but to then use the 'metamodes' option for each Screen section to uniquely identify the port associated with each monitor in your setup. Here is my xorg.conf: ``` Section "ServerLayout" Identifier "Layout0" Screen 0 "Screen0" 0 0 Screen 1 "Screen1" RightOf "Screen0" InputDevice "Keyboard0" "CoreKeyboard" InputDevice "Mouse0" "CorePointer" Option "Xinerama" "0" EndSection Section "Files" FontPath "/usr/share/fonts/default/Type1" EndSection Section "InputDevice" # generated from default Identifier "Mouse0" Driver "mouse" Option "Protocol" "auto" Option "Device" "/dev/input/mice" Option "Emulate3Buttons" "no" Option "ZAxisMapping" "4 5" EndSection Section "InputDevice" # generated from default Identifier "Keyboard0" Driver "kbd" EndSection Section "Monitor" Identifier "Monitor0" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device0" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 0 EndSection Section "Screen" Identifier "Screen0" Device "Device0" Monitor "Monitor0" Option "TwinView" "0" Option "metamodes" "DFP-0: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection Section "Monitor" Identifier "Monitor1" VendorName "DELL" ModelName "P2411Hb" HorizSync 28.0 - 33.0 VertRefresh 43.0 - 72.0 Option "DPMS" EndSection Section "Device" Identifier "Device1" Driver "nvidia" VendorName "NVIDIA Corporation" BoardName "Quadro K2000M" BusID "PCI:1:0:0" Screen 1 EndSection Section "Screen" Identifier "Screen1" Device "Device1" Monitor "Monitor1" Option "TwinView" "0" Option "metamodes" "DFP-2: nvidia-auto-select +0+0" DefaultDepth 24 SubSection "Display" Depth 24 EndSubSection EndSection ``` Hopefully that gets you started. I have not found a gui tool in any Desktop Environment that reliably creates an xorg.conf supporting independent displays. My advice is to start with any 'X configuration generator' tool that comes with your chosen video driver (for example, nvidia's `nvidia-xconfig`) and see if you can use my example, above, to guide your trial-and-error.
42,440,070
I have this problem: The GridView I has in the view (shown below) is too long that it doesn't fit entirely in the screen, maybe because one value parameter is too long, and it doesn't follow the text down. This this a screenshot for the GridView: [![enter image description here](https://i.stack.imgur.com/HPKAh.png)](https://i.stack.imgur.com/HPKAh.png) And this the code for the GridView ``` <?php Pjax::begin(); ?> <?= GridView::widget([ 'dataProvider' => $dataProvider, 'filterModel' => $searchModel, 'columns' => [ ['class' => 'yii\grid\SerialColumn'], 'fecha', 'nombreSesion', 'objetivosPlanificacion:ntext', ['class' => 'yii\grid\ActionColumn'], ], ]); ?> <?php Pjax::end(); ?> ```
2017/02/24
[ "https://Stackoverflow.com/questions/42440070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7575968/" ]
`java` **doesn't** supports multiple inheritance. What you are doing is implementing an `interface`. **You can't extend multiple classes in `java` but you can implement multiple interfaces**. An interface is a reference type and it is similar to class. It is a collection of abstract methods. A class implements an interface, thereby inheriting the abstract methods of the interface. An interface may also contain constants, default methods, static methods, and nested types. Method bodies exist only for default methods and static methods. A class describes the attributes and behaviors of an object and an interface contains behaviors that a class implements. For more on `interface`, [click here](https://docs.oracle.com/javase/tutorial/java/concepts/interface.html)
22,532,019
I adapted the following code found [here](http://pythonexcels.com/automating-pivot-tables-with-python/) to create a pivot table in my existing excel sheet: ``` import win32com.client as win32 win32c = win32.constants import sys import itertools tablecount = itertools.count(1) def addpivot(wb,sourcedata,title,filters=(),columns=(), rows=(),sumvalue=(),sortfield=""): newsheet = wb.Sheets.Add() newsheet.Cells(1,1).Value = title newsheet.Cells(1,1).Font.Size = 16 tname = "PivotTable%d"%tablecount.next() pc = wb.PivotCaches().Add(SourceType=win32c.xlDatabase, SourceData=sourcedata) pt = pc.CreatePivotTable(TableDestination="%s!R4C1"%newsheet.Name, TableName=tname, DefaultVersion=win32c.xlPivotTableVersion10) for fieldlist,fieldc in ((filters,win32c.xlPageField), (columns,win32c.xlColumnField), (rows,win32c.xlRowField)): for i,val in enumerate(fieldlist): wb.ActiveSheet.PivotTables(tname).PivotFields(val).Orientation = fieldc wb.ActiveSheet.PivotTables(tname).PivotFields(val).Position = i+1 wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname). PivotFields(sumvalue),sumvalue,win32c.xlSum) def runexcel(): excel = win32.gencache.EnsureDispatch('Excel.Application') #excel.Visible = True try: wb = excel.Workbooks.Open('18.03.14.xls') except: print "Failed to open spreadsheet 18.03.14.xls" sys.exit(1) ws = wb.Sheets('defaulters') xldata = ws.UsedRange.Value newdata = [] for row in xldata: if len(row) == 4 and row[-1] is not None: newdata.append(list(row)) rowcnt = len(newdata) colcnt = len(newdata[0]) wsnew = wb.Sheets.Add() wsnew.Range(wsnew.Cells(1,1),wsnew.Cells(rowcnt,colcnt)).Value = newdata wsnew.Columns.AutoFit() src = "%s!R1C1:R%dC%d"%(wsnew.Name,rowcnt,colcnt) addpivot(wb,src, title="Employees by leads", filters=("Leads",), columns=(), rows=("Name",), sumvalue="Actual hours", sortfield=()) if int(float(excel.Version)) >= 12: wb.SaveAs('new18.03.14.xlsx',win32c.xlOpenXMLWorkbook) else: wb.SaveAs('new18.03.14.xls') excel.Application.Quit() if __name__ == "__main__": runexcel() ``` This line of code, `wb.ActiveSheet.PivotTables(tname).AddDataField(wb.ActiveSheet.PivotTables(tname).PivotFields(sumvalue),sumvalue,win32c.xlSum)` returns the following error: `pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, u'Microsoft Excel', u'PivotFields method of PivotTable class failed', u'xlmain11.chm', 0, -2146827284), None)`. When I remove that line, the pivot table is generated without any data fields. Is there something I'm doing wrong?
2014/03/20
[ "https://Stackoverflow.com/questions/22532019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3335936/" ]
As this is the one of the first Google hits when searching for Excel pivot tables from Python, I post my example code. This code generates a simple pivot table in Excel through a COM server, with some basic filters, columns, rows, and some number formatting applied. I hope this helps someone not to waste half a day on it (like I did...) ``` import win32com.client Excel = win32com.client.gencache.EnsureDispatch('Excel.Application') # Excel = win32com.client.Dispatch('Excel.Application') win32c = win32com.client.constants wb = Excel.Workbooks.Add() Sheet1 = wb.Worksheets("Sheet1") TestData = [['Country','Name','Gender','Sign','Amount'], ['CH','Max' ,'M','Plus',123.4567], ['CH','Max' ,'M','Minus',-23.4567], ['CH','Max' ,'M','Plus',12.2314], ['CH','Max' ,'M','Minus',-2.2314], ['CH','Sam' ,'M','Plus',453.7685], ['CH','Sam' ,'M','Minus',-53.7685], ['CH','Sara','F','Plus',777.666], ['CH','Sara','F','Minus',-77.666], ['DE','Hans','M','Plus',345.088], ['DE','Hans','M','Minus',-45.088], ['DE','Paul','M','Plus',222.455], ['DE','Paul','M','Minus',-22.455]] for i, TestDataRow in enumerate(TestData): for j, TestDataItem in enumerate(TestDataRow): Sheet1.Cells(i+2,j+4).Value = TestDataItem cl1 = Sheet1.Cells(2,4) cl2 = Sheet1.Cells(2+len(TestData)-1,4+len(TestData[0])-1) PivotSourceRange = Sheet1.Range(cl1,cl2) PivotSourceRange.Select() Sheet2 = wb.Worksheets(2) cl3=Sheet2.Cells(4,1) PivotTargetRange= Sheet2.Range(cl3,cl3) PivotTableName = 'ReportPivotTable' PivotCache = wb.PivotCaches().Create(SourceType=win32c.xlDatabase, SourceData=PivotSourceRange, Version=win32c.xlPivotTableVersion14) PivotTable = PivotCache.CreatePivotTable(TableDestination=PivotTargetRange, TableName=PivotTableName, DefaultVersion=win32c.xlPivotTableVersion14) PivotTable.PivotFields('Name').Orientation = win32c.xlRowField PivotTable.PivotFields('Name').Position = 1 PivotTable.PivotFields('Gender').Orientation = win32c.xlPageField PivotTable.PivotFields('Gender').Position = 1 PivotTable.PivotFields('Gender').CurrentPage = 'M' PivotTable.PivotFields('Country').Orientation = win32c.xlColumnField PivotTable.PivotFields('Country').Position = 1 PivotTable.PivotFields('Country').Subtotals = [False, False, False, False, False, False, False, False, False, False, False, False] PivotTable.PivotFields('Sign').Orientation = win32c.xlColumnField PivotTable.PivotFields('Sign').Position = 2 DataField = PivotTable.AddDataField(PivotTable.PivotFields('Amount')) DataField.NumberFormat = '#\'##0.00' Excel.Visible = 1 wb.SaveAs('ranges_and_offsets.xlsx') Excel.Application.Quit() ```
21,646,093
So I have a many to many relationship between Users and Photos via the pivot table `user_photo`. I use `belongsToMany('Photo')` in my User model. However the trouble here is that I have a dozen columns in my Photo table most I don't need (especially during a json response). So an example would be: ``` //Grab user #987's photos: User::with('photos')->find(987); //json output: { id: 987, name: "John Appleseed", photos: { id: 5435433, date: ..., name: 'feelsgoodman.jpg', ....// other columns that I don't need } } ``` Is it possible to modify this method such that `Photos` model will only return the accepted columns (say specified by an array `['name', 'date']`)? **User.php** ``` public function photos() { return $this->belongsToMany('Photo'); } ``` Note: I only want to select specific columns when doing a `User->belongsToMany->Photo` only. When doing something like `Photo::all()`, yes I would want all the columns as normal. EDIT: I've tried [Get specific columns using "with()" function in Laravel Eloquent](https://stackoverflow.com/questions/19852927/get-specific-columns-using-with-function-in-laravel-eloquent?rq=1) but the columns are still being selected. Also <https://github.com/laravel/laravel/issues/2306>
2014/02/08
[ "https://Stackoverflow.com/questions/21646093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3189288/" ]
You can use belongsToMany with select operation using laravel relationship. ``` public function photos() { return $this->belongsToMany('Photo')->select(array('name', 'date')); } ```
51,581,398
When we are using hive, data is not displayed in perfect table format. Column name and actual data related to column differs in position if the column name is big. How to fix it?
2018/07/29
[ "https://Stackoverflow.com/questions/51581398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10151665/" ]
You specified the condition in `WHERE` clause for the condition that you required ``` DELETE d FROM mytab d WHERE ( d.x1 = 'b' AND d.act = 0 ) OR d.x1 is null ```
15,346,793
Hello :) How do i find out which "count"-id the loaded picture has? The loaded picture is: "df5ddc27f7569f83e3867bec71a2cac0.jpg" And my json are: ``` [ {"count":1,"file":"8b6c5592f0378dc8c56e591a7b147826.jpg"}, {"count":2,"file":"a44618c1afe93be486382ceb38536e02.jpg"}, {"count":3,"file":"3c692942d69fba0d16971e0685f42757.jpg"}, {"count":4,"file":"df5ddc27f7569f83e3867bec71a2cac0.jpg"} ] ``` Has anybody an idea for me?
2013/03/11
[ "https://Stackoverflow.com/questions/15346793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1936309/" ]
Yeah, this should be pretty straightforward. Assuming the two are siblings, you can even do this with CSS. **CSS APPROACH** ``` #site-logo { background-image: url(path/to/non-animated-image); } .login-button { /* Login default CSS here */ } .login-button:active ~ #site-logo { background-image: url(path/to/animated-image.gif); } ``` And then use an animated gif in the `.login-button:active ~ .site-logo` block. Otherwise, you can use jQuery or something similar **jQuery Approach** ``` .login-button.on('click', function(){ $('#site-logo').css('background-image', 'url(path/to/animated-image.gif)'); }); ```
3,442,781
I was using one of my favorite R packages today to read data from a google spreadsheet. It would not work. This problem is occurring on all my machines (I use windows) and it appears to be a new problem. I am using Version: 0.4-1 of RGoogleDocs ``` library(RGoogleDocs) ps <-readline(prompt="get the password in ") sheets.con = getGoogleDocsConnection(getGoogleAuth("[email protected]", ps, service ="wise")) ts2=getWorksheets("OnCall",sheets.con) ``` And this is what I get after running the last line. > > Error in curlPerform(curl = curl, .opts = opts, .encoding = .encoding) : > SSL certificate problem, verify that the CA cert is OK. Details: > error:14090086:SSL routines:SSL3\_GET\_SERVER\_CERTIFICATE:certificate verify failed > > > I did some reading and came across some interesting, but not useful to me at least, information. [When I try to interact with a URL via https, I get an error of the form](http://www.omegahat.org/RCurl/FAQ.html) [Curl: SSL certificate problem, verify that the CA cert is OK](http://ademar.name/blog/2006/04/curl-ssl-certificate-problem-v.html) I got the very big picture message but did not know how to implement the solution in my script. I dropped the following line before getWorksheets. ``` x = getURLContent("https://www.google.com", ssl.verifypeer = FALSE) ``` That did not work so I tried ``` ts2=getWorksheets("OnCall",sheets.con,ssl.verifypeer = FALSE) ``` That also did not work. Interestingly enough, the following line works ``` getDocs(sheets.con,folders = FALSE) ``` What do you suggest I try to get it working again? Thanks.
2010/08/09
[ "https://Stackoverflow.com/questions/3442781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/168139/" ]
I no longer have this problem. I do not quite remember the timeline of exactly when I overcame the problem and cannot remember who helped me get here but here is a typical session which works. ``` library(RGoogleDocs) if(exists("ps")) print("got password, keep going") else ps <-readline(prompt="get the password in ") #conditional password asking options(RCurlOptions = list(capath = system.file("CurlSSL", "cacert.pem", package = "RCurl"), ssl.verifypeer = FALSE)) sheets.con = getGoogleDocsConnection(getGoogleAuth("[email protected]", ps, service ="wise")) #WARNING: this would prevent curl from detecting a 'man in the middle' attack ts2=getWorksheets("name of workbook here",sheets.con) names(ts2) sheet.1 <-sheetAsMatrix(ts2$"Sheet 1",header=TRUE, as.data.frame=TRUE, trim=TRUE) #Get one sheet other <-sheetAsMatrix(ts2$"whatever name of tab",header=TRUE, as.data.frame=TRUE, trim=TRUE) #Get other sheet ``` Does it help you?
46,415,325
Microsoft has some [decent documentation](https://learn.microsoft.com/en-us/microsoft-edge/extensions/guides/debugging-extensions#content-script-debugging) on debugging Content Scripts for an Edge Extension and the top of the page even includes a [Channel 9 video](https://channel9.msdn.com/Blogs/One-Dev-Minute/Debugging-Microsoft-Edge-Extensions) on the subject. Unfortunately, the techniques [no longer seem to work](https://developer.microsoft.com/en-us/microsoft-edge/platform/issues/13829248/), as even when following the debug instructions and using the the [sample Text Swap extension](https://github.com/MicrosoftEdge/MicrosoftEdge-Extensions-Demos), the extension and content script never show up in the debugger. [![Screenshot of Edge running Text Swap extension](https://i.stack.imgur.com/F1ShJ.png)](https://i.stack.imgur.com/F1ShJ.png) As you can see from the screenshot, the content script has run (and changed the font on the page) but it and the extension itself are nowhere to be seen in the debugger. Anyone figured out how to get the content script to show up in the debugger?
2017/09/25
[ "https://Stackoverflow.com/questions/46415325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31629/" ]
The answer is no. You only need one. NPM modules can be incorporated into your code several folders down in your project. Take for example a project folder: ``` /root app.js package.json /public index.html /node_modules ... ``` All modules in the `node-module` folder can be used in any project sub-folder. Say, you have a file named `anotherApp.js` in a folder down the line, it will 'inherit' all node modules installed in any parent folder. Therefore, it will also be able to access every module that is in the project root `node_module` folder. ``` /root /somefoldername /anotherfolder /application anotherApp.js /node_modules ... ``` I should add, that NPM (Node package manager) is there to handle locally installed modules. The `fs` (File System) modules does come with node and is installed as a global, therefore you do not need to install it via NPM. Check out <https://www.npmjs.com/> for a full list of available downloadable modules.
11,200,518
newbie here, so thanks in advance for help! I have a Wordpress site with multiple taxonomies. I'd like to create a very simple form with two select boxes, one for each taxonomy. Then I'd like to use an HTML form with the get method to display posts matching the criteria they requested from the select boxes. I'm able to do this easy enough if each of the two select boxes are filled out, I get a permalink something like: ``` testsite.com/?tax1=value1&tax2=value2 ``` (ugly, I know, but it works). What I can't figure out is what to do if they don't fill out both select boxes. Ideally it would only give the permalink for the one they fill in, so either: ``` testsite.com/?tax1=value1 or testsite.com/?tax2=value2 ``` But instead I'm getting ``` testsite.com/?tax1=value1&tax2=Select+tax ``` here is my HTML ``` <form action="http://www.testsite.com/" method="get"> Season: <select name="season"> <option>Select season</option> <option value="">Select season</option> <option value="spring">Spring</option> <option value="summer">Summer</option> <option value="fall">Fall</option> </select><br/> Vacation type: <select name="vacations"> <option value="">Select vacation type</option> <option value="beach">Beach</option> <option value="ski">Ski</option> </select><br/> <input type="submit" /> </form> ``` I realize the answer is probably simple but I'm banging my head against a wall so any help is very very much appreciated. Thank you!
2012/06/26
[ "https://Stackoverflow.com/questions/11200518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1481578/" ]
**How to get the error EAGAIN?** To get the error EAGAIN, you need to be using Non-Blocking Sockets. With Non-Blocking sockets, you need to write huge amounts of data (and stop receiving data on the peer side), so that your internal TCP buffer gets filled and returns this error. **How to get the error EPIPE?** To get the error EPIPE, you need to send large amount of data after closing the socket on the peer side. You can get more info about EPIPE error from this SO [Link](https://stackoverflow.com/questions/4584904/what-causes-the-broken-pipe-error). I had asked a question about Broken Pipe Error in the link provided and the accepted answer gives a detailed explanation. It is important to note that to get EPIPE error you should have set the flags parameter of send to MSG\_NOSIGNAL. Without that, an abnormal send can generate SIGPIPE signal. **Additional Note** Please note that it is difficult to simulate a write failure, as TCP generally stores the data that you are trying to write into it's internal buffer. So, if the internal buffer has sufficient space, then you won't get an error immediately. The best way is to try to write huge amounts of data. You can also try setting a smaller buffer size for send by using [setsockopt](http://www.manpagez.com/man/2/setsockopt/) function with SO\_SNDBUF option
40,006
I'm trying to chart out a song, just so I have a chord chart to use for comping. It's in 4/4, and most chord changes happen on the strong beats (1 and 3), but there's a couple of places where beat 3 is anticipated (by an 8th note). For reference, the song is "Sultans of Swing" by Dire Straights. Is there any sort of convention used to notate, in this example, that the Bb in measure 16 should be anticipated, rather than played right on beat 3? [![SultansSnip](https://i.stack.imgur.com/Ravs7.gif)](https://i.stack.imgur.com/Ravs7.gif)
2015/12/05
[ "https://music.stackexchange.com/questions/40006", "https://music.stackexchange.com", "https://music.stackexchange.com/users/3404/" ]
(I don't have enough reputation points yet to comment, so I'll make this an answer instead. Will convert to comments on other answers later, or to edits on other answers, once I have enough cred to ask those answers' authors whether they welcome the edit.) I don't see any convention specified in either the "Concise Dictionary of Music" (Wm Collins Sons) or the "Essential Dictionary of Music Notation" (Alfred). Seems like you're on your own to come up with an approach that works best for you. As pointed out in the answer from @Tim, if you're already using staves, then why not jot out just those notes that are pushed, tying them to the downbeat chords to which they push? Or if you want to go with chord notation, maybe just use that same "Ant." abbreviation that you saw in the examples given at <http://www.musicarrangerspage.com/1493/how-to-use-anticipation-in-music/>, not as markings on written-out notes in the staff as they do there, but as stand-alone markings prior to the anticipated chord, e.g. > > Bb     Bb     Dmi     ant. Bb > > >
55,012,413
New to javascript and just trying to make a simple form validation where if the user/pass is valid the box border turns green, and if invalid, it turns red (pictured) [Valid/Invalid](https://i.stack.imgur.com/Qlmd0.png) Here is my HTML: (Form Works, I'm guessing I'm screwing up on the listeners and Handlers) ``` <!DOCTYPE html> <html> <body> <form action="/action_page.php"> <input type="text" name="username" value="Username" minLength="6" maxlength="10" required> <br><br> <input type="text" name="password" value="Password" minLength="8" maxlength="15" required> <br><br> <input type="submit" value="Submit" onclick="function(changeStyle)"> </form> <script src="Script1.js"> </script> </body> </html> ``` Javascript: ``` function valid() { var textElements = document.getElementsByTagName('input'); textElements[i].addEventListener('input', function(changeStyle) { if (event.target.validity.valid) { textElements[i].style.border = "solid green 2px"; textElements[i].style.boxShadow = "0 0 5px green"; } else { textElements[i].style.border = "solid red 2px"; textElements[i].style.boxShadow = "0 0 5px red"; } }, false); } </script> ```
2019/03/05
[ "https://Stackoverflow.com/questions/55012413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8812202/" ]
``` "code": 403, "message": "Daily Limit for Unauthenticated Use Exceeded. Continued use requires signup." } } ``` This means that you have exceeded your limit to serve videos from youtube. You need to create an account to be able to show more videos. If you're sure you haven't exceeded your limit/ have an account double check your developer console that the API is turned on. [Developer Console](https://console.developers.google.com/apis). What I would suggest is to add a `catch` to your call to handle errors in the future. ``` axios .get("https://www.googleapis.com/youtube/v3/search", { params: { keys: API_KEY, type: "video", part: "snippet", q: searchTerm } }) .then(response => console.log(response)); .catch(err => { console.log(err); } ```
69,147,252
``` <img src="https://res.cloudinary.com/dvhhqcxre/image/upload/v1611495185/zenith/tldyffcvvfm9fj51pvjp.jpg"> ``` I want to get rid of the img tag, I just want only the image link
2021/09/11
[ "https://Stackoverflow.com/questions/69147252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13574659/" ]
```js const image = document.querySelector('img') image.outerHTML = image.src ``` ```html <img src="https://res.cloudinary.com/dvhhqcxre/image/upload/v1611495185/zenith/tldyffcvvfm9fj51pvjp.jpg"> ```
8,162,278
**I am getting following errors while deploying GAE application. What will be the reason for that? Stack backtrace below.** ``` Uncaught exception from servlet com.google.apphosting.runtime.HardDeadlineExceededError: This request (0000000000000000) started at 2011/11/17 04:12:01.160 UTC and was still executing at 2011/11/17 04:13:01.204 UTC. at com.google.appengine.runtime.Request.process-0000000000000000(Request.java) at java.lang.ClassLoader.defineClass1(Native Method) at java.lang.ClassLoader.defineClass(ClassLoader.java:634) at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:142) at java.net.URLClassLoader.defineClass(URLClassLoader.java:277) at sun.reflect.GeneratedMethodAccessor5.invoke(Unknown Source) at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.lang.reflect.Method.invoke(Method.java:616) at java.lang.ClassLoader.loadClass(ClassLoader.java:266) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:56) at org.springframework.expression.spel.standard.SpelExpressionParser.doParseExpression(SpelExpressionParser.java:1) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:66) at org.springframework.expression.common.TemplateAwareExpressionParser.parseExpression(TemplateAwareExpressionParser.java:56) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.processMap(ExpressionBasedFilterInvocationSecurityMetadataSource.java:47) at org.springframework.security.web.access.expression.ExpressionBasedFilterInvocationSecurityMetadataSource.<init>(ExpressionBasedFilterInvocationSecurityMetadataSource.java:29) at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:57) at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) at java.lang.reflect.Constructor.newInstance(Constructor.java:33) at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:126) at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:108) at org.springframework.beans.factory.support.ConstructorResolver$1.run(ConstructorResolver.java:274) at java.security.AccessController.doPrivileged(Native Method) at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:272) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1003) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:907) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:485) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:270) at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:125) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1325) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456) at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291) at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288) at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190) at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580) at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895) at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425) at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276) at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197) at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47) at org.mortbay.jetty.handler.ContextHandler.startContext(ContextHandler.java:548) at org.mortbay.jetty.servlet.Context.startContext(Context.java:136) at org.mortbay.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1250) at org.mortbay.jetty.handler.ContextHandler.doStart(ContextHandler.java:517) at org.mortbay.jetty.webapp.WebAppContext.doStart(WebAppContext.java:467) at org.mortbay.component.AbstractLifeCycle.start(AbstractLifeCycle.java:50) at com.google.tracing.TraceContext$TraceContextRunnable.runInContext(TraceContext.java:449) at com.google.tracing.TraceContext$TraceContextRunnable$1.run(TraceContext.java:455) at com.google.tracing.TraceContext.runInContext(TraceContext.java:695) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContextNoUnref(TraceContext.java:333) at com.google.tracing.TraceContext$AbstractTraceContextCallback.runInInheritedContext(TraceContext.java:325) at com.google.tracing.TraceContext$TraceContextRunnable.run(TraceContext.java:453) at java.lang.Thread.run(Thread.java:679) ``` with following explanation: This request caused a new process to be started for your application, and thus caused your application code to be loaded for the first time. This request may thus take longer and use more CPU than a typical request for your application. A serious problem was encountered with the process that handled this request, causing it to exit. This is likely to cause a new process to be used for the next request to your application. If you see this message frequently, you may be throwing exceptions during the initialization of your application. (Error code 104)
2011/11/17
[ "https://Stackoverflow.com/questions/8162278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/930544/" ]
As it says in the stacktrace: ``` HardDeadlineExceededError: This request (0000000000000000) started at 2011/11/17 04:12:01.160 UTC and was still executing at 2011/11/17 04:13:01.204 UTC. ``` Frontend requests to App Engine apps have 60 seconds to complete. If your request takes longer than that, it will be terminated. If you need to do a lot of work, you should do it on the Task Queue.
53,203,011
It's abundantly clear to me that when we want to delete a node in a Linked List (be it doubly or singly linked), and we have to search for this node, the time complexity for this task is O(n), as we must traverse the whole list in the worst case to identify the node. Similarly, it is O(k) if we want to delete the k-th node, and we don't have a reference to this node already. It is commonly cited that one of the benefits of using a doubly linked list over a singly linked list is that deletion is O(1) when we have a reference to the node we want to delete. I.e., if you want to delete the Node i, simply do the following: i.prev.next = i.next and i.next.prev = i.prev It is said that deletion is O(1) in a singly linked list ONLY if you have a reference to the node prior to the one you want to delete. However, I don't think this is necessarily the case. If you want to delete Node i (and you have a reference to Node i), why can't you just copy over the data from i.next, and set i.next = i.next.next? This would also be O(1), as in the doubly linked list case, meaning that deletion is no more efficient in a doubly linked list in ANY case, as far as Big-O is concerned. Of course, this idea wouldn't work if the node you're trying to delete is the last node in the linked list. It's really bugging me that no one remembers this when comparing singly and doubly linked lists. What am I missing? **To clarify**: what I'm suggesting in the singly linked case is **overwriting the data at the Node you want to delete**, with the data from the next node, and then deleting the next node. This has the same desired effect as deleting Node `i`, though it is not what you're doing per se. **EDIT** **What I've Learned:** So it seems that I am correct to some extent. First of all, many people mentioned that my solution isn't complete, as deletion of the last element is a problem, so my algorithm is O(n) (by definition of Big-O). I naively suggested in response to get around this by keeping track of the "2nd to last node" in your list - of course, this causes problems once the last node in your list has been deleted the first time. A solution that was suggested, and does seem to work, is to demarcate the end of your list with something like a NullNode, and I like this approach. Other problems that were presented were referential integrity, and the time associated with copying the data itself from the next node (i.e. presumably, a costly deep copy might be necessary). If you can assume that you don't have other objects using the node that you're copying, and that the task of copying is O(1) in itself, then it seems like my solution works. Although, at this point, maybe its worth it to just use a Doubly Linked List :)
2018/11/08
[ "https://Stackoverflow.com/questions/53203011", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10622251/" ]
It is true that copying data from `i.next` to `i` and then deleting `i` would be `O(1)` assuming that copying the data is also `O(1)`. But even with this algorithm, since deleting the last element is `O(n)`, and a description of a function in terms of big O notation only provides an upper bound on the growth rate of the function, that means your algorithm is still `O(n)`. Regarding your comment: > > I guess my dissatisfaction comes from the fact that textbooks and basically every resource online cites the #1 biggest advantage of doubly linked lists is deletion - this seems a little disingenuous. It's a very specific case of deletion - deletion at the tail! If efficient deletion is all you're going for, seems like this doesn't warrant using a doubly instead of a singly linked list (due to all the overhead necessary of having double the number of pointers). Simply store a reference to the second to last node in your list, and you're good to go! > > > You can certainly store a reference to the second to last node and make deletion of the last node `O(1)`, but this would be the case only for the first time you delete the last node. You could update the reference to the node before it, but finding it will be `O(n)`. You can solve this if you keep a reference to second to last element, and so on. At this point, you have reasoned your way to a doubly linked list, whose main advantage is deletion, and since you already have pointers to previous nodes you don't really need to move values around. **Remember that big `O` notation talks about the worst case scenario, so if even a single case is `O(n)` then your entire algorithm is `O(n)`.** When you say a solution is `O(n)` you are basically saying *"in the worst possible case, this algorithm will grow as fast as `n` grows"*. Big `O` does not talk about expected or average performance, and it's a great theoretical tool, but you need to consider your particular use cases when deciding what to use. Additionally, if you need to preserve reference integrity, you would not want to move values from one node to the other, i.e. if you tad a reference to node `i+1` and delete node `i`, you wouldn't expect your reference to be silently invalid, so when removing elements the more robust option is to delete the node itself.
27,529,956
I need to enlarge an input field when it's on focus without the containing td enlarging, too. Further on both fields should stay on their actual position (have a look on the fiddle, it mooves) and not move up or down (what is caused by the absolute position). This is my actual state ``` $('.Bemerkung').focus(function() { $(this).attr('size','30'); $(this).parent().css({'position':'absolute'}); $(this).css({'position':'absolute'}); }) $('.Bemerkung').blur(function() { $(this).attr('size','5'); $(this).removeAttr('style'); $(this).parent().removeAttr('style'); }) ``` <http://jsfiddle.net/kazuya88/dhy0dxyy/> Hope you can help me.
2014/12/17
[ "https://Stackoverflow.com/questions/27529956", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4371042/" ]
It's not too far from what you originally had: ``` $('.Bemerkung').focus(function() { oldWidth = $(this).width(); $(this).attr('size','30'); $(this).css({'position':'relative'}); $(this).css({'margin-right':('-'+($(this).width()-oldWidth)+'px')}); }) $('.Bemerkung').blur(function() { $(this).attr('size','5'); $(this).removeAttr('style'); $(this).parent().removeAttr('style'); }) ``` Update: I figured I should add more explanation about what is going on here. This basically detects what the size is before gaining focus, then increases the size and sets the right margin to the difference between the new size and the old size (thus making the renderer see it as the same "width" as before gaining focus). Position:relative is so that the element width will not affect the td width (as long as right-margin is set negative).
27,541,934
I'm trying to accomplish a dynamic button which is always square, and based on the height of the text it is with. Something like this: ![Example](https://i.stack.imgur.com/9Vg9m.png) Basically the icon stays the same, but the size of the box varies, based on what size of text it is next to. The icon should be centered vertically and horizontally. To get it to look like the image, I had to manually put in everything, but I want it to work whether the `font-size` is `20px`, `70px`, or anything else. Basically, I don't know the height, but it should work is the goal, and that seems to be what is different in this question from others around the site/web. This is the HTML code: ``` <!-- This may be any font size, but the result should be like the image above. --> <div id="name"> <!-- This holds the text --> <span>Amy</span> <!-- This holds the image, and the anchor is the box. --> <a href="#"><img src="/images/edit.png" alt="Edit Name" /></a> </div> ``` I've tried following [this tutorial](http://blog.brianjohnsondesign.com/responsive-centered-square-div-resizes-height/), but I can't get it to work for some reason. Everything I've tried (which is too many things to enumerate here) either gives me the right height, but wrong width, the exact size of the image, or the image as the size of the square. Is this possible with just CSS, or am I going to have to resort to JavaScript? Thanks.
2014/12/18
[ "https://Stackoverflow.com/questions/27541934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1940394/" ]
Something like this should do it. You may have to change the size a little depending on the font. Also, you may have to `vertical-align` it. ``` .edit { display: inline-block; width: 1em; height: 1em; } .edit img { display: block; } ```
35,435,755
I am creating a json string using dictionary and I have to remove only that part from string my string is ``` [{Id: "code": "AAA" , Title: "display": "ANAA,FRENCH POLYNESIA"},{Id: "code": "AAB" , Title: "display": "ARRABURY, QL AUSTRALIA"}] ``` I want to remove only ``` "code": ``` And that part from string using string.Replace('', "") ``` "display": ``` I am trying this: ``` var entries = dict.Select(d => string.Format("{{Id: {0} , Title: {1}}}", d.Key, string.Join(",", d.Value))); return "" + string.Join(",", entries) + ""; ``` Not working to achieve ``` [{Id: "AAA" , Title: "ANAA,FRENCH POLYNESIA"},{Id: "AAB" , Title: "ARRABURY, QL AUSTRALIA"}] ```
2016/02/16
[ "https://Stackoverflow.com/questions/35435755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5879311/" ]
You can run this code: ``` string json = "[{Id: \"code\": \"AAA\" , Title: \"display\": \"ANAA,FRENCH POLYNESIA\"},{Id: \"code\": \"AAB\" , Title: \"display\": \"ARRABURY, QL AUSTRALIA\"}]"; json = json.Replace("\"code\":", String.Empty); json = json.Replace("\"display\":", String.Empty); ``` You can remove with replace method if you use **String.Empty**