qid
int64
1
74.7M
question
stringlengths
15
58.3k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
4
30.2k
response_k
stringlengths
11
36.5k
15,118,828
I don't know JQuery but am looking to create a box that populates with different content based on clicks from a navigation bar above. Thanks for any help!
2013/02/27
[ "https://Stackoverflow.com/questions/15118828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1499522/" ]
To achieve this, you should read up on the basic concepts of jQuery, in particular the jQuery [click](http://api.jquery.com/click/) and [html](http://api.jquery.com/html/)/[text](http://api.jquery.com/text/) functions. In the most basic form, you would use it something like this: ``` $('#myNavLink').click(function(){ $('#myContentArea').text("This is the new content text"); }); ```
This is a very broad question and has answers all over the internet; however, to get you started you will want to check out the following syntax: ``` var value = '<p>Here is my new content that came from my database, fetched using Ajax & jQuery!</p>'; $('#mydiv').html(value); ``` Mind you that the code above is very destructive meaning that it will completely replace all content. Good luck!
15,118,828
I don't know JQuery but am looking to create a box that populates with different content based on clicks from a navigation bar above. Thanks for any help!
2013/02/27
[ "https://Stackoverflow.com/questions/15118828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1499522/" ]
As I said in my comment on the question, this question is too broad and I expect it will get closed by the community. But I thought I'd offer a couple of pointers: 1. You can trigger a function call when an element is clicked by having jQuery hook up a `click` handler on that element. You need to be able to tell jQuery which element you're talking about, which you can do with any CSS selector. You might use an `id` (although `id`s are not necessarily the best choice in general). For example: ``` $("#foo").click(function() { alert("Hi there"); }); ``` ...will hook up that function to the `click` event on the element with the `id` `"foo"`. 2. You can load content into an element using the `html` function (for content you specify in a string in the code) or the `load` function (for content you load from your server on-demand), again by having jQuery look up the element, and then acting on it: ``` $("#foo").html("New content"); $("#foo").load("/path/to/new/content/on/server"); ``` The [jQuery API docs](http://api.jquery.com) are a good starting point, and there are any number of online tutorials and blogs. Good luck with it.
This is a very broad question and has answers all over the internet; however, to get you started you will want to check out the following syntax: ``` var value = '<p>Here is my new content that came from my database, fetched using Ajax & jQuery!</p>'; $('#mydiv').html(value); ``` Mind you that the code above is very destructive meaning that it will completely replace all content. Good luck!
3,422,711
Let $A$ be an $n\times n$ symmetric matrix with coefficient $\mathbb{R}$ and $S$ be a nonsingular matrix. Then does the signature of $S^tAS$ equal that of $A$?
2019/11/05
[ "https://math.stackexchange.com/questions/3422711", "https://math.stackexchange.com", "https://math.stackexchange.com/users/697599/" ]
First let's solve an easier integral that doesn't have the denominator squared, namely:$$y(t)=\int\_0^\infty \frac{\cos(tx)}{\color{blue}{1+x^2}}dx=\int\_0^\infty \cos(tx){\color{blue}{\int\_0^\infty \sin y e^{-xy}dy}}dx$$ $$={\int\_0^\infty}\sin y{\color{red}{\int\_0^\infty \cos(tx)e^{-xy}dx}}dy=\int\_0^\infty \frac{{\color{red}y}\sin y}{{\color{red}{t^2+y^2}}}dy $$ $$\overset{y=tx}=\int\_0^\infty \frac{x\sin(tx)}{1+x^2}dx=-y'(t)\Rightarrow \frac{y'(t)}{y(t)}=-1 \Rightarrow y(t)=c\cdot e^{-t}$$ $$y(0)=\int\_0^\infty \frac{dx}{1+x^2}=\frac{\pi}{2}\Rightarrow c=\frac{\pi}{2}\Rightarrow y(t)=\frac{\pi}{2}e^{-t}$$ $$y(t)\overset{tx=z}=t\int\_0^\infty\frac{\cos z}{t^2+z^2}dz\Rightarrow\boxed{\int\_{-\infty}^\infty\frac{\cos x}{t^2+x^2}dx=\frac{\pi}{t}e^{-t},\ t>0}$$ --- Now in order to find the desired integral, we will differentiate under the integral sign, with respect to $t$ then divide by $-2t$, since: $$\frac{d}{dt}\int\_{-\infty}^\infty\frac{\cos x}{t^2+x^2}dx=-2t\int\_{-\infty}^\infty\frac{\cos x}{(t^2+x^2)^2}dx=\frac{d}{dt}\left(\frac{\pi}{t}e^{-t}\right)$$ $$\Rightarrow \int\_{-\infty}^\infty\frac{\cos x}{(t^2+x^2)^2}dx=-\frac{1}{2t}\frac{d}{dt}\left(\frac{\pi}{t}e^{-t}\right)=\frac{\pi(t+1)}{2t^3}e^{-t},\ t>0$$
Another way to do it is to note that$$\frac{1}{x^2+t^2}=\frac{1}{2it}\left(\frac{1}{x-it}-\frac{1}{x+it}\right)\implies\frac{1}{(x^2+t^2)^2}=\frac{-1}{4t^2}\left(\frac{1}{(x-it)^2}+\frac{1}{(x+it)^2}+\frac{i}{t}\left(\frac{1}{x-it}-\frac{1}{x+it}\right)\right).$$The $e^{ix}$ in $\cos x$ doesn't diverge when $x=i\infty$, so the $\Im x\ge0$ semicircle contains a pole $it$ contributing$$\frac{-i\pi}{2t^2}\left.\left(\frac{d}{dx}e^{ix}+\frac{i}{t}e^{ix}\right)\right|\_{x=it}=\frac{-i\pi}{2t^2}\left(ie^{-t}+\frac{i}{t}e^{-t}\right)=\frac{\pi(t+1)}{2t^3e^t}.$$
31,271,549
In a bash script I have to match strings that begin with exactly 3 times with the string `lo`; so `lololoba` is good, `loloba` is bad, `lololololoba` is good, `balololo` is bad. I tried with this pattern: `"^$str1/{$n,}"` but it doesn't work, how can I do it? *EDIT:* According to OPs comment, `lololololoba` is bad now.
2015/07/07
[ "https://Stackoverflow.com/questions/31271549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928445/" ]
This should work: ``` pat="^(lo){3}" s="lolololoba" [[ $s =~ $pat ]] && echo good || echo bad ``` *EDIT (As per OPs comment):* If you want to match exactly 3 times (i.e `lolololoba` and such should be unmatched): change the `pat="^(lo){3}"` to: ``` pat="^(lo){3}(l[^o]|[^l].)" ```
You can use following regex : ``` ^(lo){3}.*$ ``` Instead of `lo` you can put your variable. See demo <https://regex101.com/r/sI8zQ6/1>
31,271,549
In a bash script I have to match strings that begin with exactly 3 times with the string `lo`; so `lololoba` is good, `loloba` is bad, `lololololoba` is good, `balololo` is bad. I tried with this pattern: `"^$str1/{$n,}"` but it doesn't work, how can I do it? *EDIT:* According to OPs comment, `lololololoba` is bad now.
2015/07/07
[ "https://Stackoverflow.com/questions/31271549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928445/" ]
You can use following regex : ``` ^(lo){3}.*$ ``` Instead of `lo` you can put your variable. See demo <https://regex101.com/r/sI8zQ6/1>
You can use this `awk` to match **exactly** 3 occurrences of `lo` at the beginning: ``` # input file cat file lololoba balololo loloba lololololoba lololo # awk command to print only valid lines awk -F '^(lo){3}' 'NF == 2 && !($2 ~ /^lo/)' file lololoba lololo ```
31,271,549
In a bash script I have to match strings that begin with exactly 3 times with the string `lo`; so `lololoba` is good, `loloba` is bad, `lololololoba` is good, `balololo` is bad. I tried with this pattern: `"^$str1/{$n,}"` but it doesn't work, how can I do it? *EDIT:* According to OPs comment, `lololololoba` is bad now.
2015/07/07
[ "https://Stackoverflow.com/questions/31271549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928445/" ]
You can use following regex : ``` ^(lo){3}.*$ ``` Instead of `lo` you can put your variable. See demo <https://regex101.com/r/sI8zQ6/1>
As per your comment: ``` ... more than 3 is bad so "lolololoba" is not good! ``` You'll find that @Jahid's answer doesn't fit (as his gives you "good" to that test string. To use his answer with the correct regex: ``` pat="^(lo){3}(?\!lo)" s="lolololoba" [[ $s =~ $pat ]] && echo good || echo bad ``` This verifies that there are three "lo"s at the beginning, and not another one immediately following the three. Note that if you're using bash you'll have to escape that `!` in the first line (which is what my regex above does)
31,271,549
In a bash script I have to match strings that begin with exactly 3 times with the string `lo`; so `lololoba` is good, `loloba` is bad, `lololololoba` is good, `balololo` is bad. I tried with this pattern: `"^$str1/{$n,}"` but it doesn't work, how can I do it? *EDIT:* According to OPs comment, `lololololoba` is bad now.
2015/07/07
[ "https://Stackoverflow.com/questions/31271549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928445/" ]
This should work: ``` pat="^(lo){3}" s="lolololoba" [[ $s =~ $pat ]] && echo good || echo bad ``` *EDIT (As per OPs comment):* If you want to match exactly 3 times (i.e `lolololoba` and such should be unmatched): change the `pat="^(lo){3}"` to: ``` pat="^(lo){3}(l[^o]|[^l].)" ```
You can use this `awk` to match **exactly** 3 occurrences of `lo` at the beginning: ``` # input file cat file lololoba balololo loloba lololololoba lololo # awk command to print only valid lines awk -F '^(lo){3}' 'NF == 2 && !($2 ~ /^lo/)' file lololoba lololo ```
31,271,549
In a bash script I have to match strings that begin with exactly 3 times with the string `lo`; so `lololoba` is good, `loloba` is bad, `lololololoba` is good, `balololo` is bad. I tried with this pattern: `"^$str1/{$n,}"` but it doesn't work, how can I do it? *EDIT:* According to OPs comment, `lololololoba` is bad now.
2015/07/07
[ "https://Stackoverflow.com/questions/31271549", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3928445/" ]
This should work: ``` pat="^(lo){3}" s="lolololoba" [[ $s =~ $pat ]] && echo good || echo bad ``` *EDIT (As per OPs comment):* If you want to match exactly 3 times (i.e `lolololoba` and such should be unmatched): change the `pat="^(lo){3}"` to: ``` pat="^(lo){3}(l[^o]|[^l].)" ```
As per your comment: ``` ... more than 3 is bad so "lolololoba" is not good! ``` You'll find that @Jahid's answer doesn't fit (as his gives you "good" to that test string. To use his answer with the correct regex: ``` pat="^(lo){3}(?\!lo)" s="lolololoba" [[ $s =~ $pat ]] && echo good || echo bad ``` This verifies that there are three "lo"s at the beginning, and not another one immediately following the three. Note that if you're using bash you'll have to escape that `!` in the first line (which is what my regex above does)
62,688,328
I am trying to create tabs in my layout. But instead of showing tab it is showing the below screen in design: [![enter image description here](https://i.stack.imgur.com/WwGzK.png)](https://i.stack.imgur.com/WwGzK.png) Below is the code: ``` **activity_mail.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="200dp" android:id="@+id/appBarLayout2"> <com.google.android.material.tabs.TabLayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed"/> </android.support.design.widget.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@android:color/white"/> </LinearLayout> ``` **MainActivity.java** ``` import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; public class MainActivity extends AppCompatActivity { /* private TabAdapter adapter; private TabLayout tabLayout; private ViewPager viewPager;*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager); viewPager.setAdapter(new TabAdapter(getSupportFragmentManager(), MainActivity.this)); TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); tabLayout.setupWithViewPager(viewPager); } } ``` **Tab1Fragment.java** ``` import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.fragment.app.Fragment; public class Tab1Fragment extends Fragment { public static final String ARG_PAGE = "ARG_PAGE"; private int mPage; public static Tab1Fragment newInstance(int page) { Bundle args = new Bundle(); args.putInt(ARG_PAGE, page); Tab1Fragment fragment = new Tab1Fragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPage = getArguments().getInt(ARG_PAGE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); TextView textView = (TextView) view; textView.setText("Fragment #" + mPage); return view; } } ``` **TabAdapter.Java** ``` import android.content.Context; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; public class TabAdapter extends FragmentStatePagerAdapter { final int PAGE_COUNT = 3; private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" }; private Context context; public TabAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public int getCount() { return PAGE_COUNT; } @Override public Fragment getItem(int position) { return Tab1Fragment.newInstance(position + 1); } @Override public CharSequence getPageTitle(int position) { // Generate title based on item position return tabTitles[position]; } } ``` **fragment\_main.xml** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.main.PlaceholderFragment"> <TextView android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="@dimen/activity_horizontal_margin" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_marginEnd="@dimen/activity_horizontal_margin" android:layout_marginBottom="@dimen/activity_vertical_margin" android:text="@string/sparta" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" tools:layout_constraintLeft_creator="1" tools:layout_constraintTop_creator="1" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` Also when trying to run it in my mobile, it is showing error something like: android.widget.RelativeLayout cannot be cast to android.widget.TextView Please suggest the way to solve this issue.
2020/07/02
[ "https://Stackoverflow.com/questions/62688328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13109658/" ]
JavaScript is case sensitive. ``` clinet.on("message", Message => {}); ``` In the following you defined message parameter with a capital "M". So you need to mention the Message with a capital M. Here's the fix for args V ``` let args = Message.content.slice(prefix.length).trim().split(' '); ``` Hope This helps.
The error is pretty self-explanatory. You've got `message` on one line and `Message` on another. JavaScript variables are case-sensitive. You also can't have `message` defined outside of a scope *`client.on()` in this case*. I recommend putting everything that requires messages into your `client.on('Message', Message => {}` scope. You should probably use only one scope too.
62,688,328
I am trying to create tabs in my layout. But instead of showing tab it is showing the below screen in design: [![enter image description here](https://i.stack.imgur.com/WwGzK.png)](https://i.stack.imgur.com/WwGzK.png) Below is the code: ``` **activity_mail.xml** <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <android.support.design.widget.AppBarLayout android:layout_width="match_parent" android:layout_height="50dp" android:layout_marginTop="200dp" android:id="@+id/appBarLayout2"> <com.google.android.material.tabs.TabLayout android:id="@+id/sliding_tabs" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabMode="fixed"/> </android.support.design.widget.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPager" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:background="@android:color/white"/> </LinearLayout> ``` **MainActivity.java** ``` import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.viewpager.widget.ViewPager; import com.google.android.material.tabs.TabLayout; public class MainActivity extends AppCompatActivity { /* private TabAdapter adapter; private TabLayout tabLayout; private ViewPager viewPager;*/ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ViewPager viewPager = (ViewPager) findViewById(R.id.viewPager); viewPager.setAdapter(new TabAdapter(getSupportFragmentManager(), MainActivity.this)); TabLayout tabLayout = (TabLayout) findViewById(R.id.sliding_tabs); tabLayout.setupWithViewPager(viewPager); } } ``` **Tab1Fragment.java** ``` import android.os.Bundle; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import androidx.fragment.app.Fragment; public class Tab1Fragment extends Fragment { public static final String ARG_PAGE = "ARG_PAGE"; private int mPage; public static Tab1Fragment newInstance(int page) { Bundle args = new Bundle(); args.putInt(ARG_PAGE, page); Tab1Fragment fragment = new Tab1Fragment(); fragment.setArguments(args); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mPage = getArguments().getInt(ARG_PAGE); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_main, container, false); TextView textView = (TextView) view; textView.setText("Fragment #" + mPage); return view; } } ``` **TabAdapter.Java** ``` import android.content.Context; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentManager; import androidx.fragment.app.FragmentStatePagerAdapter; public class TabAdapter extends FragmentStatePagerAdapter { final int PAGE_COUNT = 3; private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" }; private Context context; public TabAdapter(FragmentManager fm, Context context) { super(fm); this.context = context; } @Override public int getCount() { return PAGE_COUNT; } @Override public Fragment getItem(int position) { return Tab1Fragment.newInstance(position + 1); } @Override public CharSequence getPageTitle(int position) { // Generate title based on item position return tabTitles[position]; } } ``` **fragment\_main.xml** ``` <?xml version="1.0" encoding="utf-8"?> <androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/mainLayout" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".ui.main.PlaceholderFragment"> <TextView android:id="@+id/section_label" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginStart="@dimen/activity_horizontal_margin" android:layout_marginTop="@dimen/activity_vertical_margin" android:layout_marginEnd="@dimen/activity_horizontal_margin" android:layout_marginBottom="@dimen/activity_vertical_margin" android:text="@string/sparta" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintTop_toTopOf="parent" tools:layout_constraintLeft_creator="1" tools:layout_constraintTop_creator="1" /> </androidx.constraintlayout.widget.ConstraintLayout> ``` Also when trying to run it in my mobile, it is showing error something like: android.widget.RelativeLayout cannot be cast to android.widget.TextView Please suggest the way to solve this issue.
2020/07/02
[ "https://Stackoverflow.com/questions/62688328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13109658/" ]
JavaScript is case sensitive. ``` clinet.on("message", Message => {}); ``` In the following you defined message parameter with a capital "M". So you need to mention the Message with a capital M. Here's the fix for args V ``` let args = Message.content.slice(prefix.length).trim().split(' '); ``` Hope This helps.
Make sure to keep the "args" var inside a client.on callback. Like this: ```js client.on('message', message => { let args = message.content.slice(prefix.length).trim().split(' '); }) ```
69,847,905
I started learning Flutter this week. I'm trying to get the position of the device using the Geolocator package but I'm not used to async functions. I want to use the position.latitude inside the Text of AppBar title. I wrote < position information goes here > in the code to show the right place. Below is my code. ``` class HomeScreen extends StatelessWidget { const HomeScreen({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: buildAppBar(context), ); } AppBar buildAppBar(context) { var position = null; getCurrentPosition().then((position) => {position = position}); return AppBar( centerTitle: true, backgroundColor: kPrimaryColor, elevation: 0, toolbarHeight: MediaQuery.of(context).size.height * 0.07, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( icon: const Icon(Icons.place), iconSize: 15, onPressed: () {}, ), const Text(<position information goes here>, style: TextStyle(fontSize: 12)), ], )); } Future<Position> getCurrentPosition() async { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); return position; } } ```
2021/11/05
[ "https://Stackoverflow.com/questions/69847905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11356556/" ]
1. Your page must be stateful in order to change it state. Stateless widget are static, you can use them when your Widgets don't change and the user doesn't interact with the screen. 2. You have to call the setState() method, so your page know's something has changed. 3. Later, if you desire to evolve your code, use state management (MobX,GetX, Cubit, RxDart) instead of setStates. When you use setState, all the widgets under the widget-tree reload, so it consumes more CPU and GPU. Try something like this: ``` import 'package:flutter/material.dart'; class HomeScreen extends StatefulWidget { const HomeScreen({Key? key}) : super(key: key); @override State<HomeScreen> createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { var position = null; @override void initState() { getCurrentPosition().then((position) { setState(() { position = position; }); }); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: buildAppBar(context), ); } AppBar buildAppBar(context) { return AppBar( centerTitle: true, backgroundColor: kPrimaryColor, elevation: 0, toolbarHeight: MediaQuery.of(context).size.height * 0.07, title: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( icon: const Icon(Icons.place), iconSize: 15, onPressed: () {}, ), const Text(position ?? '', style: TextStyle(fontSize: 12)), ], )); } Future<Position> getCurrentPosition() async { Position position = await Geolocator.getCurrentPosition( desiredAccuracy: LocationAccuracy.high); return position; } } ``` if you have some problem, give me a feedback.
I don't know exactly how do you want to use it. But I will give my solution as I understood the issue. First, change StatelessWidget to StatefulWidget. Then you can define the position variable inside the HomeScreen class and set the current position to. Then send this variable as a parameter to the buildAppbar function: AppBar buildAppBar(context, dynamic currentPos){...} the variable currentPos is for storing the value got from async function named getCurrentPosition. The Text widget accepts only String data type, so you can use currPos.toString() method or using it as you prefer. To get the value of current position from the asynchronous function named getCurrentPosition and assigned it to the position variable when the widget being created and then send it to the buildAppbar function, you can do the following in your code. \*sorry see the code in the image. I wrote it in mobile because I don't have lap now and when I post the answer an error appears in code formatting. So I will tack a screenshot for code and add it here. ![enter image description here](https://i.stack.imgur.com/e6iOd.jpg)![enter image description here](https://i.stack.imgur.com/bp8St.jpg)
38,125,599
I really want to know, how can I click a button inside a Bootstrap modal after I've open it by clicking its link: ``` <a href="#" data-toggle="modal" data-target="#myid"> ``` Buttons have ids', so I think I can click the button using **js**, but I don't really know how to deal with this. Could I use a function such as `$("#buttonid").click();` in the `data-target` after the modal call? I tried with no results. Any help would be appreciate Here is the button code: ``` <button type="submit" id="buttonid" name="Profile" href="#"> ```
2016/06/30
[ "https://Stackoverflow.com/questions/38125599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6449926/" ]
```js $('#myModal').on('shown.bs.modal', function (event) { $("#newBtn").trigger("click"); }); $("#newBtn").on("click",function(){ alert("button inside modal clicked"); }) ``` ```html <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script> <!-- Trigger the modal with a button --> <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button> <!-- Modal --> <div id="myModal" class="modal fade" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">Modal Header</h4> </div> <div class="modal-body"> You can make the button hidden by adding class hidden to button. <button type="button" id="newBtn" class="btn btn-sm btn-info">clicked on modal open</button> </div> <div class="modal-footer"> <button type="button" class="btn btn-default" data-dismiss="modal">Close</button> </div> </div> </div> </div> ```
Call the trigger on the modal shown event ``` $('#myid').on('shown.bs.modal', function () { $("#buttonid").trigger('click'); }); ```
96,557
In Dybjer's *Inductive Families* the author present a method to derive an eliminator/induction principle for every inductive family of types. In particular for the type of finite lists, namely $$List' \colon (A \colon set) (n \colon N) set$$ we get the eliminator $$\begin{align\*} listrec' \colon &(A \colon set)\\ & (C \colon (a \colon N)(c \colon List'\_A n)set) \\ & (e\_1 \colon C(0,nil'\_A)\\ & (e\_2 \colon (b\_1 \colon N)(b\_2 \colon A)(u \colon List'\_A(b\_1))(v \colon C(b\_1,u))C(s(b\_1),cons'\_A(b\_1,b\_2,u)))\\ & (a \colon N) \\ & (c \colon List'\_A(a)) \\ & C(a,c)\ . \end{align\*}$$ From what I get from this eliminator we should be able to provide any possible operation using finite lists. Now my question is > > how do we get the classical *destructor* $$tail \colon (A \colon set)(n \colon N)(List'\_A(s(n))) List'\_A n$$ > that from any finite list gets its tail? > > > I am totally lost on how to approach this problem since the eliminator seems to be able to provide just function defined on the whole family $List'\_A(n)$ and not on the sub-family $List'\_A(s(n))$. Thanks in advance.
2018/08/23
[ "https://cs.stackexchange.com/questions/96557", "https://cs.stackexchange.com", "https://cs.stackexchange.com/users/27248/" ]
> > I am totally lost on how to approach this problem since the eliminator seems to be able to provide just function defined on the whole family List′A(n) and not on the sub-family List′A(s(n)). > > > The typical trick in this situation is to pick a `C` such that you can pretend you are defining a function on the whole family when, in fact, you're only focusing on the sub-family you care about thanks to equality constraints. Let me be more concrete: If you pick `C(n, xs) = (m:N) -> n = s(m) -> List'_A(m)` then you can define a generalised `gtail` by using `listrec'`, and derive `tail` as a corollary. ``` gtail : (A:set) (n:N) (xs : List'_A(n)) -> C(n, xs) gtail A = listrec' A C contradiction -- of type: (m:N) -> 0 = s(m) -> List'_A(m) (\ _ _ u _ -> u) tail : (A:set) (n:N) -> List′A (s(n)) -> List′An tail A n xs = gtailn A (s(n)) xs n refl ```
What follows is just a little modification of the idea proposed in the accepted answer, nevertheless I think it can be of interest to other readers. Here's a way to build tail We can consider the predicate $P \colon (A\colon set)(n \colon N)(l \colon List'\_A n)set$ defined (by recursion on natural numbers) as the only type family such that $$\begin{align\*} P(A,0,l)&= 1\\ P(A, s(n),l) &= List'\_A (n) \end{align\*}$$ where $1$ is the unit type with only term $()$. If we let $$e\_1 = () \colon 1= P(A,0,nil')$$ and $$e\_2=\lambda n \colon N.\lambda x \colon A.\lambda xs \colon List'\_A n. \lambda p \colon P(A,n,xs). xs \colon (n \colon N)(x\colon A)(xs \colon List'\_A n)(p \colon P(A,n,xs))\underbrace{List'\_A(n)}\_{=P(A,s(n),cons'\_A(n,x,xs))}$$ we get $almostTail = (\lambda A \colon set) listrec'(A,P(A),e\_1,e\_2) \colon (A \colon set)(n \colon N)(l \colon List'\_A(n))P(A,n,l)$ which by the reduction principle is such that $$almostTail(A,s(n),cons'\_A(n,x,xs))=e\_2(n,x,xs,almostTail(A,n,xs))=xs\ .$$ So we get $$tail' \colon (A\colon set)(n\colon N)(l \colon List'\_A(s(n)))\underbrace{P(A,s(n),l)}\_{List'\_A(n)}$$ by letting $$tail'(A,n,l) = almostTile(A,s(n),l)\ .$$ **Note**: the only difference between gallais' example and mine is that instead of adding an hypothesis in the predicate to pass to $listrec'$ I have used a predicate with a *don't care value* for the case $n=0$. In this case too we basically build a function defined on all the lists, with the desired behaviour in the case of interest (i.e. not empty lists), and then consider the specialized/restricted function for the sub-family of types we are interested in.
1,025,803
Given the follwing class - I would like to know which of the both members is abstract: ``` abstract class Test { public abstract bool Abstract { get; set; } public bool NonAbstract { get; set; } } var type = typeof( Test ); var abs = type.GetProperty( "Abstract" ); var nonAbs = type.GetProperty( "NonAbstract" ); // now, something like: if( abs.IsAbstract ) ... ``` Unfortunately there is nothing like the `IsAbstract`-property. I need to select all non-abstract fields/properties/methods of a class - but there are no `BindingFlags` to narrow the selection, too.
2009/06/22
[ "https://Stackoverflow.com/questions/1025803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/52444/" ]
A property is actually some 'syntactic sugar', and is implemented by 2 methods: a getter method and a setter method. So, I think that you should be able to determine if a property is abstract by checking if the getter and/or setter are abstract, like this: ``` PropertyInfo pi = ... if( pi.GetSetMethod().IsAbstract ) { } ``` And, AFAIK, a field cannot be abstract. ;)
First off: fields can't be abstract, since all there is to them is the field itself. Next we note that properties are (in a loose sense!) actually get\_/set\_ methods under the hood. Next we check what *does* have an `IsAbstract` property, and see that `MethodBase` (and so `MethodInfo`) does. Finally we remember/know/find out that a `PropertyInfo` has `GetGetMethod()` and `GetSetMethod()` methods that return `MethodInfo`s, and we're done, except for filling in the messy details about inheritance and so forth.
32,211,793
I am really having trouble wrapping my head around the deferred() method inside jquery. I've spent several hours reading the documentation, but I still don't fully understand what I'm doing. My basic problem is, I have a series of functions (not ajax calls) that I want to run in sequence, but stop all processes if there is an error in any of them. Here is how far I've gotten (I've stripped out a bunch of unneeded code and just left the basic idea) ``` //The module var myModule = (function() { //Defaults var vOne; var VTwo; var deferred = $.Deferred(); //Private method var _myPrivateFunction1 = function(userID) { if(userID >= 10) { //All is good, set var vOne to true and run next function vOne = true; return deferred.promise(); } else { //User is not allowed, stop everything else and show the error message return deferred.reject(); } } var _myPrivateFunction2 = function() { if(vOne === true) { //Ok we can keep going return deferred.promise(); } else { //again stop everything and throw error return deferred.reject(); } }; var _myPrivateFunction3 = function(element) { //...and so on }; var _errorMsgFunction = function(msg) { $.log("There was an error: " + msg); return false; }; //Public method var myPublicFunction = function(element,call) { //element is jquery object passed through user "click" event var userID = element.data('id') var userAction = element.data('action'); //Now... i want to fire _myPrivateFunction1, _myPrivateFunction2, _myPrivateFunction3 in sequence and STOP all processes, and run // _errorMsgFunction if there is an error in any of them. //This is how far I've gotten... _myPrivateFunction1(userID).then(_myPrivateFunction2(userAction), _errorMsgFunction("Error in _myPrivateFunction2")).then(_myPrivateFunction3(element),_errorMsgFunction("Error in _myPrivateFunction3")).fail(_errorMsgFunction("Error in _myPrivateFunction1")); }; // Public API return { myPublicFunction: myPublicFunction }; })(); ``` So right now I keep getting "Error in \_myPrivateFunction2" (I'm forcing this error for testing purposes), but the other functions after continue to fire...They don't stop. What am I missing here?
2015/08/25
[ "https://Stackoverflow.com/questions/32211793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1245564/" ]
You cannot share deferred objects. You should create a different promise from a deferred for each function. Here is some very simple example, using sycnhronus functions for the sake of simplicity, although promises are meant to be used with asynchronous functions: ``` var func1 = function(arg){ var dfd = jQuery.Deferred(); if (arg === 0) { dfd.resolve('func1 Ok'); } else { dfd.reject('func1 arg != 0'); } return dfd.promise(); } var func2 = function(arg){ var dfd = jQuery.Deferred(); if (arg === 0) { dfd.resolve('func2 Ok'); } else { dfd.reject('func2 arg != 0'); } return dfd.promise(); } var func3 = function(arg){ var dfd = jQuery.Deferred(); if (arg === 0) { dfd.resolve('func3 Ok'); } else { dfd.reject('func3 arg != 0'); } return dfd.promise(); } ``` If the functions does not depend on other to do their processing, we can do it in parallel using `jQuery.when` ``` // Parallel processing jQuery.when(func1(1), func2(0), func3(0)).then(function(res1, res2, res3){ console.log(res1, res2, res3); }).fail(function(reason){ console.error(reason); // will fail with reason func1 arg != 0 }); ``` If it is a sequence processing (as I undertood your problem is), you should do: ``` // Sequential processing func1(0).then(function(res1){ return func2(res1); }).then(function(res2){ return func3(res2); }).then(function(res3){ // everything ran ok, so do what you have to do... }).fail(function(reason){ console.log(reason); }); ``` The code above will fail with reason: ``` > func2 arg != 0 ``` If you have mixed parallel and sequential processing to do, then you should mix both approaches. --- Disclaimer ---------- As in my example, if `func1` or `func2` have side effects, they will not be undone within `fail()` by themselves. The best practice is to only have side effects when you are absolutely sure that everything went ok, that is, inside the last `then()` call.
You will need a separate `$.deferred()` inside each of your functions, because you want to return unique promise for each function. ``` //Private method var _myPrivateFunction1 = function(userID) { var deferred = $.Deferred(); if(userID >= 10) { //All is good, set var vOne to true and run next function vOne = true; deferred.resolve(); } else { //User is not allowed, stop everything else and show the error message deferred.reject(); } return deferred.promise(); } ``` Then your public function should work.
13,679,608
\**Note: \** I'm new here. If you're going to downvote please tell me why. I'm writing a java chess program using swing. I'm able to display the board, initialize pieces, and store them in a two dimensional array. However, I can't figure out how to display the pieces on my canvas. I keep getting a null pointer error on line 65 of class Piece. \**Update: \** I've included some of the suggested changes. The null pointer error has cleared up, but I'm still having trouble getting the pieces to display. I don't think I've correctly pointed them at the canvas I created in class Chess. My program is broken into three classes as follows: Class Chess ``` import java.util.Scanner; import javax.swing.*; //import java.awt.*; public class Chess { public static final int WINDOW_WIDTH=600; public static final int WINDOW_HEIGHT=600; public static final int SQUARE_WIDTH = (WINDOW_WIDTH-10)/8; public static final int SQUARE_HEIGHT = (WINDOW_HEIGHT-40)/8; public static int position[][] = {}; public BoardComponent mycanvas= new BoardComponent(this); public Chess() { JFrame mywindow; mywindow=new JFrame("ChessMaster 2012"); mywindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); mywindow.setSize(WINDOW_WIDTH, WINDOW_HEIGHT); //BoardComponent mycanvas= new BoardComponent(this); mywindow.add(mycanvas); mywindow.setVisible(true); //window appears here } public static void main(String[] args) { position = new int [8][8]; new Chess(); import javax.swing.*; import java.awt.*; import java.awt.image.BufferStrategy; import javax.swing.ImageIcon; public class Piece extends JPanel{ Piece[] mypiece; public ImageIcon piece; int nextID = 0; BoardComponent board; Chess chess; public int locx, locy; public void setCanvas(BoardComponent board) { this.board=board; } public Piece(char color, char Type, int posX, int posY){ // each piece assigned a PK on creation, beginning sequentially from top left // and looping back to the beginning of each row int pieceID = nextID; char pieceColor = color; char pieceType = Type; posX = locx; posY = locy; // P = pawn, K = knight, R = Rook, B = Bishop, Q = Queen, //S = king (can't reuse K, so we use S instead) if (pieceType == 'P'){ new Pawn(pieceColor); } else if (pieceType == 'K'){ new Knight(pieceColor); } else if (pieceType == 'R'){ new Rook(pieceColor); } else if (pieceType == 'B'){ new Bishop(pieceColor); } else if (pieceType == 'Q'){ new Queen(pieceColor); } else if (pieceType == 'S'){ new King(pieceColor); } nextID ++; Chess.position[posX][posY] = pieceID; setCanvas(board); repaint(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); drawPiece(g); } public void drawPiece(Graphics g){ g.drawImage(piece.getImage(),(locx*Chess.SQUARE_WIDTH),(locy*Chess.SQUARE_HEIGHT),null); } public class Pawn{ public Pawn(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wpawn.gif"); } else{ piece = new ImageIcon("src/gfx/bpawn.gif"); } } } public class Knight{ public Knight(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wknight.gif"); } else{ piece = new ImageIcon("src/gfx/bknight.gif"); } } } public class Rook{ public Rook(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wrook.gif"); } else{ piece = new ImageIcon("src/gfx/brook.gif"); } } } public class Bishop{ public Bishop(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wbishop.gif"); } else{ piece = new ImageIcon("src/gfx/bbishop.gif"); } } } public class Queen{ public Queen(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wqueen.gif"); } else{ piece = new ImageIcon("src/gfx/bqueen.gif"); } } } public class King{ public King(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wking.gif"); } else{ piece = new ImageIcon("src/gfx/bking.gif"); } } } } ``` Class BoardComponent: ``` import java.awt.*; import javax.swing.*; //This class draws the board and places the initial pieces public class BoardComponent extends JComponent{ Chess chess; public BoardComponent(Chess chessobject) { super(); chess=chessobject; } @Override public void paintComponent(Graphics g) { super.paintComponent(g); int rowCount = 0; int highCount = 0; int wideCount = 0; int squareCount = 0; ImageIcon piece; for(rowCount = 0; rowCount<8;rowCount++){ for(int i = 0; i < 8; i++){ if(squareCount%2==1){ g.setColor(Color.ORANGE); } else{ g.setColor(Color.darkGray); } g.fillRect(wideCount,highCount, Chess.SQUARE_WIDTH-5, Chess.SQUARE_HEIGHT-5); squareCount = squareCount + 1; wideCount = wideCount + Chess.SQUARE_WIDTH; g.setColor(Color.RED); } squareCount +=1; wideCount = 0; highCount = highCount + Chess.SQUARE_HEIGHT; } } } ``` Class Piece: ``` import javax.swing.*; import java.awt.*; import java.awt.image.BufferStrategy; import javax.swing.ImageIcon; public class Piece extends JPanel{ Piece[] mypiece; public ImageIcon piece; int nextID = 0; BoardComponent board; Chess chess; public int locx, locy; public void setCanvas(BoardComponent board) { this.board=board; } public Piece(char color, char Type, int posX, int posY){ // each piece assigned a PK on creation, beginning sequentially from top left // and looping back to the beginning of each row int pieceID = nextID; char pieceColor = color; char pieceType = Type; posX = locx; posY = locy; // P = pawn, K = knight, R = Rook, B = Bishop, Q = Queen, //S = king (can't reuse K, so we use S instead) if (pieceType == 'P'){ new Pawn(pieceColor); } else if (pieceType == 'K'){ new Knight(pieceColor); } else if (pieceType == 'R'){ new Rook(pieceColor); } else if (pieceType == 'B'){ new Bishop(pieceColor); } else if (pieceType == 'Q'){ new Queen(pieceColor); } else if (pieceType == 'S'){ new King(pieceColor); } nextID ++; Chess.position[posX][posY] = pieceID; setCanvas(board); repaint(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); drawPiece(g); } public void drawPiece(Graphics g){ g.drawImage(piece.getImage(),(locx*Chess.SQUARE_WIDTH),(locy*Chess.SQUARE_HEIGHT),null); } public class Pawn{ public Pawn(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wpawn.gif"); } else{ piece = new ImageIcon("src/gfx/bpawn.gif"); } } } public class Knight{ public Knight(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wknight.gif"); } else{ piece = new ImageIcon("src/gfx/bknight.gif"); } } } public class Rook{ public Rook(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wrook.gif"); } else{ piece = new ImageIcon("src/gfx/brook.gif"); } } } public class Bishop{ public Bishop(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wbishop.gif"); } else{ piece = new ImageIcon("src/gfx/bbishop.gif"); } } } public class Queen{ public Queen(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wqueen.gif"); } else{ piece = new ImageIcon("src/gfx/bqueen.gif"); } } } public class King{ public King(char color){ if(color == 'w'){ piece = new ImageIcon("src/gfx/wking.gif"); } else{ piece = new ImageIcon("src/gfx/bking.gif"); } } } } ``` I'm fairly new to java, and this is really throwing me for a loop. Can anyone help? Thanks!
2012/12/03
[ "https://Stackoverflow.com/questions/13679608", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1811341/" ]
* Dont call `drawPiece()` from your constructor for what reason? I think [`repaint()`](http://docs.oracle.com/javase/7/docs/api/java/awt/Component.html#repaint%28%29) might be what you need. * dont use `getGraphics()` as it wont be initialized yet until the panel is added and first repaint is done if im not mistaken. * Also never forget to honor paint chain and have `super.paintComponent(..)` as your first call in your overridden `paintComponent(..)` method of panel. * Rather extend `JPanel` and not `JComponent` I think you meant to call `drawPiece()` in `paintComponent(..)` in which place you should just pass the `Graphic`s object to `drawPiece()` from `paintComponent(..)` like so: ``` public class Piece extends JPanel{ public Piece(char color, char Type, int posX, int posY){ // each piece assigned a PK on creation, beginning sequentially from top left // and looping back to the beginning of each row .... // P = pawn, K = knight, R = Rook, B = Bishop, Q = Queen, //S = king (can't reuse K, so we use S instead (from Shah, the historical name)) .... nextID ++; Chess.position[posX][posY] = pieceID; repaint(); } @Override public void paintComponent(Graphics g){ super.paintComponent(g); drawPiece(g); } public void drawPiece(Graphics g){ g.drawImage(piece.getImage(),(locx*Chess.SQUARE_WIDTH),(locy*Chess.SQUARE_HEIGHT),null); } } ``` Other suggestions: * Create `JFrame` and other Swing components on [EDT](http://docs.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html) by wrapping UI creation code in ``` SwingUtilities.invokeLater(new Runnable(){ @Override public void run() { //create ui here } }); ``` * Dont call `setSize(...)` on `JFrame` rather override `JPanel` `getPreferredSize()` and return an appropriate size which fits components etc than you can remove `setSize` call on `JFrame` and call `pack()` on `JFrame` instance before setting visible
It seems like your variable `board` is not initialized yet. You need to call `setCanvas()` first to initialize it, then you can call `drawPiece()`.
47,491,642
After changing my theme on my website, my articles do not show the hole article. it seems to only display the first part of the article and then it shows [...] I have changed the settings to display hole article. Am i missing another setting or is this a code error? You can view the website here [www.greywatershop.com.au][1] ``` [1]: http://www.greywatershop.com.au/blog Code for archives.php <?php /** * The template for displaying archive pages * * @link https://codex.wordpress.org/Template_Hierarchy * * @package Shopper */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <?php the_archive_title( '<h1 class="page-title">', '</h1>' ); ?> </header><!-- .page-header --> <?php get_template_part( 'loop' ); else : get_template_part( 'content', 'none' ); endif; ?> </main><!-- #main --> </div><!-- #primary --> <?php do_action( 'shopper_sidebar' ); get_footer(); ```
2017/11/25
[ "https://Stackoverflow.com/questions/47491642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2130954/" ]
Elegant solution for a two characters alphabet ---------------------------------------------- Since you only have two letters in your alphabet, an elegant solution could be to use binary decomposition of integers (`a` represents a binary `0` and `b` represents a `1`). Here's the algorithm you could implement: ``` private static final int MAX_LENGTH = 3; public static void main(String[] args) { int wordLength = 1; int current = 0; int max = (1 << wordLength) - 1; while (wordLength <= MAX_LENGTH) { System.out.println(makeWord(current, wordLength)); if (current < max) current++; else { wordLength++; current = 0; max = (1 << wordLength) - 1; } } } private static String makeWord(int current, int wordLength) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < wordLength; i++) { sb.append((char) ((current % 2) + 'a')); current >>= 1; } return sb.reverse().toString(); } ``` Output: ``` a b aa ab ba bb aaa aab aba abb baa bab bba bbb ``` General solution for any alphabet --------------------------------- You can generalize the above solution by counting in base `k` (where `k` is the size of the alphabet) instead of 2. It could look like this: ``` public static void main(String[] args) { listWords(new char[]{ 'e', 'z', 'f' }, 3); } private static void listWords(char[] alphabet, int maxWordLength) { Arrays.sort(alphabet); int base = alphabet.length; int wordLength = 1; int current = 0; int max = (int) Math.pow(base, wordLength) - 1; while (wordLength <= maxWordLength) { System.out.println(makeWord(alphabet, current, wordLength)); if (current < max) current++; else { wordLength++; current = 0; max = (int) Math.pow(base, wordLength) - 1; } } } private static String makeWord(char[] alphabet, int current, int wordLength) { int base = alphabet.length; StringBuilder sb = new StringBuilder(); for (int i = 0; i < wordLength; i++) { sb.append(alphabet[current % base]); current /= base; } return sb.reverse().toString(); } ``` Output: ``` e f z ee ef ez fe ff fz ze zf zz eee eef eez efe eff efz eze ezf ezz fee fef fez ffe fff ffz fze fzf fzz zee zef zez zfe zff zfz zze zzf zzz ``` Note that this implementation will be much slower than the previous one because divisions and `Math.pow` are slow operations compared to binary shifts. Non-arithmetic general solution ------------------------------- The logic of counting in base `k` can also be implemented manually. It might be more efficient but will definitely take more time and code. Below is the general idea of the algorithm: * you start by filling the string with the lowest value * then, you increment the value of the last character * when you can't increment anymore, you reset all the characters at the right of your current position * you increment your position, and increment the value of this position * you start all over again doing the same thing from the right of the string What's cool about this is that if you use a `StringBuilder`, you can minimize the number of array allocation to only one per iteration since each state of the `StringBuilder` can be reached in a few operations (proportional the the length of the string) from the previous state.
By following @Dici's approach, I've written this code that specifically solves my problem. ``` public class SigmaStar { //max length of word, just to limit the execution //change it with your own value private static final int MAX_LENGTH = 4; public static void main(String[] args) { int wordLength = 0; int current = 0; int max = (1 << wordLength) - 1; while (wordLength <= MAX_LENGTH) { System.out.println("'"+makeWord(current, wordLength)+"'"); if (current < max) current++; else { wordLength++; current = 0; max = (1 << wordLength) - 1; } } } private static String makeWord(int current, int wordLength) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < wordLength; i++) { sb.append((char) ((current % 2) + 'a')); current >>= 1; } return sb.reverse().toString(); } } ```
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
`SharedPreferences` are managed internally by Android as singletons. You can get as many instances as you want using: ``` context.getSharedPreferences(name, mode); ``` as long as you use the same **name**, you'll always get the same **instance**. Therefore there are no concurrency problems.
I will prefer using a **singleton** class for preference, *initialize preference once by application context*. create getter and setter(get/put) methods to add, update and delete data. This way it will create instance once and can be more readable,reusable.
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
It is worth reviewing the [sources](http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/2.3.7_r1/android/app/ContextImpl.java/?v=source) that show that a `Context` instance (be it an `Activity` or an `Application` instance) share the same static map `HashMap<String, SharedPreferencesImpl>`. So whenever you request an instance of `SharedPreferences` by the same name via `Context.getSharedPreferences(name, mode)` you get the same instance since it first checks if the map already contains `SharedPreferences` instance for a key (which is the passed name). Once `SharedPreferences` instance is loaded it will not be loaded again, but taken from the map instead. So it actually does not matter which way you go, the important thing is to use the same name in order to get the same prefs from different parts of the application. However creating a single "access point" for the prefs could be a plus. So it could be a singleton wrapper over the prefs instantiated in `Application.onCreate()`.
I will prefer using a **singleton** class for preference, *initialize preference once by application context*. create getter and setter(get/put) methods to add, update and delete data. This way it will create instance once and can be more readable,reusable.
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
I will prefer using a **singleton** class for preference, *initialize preference once by application context*. create getter and setter(get/put) methods to add, update and delete data. This way it will create instance once and can be more readable,reusable.
We can make a Preferences Singleton Class and make instance of that class in extended Application class with applicationContext, so we may use that object in whole application I have made a sharedPreferenceManager Class and make a static object by providing applicationContext. Now static object can be accessible anywhere in project ``` public class App extends Application { public static App myApp; public static PreferenceManagerSignlton preferenceManagerSingleton; @Override public void onCreate() { super.onCreate(); myApp = this; preferenceManagerSingleton = new PreferenceManagerSignlton(); preferenceSingleton.initialize(getApplicationContext()); } } ``` Accessing static object in project ``` App.myapp.PreferenceManagerSignltonz.getSavedValue(); ```
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
It is worth reviewing the [sources](http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/2.3.7_r1/android/app/ContextImpl.java/?v=source) that show that a `Context` instance (be it an `Activity` or an `Application` instance) share the same static map `HashMap<String, SharedPreferencesImpl>`. So whenever you request an instance of `SharedPreferences` by the same name via `Context.getSharedPreferences(name, mode)` you get the same instance since it first checks if the map already contains `SharedPreferences` instance for a key (which is the passed name). Once `SharedPreferences` instance is loaded it will not be loaded again, but taken from the map instead. So it actually does not matter which way you go, the important thing is to use the same name in order to get the same prefs from different parts of the application. However creating a single "access point" for the prefs could be a plus. So it could be a singleton wrapper over the prefs instantiated in `Application.onCreate()`.
`SharedPreferences` are managed internally by Android as singletons. You can get as many instances as you want using: ``` context.getSharedPreferences(name, mode); ``` as long as you use the same **name**, you'll always get the same **instance**. Therefore there are no concurrency problems.
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
`SharedPreferences` are managed internally by Android as singletons. You can get as many instances as you want using: ``` context.getSharedPreferences(name, mode); ``` as long as you use the same **name**, you'll always get the same **instance**. Therefore there are no concurrency problems.
We can make a Preferences Singleton Class and make instance of that class in extended Application class with applicationContext, so we may use that object in whole application I have made a sharedPreferenceManager Class and make a static object by providing applicationContext. Now static object can be accessible anywhere in project ``` public class App extends Application { public static App myApp; public static PreferenceManagerSignlton preferenceManagerSingleton; @Override public void onCreate() { super.onCreate(); myApp = this; preferenceManagerSingleton = new PreferenceManagerSignlton(); preferenceSingleton.initialize(getApplicationContext()); } } ``` Accessing static object in project ``` App.myapp.PreferenceManagerSignltonz.getSavedValue(); ```
11,567,134
I am using several SharedPreferences to store data in my app. Some preferences are used in a lot of activites. I know that the SharedPreferences are internally backed by a map for fast read-access and written to sdcard when settings are changed. I wonder which way is better if a sharedpreference is accessed by a lot of activies: 1. Instantiate it in every activity using the activity context. 2. Instantiate it in every activity, but using the application context. 3. Put it in e.g. the Application class and instantiate it only once there, similar to a singleton. If I use 1. solution is there a sharedpreference object for every activity? And will the sharedpreference's internal map get destroyed when the activity is destroyed? If I use 2. solution will there be only one instance although I call getSharedPreferences in every activity? And will the internal map be in memory as long as the application is alive? Hopefully someone knows how Android handles it internally.
2012/07/19
[ "https://Stackoverflow.com/questions/11567134", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1164971/" ]
It is worth reviewing the [sources](http://grepcode.com/file_/repository.grepcode.com/java/ext/com.google.android/android/2.3.7_r1/android/app/ContextImpl.java/?v=source) that show that a `Context` instance (be it an `Activity` or an `Application` instance) share the same static map `HashMap<String, SharedPreferencesImpl>`. So whenever you request an instance of `SharedPreferences` by the same name via `Context.getSharedPreferences(name, mode)` you get the same instance since it first checks if the map already contains `SharedPreferences` instance for a key (which is the passed name). Once `SharedPreferences` instance is loaded it will not be loaded again, but taken from the map instead. So it actually does not matter which way you go, the important thing is to use the same name in order to get the same prefs from different parts of the application. However creating a single "access point" for the prefs could be a plus. So it could be a singleton wrapper over the prefs instantiated in `Application.onCreate()`.
We can make a Preferences Singleton Class and make instance of that class in extended Application class with applicationContext, so we may use that object in whole application I have made a sharedPreferenceManager Class and make a static object by providing applicationContext. Now static object can be accessible anywhere in project ``` public class App extends Application { public static App myApp; public static PreferenceManagerSignlton preferenceManagerSingleton; @Override public void onCreate() { super.onCreate(); myApp = this; preferenceManagerSingleton = new PreferenceManagerSignlton(); preferenceSingleton.initialize(getApplicationContext()); } } ``` Accessing static object in project ``` App.myapp.PreferenceManagerSignltonz.getSavedValue(); ```
3,101,545
I'm trying to index the GAC and use the `ResolveAssemblyReferences` target. However, some assemblies (such as Unity application block) seem to be missing from the GAC and yet VS happily shows them in the Add Reference dialog. My question: how can this be? I always thought that only GAC-registered assemblies appear there. Am I missing something?
2010/06/23
[ "https://Stackoverflow.com/questions/3101545", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9476/" ]
In addition to the registry setting ckramer mentioned, there is also `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v2.0.50727\AssemblyFoldersEx` and `HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework\v4.0.30319\AssemblyFoldersEx`. Tip: if you download the [VS 2010 Pro Power Tools](http://visualstudiogallery.msdn.microsoft.com/en-us/d0d33361-18e2-46c0-8ff2-4adea1e34fef) extension, the updated "Add Reference" dialog clearly distinguishes between Framework assemblies and Framework Extension assemblies.
There is actually a registry setting which allows you to add directories to the list of locations where Visual Studio will search for assemblies to display in the "Add References" dialog. [Here](http://www.csharp411.com/adding-assemblies-to-the-visual-studio-add-reference-dialog/) is a quick overview of where it is and how to add your own paths to it.
14,896,607
My application is navigation based and mainly runs in portrait orientation, But one view controller supports both portrait and landscape orientation. Now the problem is, When I push the new viewcontroller from landscape view controller, the new view controller is also pushed in landscape mode though i want it in portrait mode. Also when I pop view controller from landscape controller then the poped view controller is getting displayed in portrait mode. I don't know what is wrong with my code. Here is the my code snippet and information used for these orientation support. In info.plist file I kept support for all orientation but portrait upsidedown. I have also added category for navigation controller category as below. ``` @implementation UINavigationController(Rotation_IOS6) -(BOOL)shouldAutorotate { return [[self.viewControllers lastObject] shouldAutorotate]; } -(NSUInteger)supportedInterfaceOrientations { return [[self.viewControllers lastObject] supportedInterfaceOrientations]; } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation { return [[self.viewControllers lastObject] preferredInterfaceOrientationForPresentation]; } @end ``` I have also created a UIViewController subclass that acts as superclass for all classes. Here are the orientation methods for super class. ``` @implementation ParentViewController - (BOOL)shouldAutorotate{ return NO; } - (NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskPortrait; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{ return (toInterfaceOrientation == UIInterfaceOrientationPortrait); } - (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation{ return UIInterfaceOrientationPortrait; } @end ``` And the orientation methods controller that supports landscape are as below. ``` @implementation LandscapeController #pragma mark - #pragma mark Orientation Methods - (BOOL)shouldAutorotate{ return YES; } - (NSUInteger)supportedInterfaceOrientations{ return UIInterfaceOrientationMaskPortrait|UIInterfaceOrientationMaskLandscape; } -(BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation{ return (toInterfaceOrientation != UIInterfaceOrientationPortraitUpsideDown); } @end ``` Thanks in advance.
2013/02/15
[ "https://Stackoverflow.com/questions/14896607", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1838063/" ]
I found a solution to this. It's bloody witchcraft, but it works. When you install the client, open **Control Panel > Network Connections**. You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such). Right Click it, click **Enable**. The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.
It seems to me you are using the wrong version... TAP-Win32 should not be installed on the 64bit version. Download the right one and try again!
65,028,698
I have two files. File1 with data ``` DF2SVT-(.CD(),.CP(clk),.D(),.SDN(),.Q(na)); OAI3DSVT-(.A1(na),.A2(),.A3(),.B(),.ZN(y)); GLHSVT-(.D(v),.E(),.Q(y)); DCCDSVT-(.I(w),.ZN(y)); ``` and file2 with data ``` GLHSVT-(.D(v),.E(),.Q(y)); ``` If the line in file2 is present in file1 then remove that line from file1 and print rest of the lines of file1. So I want output file fout as ``` DF2SVT-(.CD(),.CP(clk),.D(),.SDN(),.Q(na)); OAI3DSVT-(.A1(na),.A2(),.A3(),.B(),.ZN(y)); DCCDSVT-(.I(w),.ZN(y)); ``` I know how to print common lines between two files using ``` for line in file1 & file2: if line: print line ``` But I am not getting how to remove that common line from file if match is there.
2020/11/26
[ "https://Stackoverflow.com/questions/65028698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12346657/" ]
Read the lines of both files into a separate variables. Iterate over the lines of the first file, and for each of one them check if they exist on the second file, if not then save them into the first file. ``` with open(file1, "r") as file1: lines_file1 = file1.readlines() with open(file, "r") as file2: lines_file2 = file2.readlines() with open(file1, "w") as f_w: for line in lines_file1: if line not in lines_file2 f_w.write(line) ``` The downside of this approach is that you are loading the entire files into memory.
You can use **set operations** to do this with few lines of code. Read two file and convert the list of lines into the set and use set operations ``` line_file1 = set(line_file1) line_file2 = set(line_file2) result = line_file1 - line_file2 ``` Now write the **result** set each element (line) to the file. **Note**: repeated data in file1 will be also removed.
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` 'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g); ``` the bounding quotes get included though
Expanding on the accepted answer, here's a search engine parser that, * can match phrases or words * treats phrases as regular expressions * does a boolean OR across multiple properties (e.g. item.title and item.body) * handles negation of words or phrases when they are prefixed with - Treating phrases as regular expressions makes the UI simpler for my purposes. ```js const matchOrIncludes = (str, search, useMatch = true) => { if (useMatch) { let result = false try { result = str.match(search) } catch (err) { return false } return result } return str.includes(search) } const itemMatches = (item, searchString, fields) => { const keywords = searchString.toString().replace(/\s\s+/g, ' ').trim().toLocaleLowerCase().match(/(-?"[^"]+"|[^"\s]+)/g) || [] for (let i = 0; i < keywords.length; i++) { const negateWord = keywords[i].startsWith('-') ? true : false let word = keywords[i].replace(/^-/,'') const isPhraseRegex = word.startsWith('"') ? true : false if (isPhraseRegex) { word = word.replace(/^"(.+)"$/,"$1") } let word_in_item = false for (const field of fields) { if (item[field] && matchOrIncludes(item[field].toLocaleLowerCase(), word, isPhraseRegex)) { word_in_item = true break } } if ((! negateWord && ! word_in_item) || (negateWord && word_in_item)) { return false } } return true } const item = {title: 'My title', body: 'Some text'} console.log(itemMatches(item, 'text', ['title', 'body'])) ```
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); ``` ... returns the array you're looking for. Note, however: * Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results. * Spaces between the quotes will stay intact. So, if there are three spaces between `lorem` and `ipsum`, they'll be in the result. You can fix this by running `replace(/\s+/," ")` on the results. * If there's no closing `"` after `ipsum` (i.e. an incorrectly-quoted phrase) you'll end up with: `['foo', 'bar', 'lorem', 'ipsum', 'baz']`
One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like `"hello my name is 'jon delaware smith fred' I have a 'long name'"`.... A bit like the answer by AC but a bit neater... ``` function split(input, delimiter, joiner){ var output = []; var joint = []; input.split(delimiter).forEach(function(element){ if (joint.length > 0 && element.indexOf(joiner) === element.length - 1) { output.push(joint.join(delimiter) + delimiter + element); joint = []; } if (joint.length > 0 || element.indexOf(joiner) === 0) { joint.push(element); } if (joint.length === 0 && element.indexOf(joiner) !== element.length - 1) { output.push(element); joint = []; } }); return output; } ```
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A simple regular expression will do but leave the quotation marks. e.g. ``` 'foo bar "lorem ipsum" baz'.match(/("[^"]*")|([^\s"]+)/g) output: ['foo', 'bar', '"lorem ipsum"', 'baz'] ``` edit: beaten to it by shyamsundar, sorry for the double answer
``` 'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g); ``` the bounding quotes get included though
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Try this: ``` var input = 'foo bar "lorem ipsum" baz'; var R = /(\w|\s)*\w(?=")|\w+/g; var output = input.match(R); output is ["foo", "bar", "lorem ipsum", "baz"] ``` Note there are no extra double quotes around lorem ipsum Although it assumes the input has the double quotes in the right place: ``` var input2 = 'foo bar lorem ipsum" baz'; var output2 = input2.match(R); var input3 = 'foo bar "lorem ipsum baz'; var output3 = input3.match(R); output2 is ["foo bar lorem ipsum", "baz"] output3 is ["foo", "bar", "lorem", "ipsum", "baz"] ``` And won't handle escaped double quotes (is that a problem?): ``` var input4 = 'foo b\"ar bar\" \"bar "lorem ipsum" baz'; var output4 = input4.match(R); output4 is ["foo b", "ar bar", "bar", "lorem ipsum", "baz"] ```
how about, ``` output = /(".+?"|\w+)/g.exec(input) ``` then do a pass on output to lose the quotes. alternately, ``` output = /"(.+?)"|(\w+)/g.exec(input) ``` then do a pass n output to lose the empty captures.
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); ``` ... returns the array you're looking for. Note, however: * Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results. * Spaces between the quotes will stay intact. So, if there are three spaces between `lorem` and `ipsum`, they'll be in the result. You can fix this by running `replace(/\s+/," ")` on the results. * If there's no closing `"` after `ipsum` (i.e. an incorrectly-quoted phrase) you'll end up with: `['foo', 'bar', 'lorem', 'ipsum', 'baz']`
A simple regular expression will do but leave the quotation marks. e.g. ``` 'foo bar "lorem ipsum" baz'.match(/("[^"]*")|([^\s"]+)/g) output: ['foo', 'bar', '"lorem ipsum"', 'baz'] ``` edit: beaten to it by shyamsundar, sorry for the double answer
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` 'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g); ``` the bounding quotes get included though
One that's easy to understand and a general solution. Works for all delimiters and 'join' characters. Also supports 'joined' words that are more than two words in length.... ie lists like `"hello my name is 'jon delaware smith fred' I have a 'long name'"`.... A bit like the answer by AC but a bit neater... ``` function split(input, delimiter, joiner){ var output = []; var joint = []; input.split(delimiter).forEach(function(element){ if (joint.length > 0 && element.indexOf(joiner) === element.length - 1) { output.push(joint.join(delimiter) + delimiter + element); joint = []; } if (joint.length > 0 || element.indexOf(joiner) === 0) { joint.push(element); } if (joint.length === 0 && element.indexOf(joiner) !== element.length - 1) { output.push(element); joint = []; } }); return output; } ```
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
ES6 solution supporting: * Split by space except for inside quotes * Removing quotes but not for backslash escaped quotes * Escaped quote become quote Code: ``` input.match(/\\?.|^$/g).reduce((p, c) => { if(c === '"'){ p.quote ^= 1; }else if(!p.quote && c === ' '){ p.a.push(''); }else{ p.a[p.a.length-1] += c.replace(/\\(.)/,"$1"); } return p; }, {a: ['']}).a ``` Output: ``` [ 'foo', 'bar', 'lorem ipsum', 'baz' ] ```
Expanding on the accepted answer, here's a search engine parser that, * can match phrases or words * treats phrases as regular expressions * does a boolean OR across multiple properties (e.g. item.title and item.body) * handles negation of words or phrases when they are prefixed with - Treating phrases as regular expressions makes the UI simpler for my purposes. ```js const matchOrIncludes = (str, search, useMatch = true) => { if (useMatch) { let result = false try { result = str.match(search) } catch (err) { return false } return result } return str.includes(search) } const itemMatches = (item, searchString, fields) => { const keywords = searchString.toString().replace(/\s\s+/g, ' ').trim().toLocaleLowerCase().match(/(-?"[^"]+"|[^"\s]+)/g) || [] for (let i = 0; i < keywords.length; i++) { const negateWord = keywords[i].startsWith('-') ? true : false let word = keywords[i].replace(/^-/,'') const isPhraseRegex = word.startsWith('"') ? true : false if (isPhraseRegex) { word = word.replace(/^"(.+)"$/,"$1") } let word_in_item = false for (const field of fields) { if (item[field] && matchOrIncludes(item[field].toLocaleLowerCase(), word, isPhraseRegex)) { word_in_item = true break } } if ((! negateWord && ! word_in_item) || (negateWord && word_in_item)) { return false } } return true } const item = {title: 'My title', body: 'Some text'} console.log(itemMatches(item, 'text', ['title', 'body'])) ```
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A simple regular expression will do but leave the quotation marks. e.g. ``` 'foo bar "lorem ipsum" baz'.match(/("[^"]*")|([^\s"]+)/g) output: ['foo', 'bar', '"lorem ipsum"', 'baz'] ``` edit: beaten to it by shyamsundar, sorry for the double answer
how about, ``` output = /(".+?"|\w+)/g.exec(input) ``` then do a pass on output to lose the quotes. alternately, ``` output = /"(.+?)"|(\w+)/g.exec(input) ``` then do a pass n output to lose the empty captures.
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
``` var str = 'foo bar "lorem ipsum" baz'; var results = str.match(/("[^"]+"|[^"\s]+)/g); ``` ... returns the array you're looking for. Note, however: * Bounding quotes are included, so can be removed with `replace(/^"([^"]+)"$/,"$1")` on the results. * Spaces between the quotes will stay intact. So, if there are three spaces between `lorem` and `ipsum`, they'll be in the result. You can fix this by running `replace(/\s+/," ")` on the results. * If there's no closing `"` after `ipsum` (i.e. an incorrectly-quoted phrase) you'll end up with: `['foo', 'bar', 'lorem', 'ipsum', 'baz']`
``` 'foo bar "lorem ipsum" baz'.match(/"[^"]*"|\w+/g); ``` the bounding quotes get included though
64,904
I need to support exact phrases (enclosed in quotes) in an otherwise space-separated list of terms. Thus splitting the respective string by the space-character is not sufficient anymore. Example: ``` input : 'foo bar "lorem ipsum" baz' output: ['foo', 'bar', 'lorem ipsum', 'baz'] ``` I wonder whether this could be achieved with a single RegEx, rather than performing complex parsing or split-and-rejoin operations. Any help would be greatly appreciated!
2008/09/15
[ "https://Stackoverflow.com/questions/64904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Thanks a lot for the quick responses! Here's a summary of the options, for posterity: ``` var input = 'foo bar "lorem ipsum" baz'; output = input.match(/("[^"]+"|[^"\s]+)/g); output = input.match(/"[^"]*"|\w+/g); output = input.match(/("[^"]*")|([^\s"]+)/g) output = /(".+?"|\w+)/g.exec(input); output = /"(.+?)"|(\w+)/g.exec(input); ``` For the record, here's the abomination I had come up with: ``` var input = 'foo bar "lorem ipsum" "dolor sit amet" baz'; var terms = input.split(" "); var items = []; var buffer = []; for(var i = 0; i < terms.length; i++) { if(terms[i].indexOf('"') != -1) { // outer phrase fragment -- N.B.: assumes quote is either first or last character if(buffer.length === 0) { // beginning of phrase //console.log("start:", terms[i]); buffer.push(terms[i].substr(1)); } else { // end of phrase //console.log("end:", terms[i]); buffer.push(terms[i].substr(0, terms[i].length - 1)); items.push(buffer.join(" ")); buffer = []; } } else if(buffer.length != 0) { // inner phrase fragment //console.log("cont'd:", terms[i]); buffer.push(terms[i]); } else { // individual term //console.log("standalone:", terms[i]); items.push(terms[i]); } //console.log(items, "\n", buffer); } items = items.concat(buffer); //console.log(items); ```
ES6 solution supporting: * Split by space except for inside quotes * Removing quotes but not for backslash escaped quotes * Escaped quote become quote Code: ``` input.match(/\\?.|^$/g).reduce((p, c) => { if(c === '"'){ p.quote ^= 1; }else if(!p.quote && c === ' '){ p.a.push(''); }else{ p.a[p.a.length-1] += c.replace(/\\(.)/,"$1"); } return p; }, {a: ['']}).a ``` Output: ``` [ 'foo', 'bar', 'lorem ipsum', 'baz' ] ```
51,046,476
I am trying to import the account circle icon from material-ui icons, but I am getting this error: > > export 'default' (imported as 'AccountCircle') was not found in '@material-ui/icons/es'. > > > I am not sure what it means. Thanks in advance.
2018/06/26
[ "https://Stackoverflow.com/questions/51046476", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8684976/" ]
Assuming your `photos` array contains an array of file system paths of the uploaded photos, Your FormData should be looped through like this: ``` const data = new FormData() photos.forEach((element, i) => { const newFile = { uri: element, type: 'image/jpg' } data.append('files', newFile) }); ``` Then you can attach this variable `data` to your post request to upload the array of files to server.
``` const data = new FormData() photos.forEach((element, i) => { const newFile = { uri: element, type: 'image/jpg' } data.append('files[]', newFile) }); ``` docs say <https://developer.mozilla.org/en-US/docs/Web/API/FormData/append#Example>
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
no need to echo json encode two times....merge the array and send the data....... ``` echo json_encode(array('result1'=>$arr1,'result2'=>$arr2)); ``` and get data by ``` initChart2(data.result1,data.result2); ```
You cannot get multiple object like that. For a JSON object, you will need to have single object. So what you can do is, create a wrapper object put those two array inside it. So basically, your php code will be: ``` <?php $arr= array(); $arr['arr1'] = $arr1; $arr['arr2'] = $arr2; echo json_encode($arr); ?> ``` So now you will have single main array and so single JSON object. On JS side, you will get single data. Little Modification will be ``` $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { var data21=data['arr1']; var data22=data['arr2']; initChart2(data21,data22); } }); ``` This should work.
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
You cannot get multiple object like that. For a JSON object, you will need to have single object. So what you can do is, create a wrapper object put those two array inside it. So basically, your php code will be: ``` <?php $arr= array(); $arr['arr1'] = $arr1; $arr['arr2'] = $arr2; echo json_encode($arr); ?> ``` So now you will have single main array and so single JSON object. On JS side, you will get single data. Little Modification will be ``` $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { var data21=data['arr1']; var data22=data['arr2']; initChart2(data21,data22); } }); ``` This should work.
You need to combine both array using `array_merge()`. **Example** ``` $response = array(); $response = array_merge($arr1,$arr2); echo json_encode($response); ```
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
See if you are able to produce two object arrays of json then you can try with this: ``` var data21,data22; $.ajax({ type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { $.each(data, function(i, item){ data21 = item.data21; data22 = item.data22; }); initChart2(data21,data22); } }); ``` and i am supposing if you are able to produce this: ``` [ { "data21": { ......... }, "data22": { ........ } } ] ```
You cannot get multiple object like that. For a JSON object, you will need to have single object. So what you can do is, create a wrapper object put those two array inside it. So basically, your php code will be: ``` <?php $arr= array(); $arr['arr1'] = $arr1; $arr['arr2'] = $arr2; echo json_encode($arr); ?> ``` So now you will have single main array and so single JSON object. On JS side, you will get single data. Little Modification will be ``` $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { var data21=data['arr1']; var data22=data['arr2']; initChart2(data21,data22); } }); ``` This should work.
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
no need to echo json encode two times....merge the array and send the data....... ``` echo json_encode(array('result1'=>$arr1,'result2'=>$arr2)); ``` and get data by ``` initChart2(data.result1,data.result2); ```
You need to combine both array using `array_merge()`. **Example** ``` $response = array(); $response = array_merge($arr1,$arr2); echo json_encode($response); ```
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
no need to echo json encode two times....merge the array and send the data....... ``` echo json_encode(array('result1'=>$arr1,'result2'=>$arr2)); ``` and get data by ``` initChart2(data.result1,data.result2); ```
See if you are able to produce two object arrays of json then you can try with this: ``` var data21,data22; $.ajax({ type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { $.each(data, function(i, item){ data21 = item.data21; data22 = item.data22; }); initChart2(data21,data22); } }); ``` and i am supposing if you are able to produce this: ``` [ { "data21": { ......... }, "data22": { ........ } } ] ```
15,676,722
I want to build a graph in jqchart where i need to get two arrays Now i want to perform operation as given below.Which is giving error ofcourse. ``` html $.ajax( { type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data21,data22) { initChart2(data21,data22); } }); function initChart2(data21,data22) { $('#jqChart2').jqChart({ series: [ { type: 'column', title: 'no of days ', data:data21, }, { type: 'column', title: 'no of days ', data:data22, }, ] }); } ``` heres PHP code ``` echo json_encode($arr1); echo json_encode($arr2); ``` So any one has idea of how to do it?
2013/03/28
[ "https://Stackoverflow.com/questions/15676722", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1814087/" ]
See if you are able to produce two object arrays of json then you can try with this: ``` var data21,data22; $.ajax({ type: "GET", url: "customer_coverage.php", data: {id:id}, contentType: "application/json", dataType: "json", success: function (data) { $.each(data, function(i, item){ data21 = item.data21; data22 = item.data22; }); initChart2(data21,data22); } }); ``` and i am supposing if you are able to produce this: ``` [ { "data21": { ......... }, "data22": { ........ } } ] ```
You need to combine both array using `array_merge()`. **Example** ``` $response = array(); $response = array_merge($arr1,$arr2); echo json_encode($response); ```
45,786,448
I created a standard nav menu. my `home.html` has a slider component. this slider component can be navigated using few links that invoke the `goToSlide()` method exposed using ``` @ViewChild(Slides) slides: Slides; ``` As the side navigator menu is implemented and accessible via `app.component.ts` so how do i get access to slides component defined in `home.ts` ? hime.html ``` <ion-header> <ion-navbar no-padding> <button ion-button menuToggle> <ion-icon name="menu"></ion-icon> </button> <ion-title style="background-color:#2298D3"> <ion-row><ion-col text-left> <img (click)="goToSlide(0)" src="assets/images/white_logo_color_background.jpg" width="20%" /> </ion-col> <ion-col text-right> <button ion-button clear (click)="goToSlide(1)" style="color:white">Services</button> <button ion-button clear (click)="goToSlide(2)" style="color:white">Contact Us</button> </ion-col> </ion-row> </ion-title> </ion-navbar> </ion-header> <ion-content no-padding> <ion-slides direction="horizontal" speed="1000" slidesPerView="1" pager="true"> <ion-slide class="home-intro" style="background-color:#2298D3;max-height:440px"> </ion-slide> <ion-slide padding class="site-slide" > <ion-row> <ion-row> </ion-slide> </ion-slides> </ion-content> ``` home.ts ``` import { Component } from '@angular/core'; import { NavController, Slides } from 'ionic-angular'; import { ViewChild } from '@angular/core'; import { FormBuilder, FormGroup, Validators } from '@angular/forms'; import { SendEnquiryService } from '../../providers/send-enquiry.service' @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage { @ViewChild(Slides) slides: Slides; slideTwoForm: FormGroup; constructor(public navCtrl: NavController, public formBuilder: FormBuilder, public enquiryService:SendEnquiryService) { } goToSlide(num){ this.slides.slideTo(num, 500); } ``` } app.components.ts: ``` import { Component, ViewChild } from '@angular/core'; import { Nav, Platform, Slides, Events } from 'ionic-angular'; import { StatusBar } from '@ionic-native/status-bar'; import { SplashScreen } from '@ionic-native/splash-screen'; import { HomePage } from '../pages/home/home'; @Component({ templateUrl: 'app.html' }) export class MyApp { rootPage:any = HomePage; @ViewChild(Nav) nav: Nav; constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen, public events: Events) { platform.ready().then(() => { // Okay, so the platform is ready and our plugins are available. // Here you can do any higher level native things you might need. statusBar.styleDefault(); splashScreen.hide(); this.nav.setRoot(HomePage); }); } goToSlide(index){ this.changeCurrentSlide(index); } changeCurrentSlide(index) { this.events.publish('slider:slideTo', index); } } ```
2017/08/20
[ "https://Stackoverflow.com/questions/45786448", "https://Stackoverflow.com", "https://Stackoverflow.com/users/135982/" ]
You can use [Events](https://ionicframework.com/docs/api/util/Events/). In your `home.ts` file subscribe to an event that will change the current slide: ``` import { Events } from 'ionic-angular'; @ViewChild(Slides) slides: Slides; constructor(public events: Events) { events.subscribe('slider:slideTo', (index) => { if(this.slides) { this.slides.slideTo(index, 500); } else { console.log('Tried to modify the slides but they were not loaded yet'); } }); } ``` And in your `app.component.ts` file, just publish that event when needed: ``` import { Events } from 'ionic-angular'; constructor(public events: Events) {} changeCurrentSlide(index) { this.events.publish('slider:slideTo', index); } ```
You could just insert a slider component on that page too? If you want the slider component to be defined only in the app component you could: 1.: emit an event in the home.ts which would be listened to in the app.component. 2.: make a slider.service.ts which you inject in your he component and in your app.component or directly in your slider.component(if it's not third party). The slider service could have a public eventemitter which u'd use or a rxjs Subject. This way you can notify a component from within another component.
10,781,185
What I am trying to do is something similar to how collaborative editor works. I want to allow two people to edit the same document. And for this I have to simulate an artificial caret. I can extract the other user's activity in term of addition and deletion at specified location in a textarea. I will then transmit the location, along with the action to the other document. There I need to carry out the required change at the sent coordinate. I have searched and found enough ways to set the caret location and insert or delete text at the current caret location, but the problem is that the caret of the document moves to the location at which I make the change. I don't want that, I want to have two carets, one each for the two users. Transmit their changes to each other documents and make the changes at their respective locations, while showing two different carets. I just need to know if there are certain libraries that I can use, or even if I have to make this on my own, then how and where do I start. I don't even know how a textarea is represented within a browser. How can I characterize locations within a textarea, if I know that then I save the locations in memory and make the changes based on the input received. I hope I make sense, thanks for any help.
2012/05/28
[ "https://Stackoverflow.com/questions/10781185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538191/" ]
have you seen this? <https://github.com/benjamn/kix-standalone/> This is how google docs does it: <https://drive.googleblog.com/2010/05/whats-different-about-new-google-docs.html>
Have you tried Draft.js, from facebook ? <https://facebook.github.io/draft-js/> "Draft.js is a framework for building rich text editors in React, powered by an immutable model and abstracting over cross-browser differences. Draft.js makes it easy to build any type of rich text input, whether you're just looking to support a few inline text styles or building a complex text editor for composing long-form articles. In Draft.js, everything is customizable – we provide the building blocks so that you have full control over the user interface."
10,781,185
What I am trying to do is something similar to how collaborative editor works. I want to allow two people to edit the same document. And for this I have to simulate an artificial caret. I can extract the other user's activity in term of addition and deletion at specified location in a textarea. I will then transmit the location, along with the action to the other document. There I need to carry out the required change at the sent coordinate. I have searched and found enough ways to set the caret location and insert or delete text at the current caret location, but the problem is that the caret of the document moves to the location at which I make the change. I don't want that, I want to have two carets, one each for the two users. Transmit their changes to each other documents and make the changes at their respective locations, while showing two different carets. I just need to know if there are certain libraries that I can use, or even if I have to make this on my own, then how and where do I start. I don't even know how a textarea is represented within a browser. How can I characterize locations within a textarea, if I know that then I save the locations in memory and make the changes based on the input received. I hope I make sense, thanks for any help.
2012/05/28
[ "https://Stackoverflow.com/questions/10781185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/538191/" ]
You could mimic a caret with a special character and do the regex to insert the partner text and move his caret, and you can use the real one. This is the simplest design I can think. To get the idead, you could use the pipe `|` as a artificial caret. but this would easily conflict with user insert a pipe, to avoid this you can use sort of uncommon combination, or find some unicode character to act as a caret. A real solution but way more complicated is not use a textarea, and use a DIV. this means that you need to handle all the key events and insert the character pressed manually to the document, and register the cursor position. But this way you can insert how many carets you want not just 2, something like this `<span class="caret1"></span>` you can make it blink, style with css, have diferent color for each caret, etc.
Have you tried Draft.js, from facebook ? <https://facebook.github.io/draft-js/> "Draft.js is a framework for building rich text editors in React, powered by an immutable model and abstracting over cross-browser differences. Draft.js makes it easy to build any type of rich text input, whether you're just looking to support a few inline text styles or building a complex text editor for composing long-form articles. In Draft.js, everything is customizable – we provide the building blocks so that you have full control over the user interface."
22,714,820
I have an image to be used a background in activity: ![enter image description here](https://i.stack.imgur.com/MfXu0.png) I want this image to fit screen by its height. It means that for wide-screen smartphones, I want my image to be fit by height and centered: ![enter image description here](https://i.stack.imgur.com/G8aXH.png) and for square-screen smartphones, I want my image to be cut: ![enter image description here](https://i.stack.imgur.com/84K02.png) I use `ImageView` for the image. What `scaleType` should I use? Looking at the second figure, I'd say to use `android:scaleType="centerInside"`. But looking at the third, I'd say to use `android:scaleType="centerCrop"`. What is correct?
2014/03/28
[ "https://Stackoverflow.com/questions/22714820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674548/" ]
Your evaluation of the different `scaleType`'s is correct. If you want the whole image to be visible, use `"centerInside"`, or if you want to fill the whole view then use `centerCrop`. To use a mix of both, you can set the `scaleType` in your `onCreate()` method. Based on the behavior you want to have, you can check the orientation or size of the screen and set the appropriate choice. `imageView.setScaleType(ScaleType.CENTER_INSIDE); // or ScaleType.CENTER_CROP`
You can have two layouts, one for each of your configurations. You can then load the proper one at the activity's onCreate() call.
22,714,820
I have an image to be used a background in activity: ![enter image description here](https://i.stack.imgur.com/MfXu0.png) I want this image to fit screen by its height. It means that for wide-screen smartphones, I want my image to be fit by height and centered: ![enter image description here](https://i.stack.imgur.com/G8aXH.png) and for square-screen smartphones, I want my image to be cut: ![enter image description here](https://i.stack.imgur.com/84K02.png) I use `ImageView` for the image. What `scaleType` should I use? Looking at the second figure, I'd say to use `android:scaleType="centerInside"`. But looking at the third, I'd say to use `android:scaleType="centerCrop"`. What is correct?
2014/03/28
[ "https://Stackoverflow.com/questions/22714820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674548/" ]
Your evaluation of the different `scaleType`'s is correct. If you want the whole image to be visible, use `"centerInside"`, or if you want to fill the whole view then use `centerCrop`. To use a mix of both, you can set the `scaleType` in your `onCreate()` method. Based on the behavior you want to have, you can check the orientation or size of the screen and set the appropriate choice. `imageView.setScaleType(ScaleType.CENTER_INSIDE); // or ScaleType.CENTER_CROP`
Use `centerCrop` because `centerInside` doesn't scale an image in a view and you have to create the image with appropriate height to achieve wide-screened smartphones background filling. Or alternative you could use `fitCenter` to get uniformly scaled image by both axes which fills the all background.
22,714,820
I have an image to be used a background in activity: ![enter image description here](https://i.stack.imgur.com/MfXu0.png) I want this image to fit screen by its height. It means that for wide-screen smartphones, I want my image to be fit by height and centered: ![enter image description here](https://i.stack.imgur.com/G8aXH.png) and for square-screen smartphones, I want my image to be cut: ![enter image description here](https://i.stack.imgur.com/84K02.png) I use `ImageView` for the image. What `scaleType` should I use? Looking at the second figure, I'd say to use `android:scaleType="centerInside"`. But looking at the third, I'd say to use `android:scaleType="centerCrop"`. What is correct?
2014/03/28
[ "https://Stackoverflow.com/questions/22714820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674548/" ]
Your evaluation of the different `scaleType`'s is correct. If you want the whole image to be visible, use `"centerInside"`, or if you want to fill the whole view then use `centerCrop`. To use a mix of both, you can set the `scaleType` in your `onCreate()` method. Based on the behavior you want to have, you can check the orientation or size of the screen and set the appropriate choice. `imageView.setScaleType(ScaleType.CENTER_INSIDE); // or ScaleType.CENTER_CROP`
When you fit one side of image to background, you will face with two problems, first one is screen width is bigger than image's width or screen height is bigger than image height.So you will have empty space. If you do not want to face with resolution problem and you want to fit both side of image to background, you need to use `centerCROP`.But as i said, if one side of image is not enough to fit background, image gets bigger till it will be filled.
22,714,820
I have an image to be used a background in activity: ![enter image description here](https://i.stack.imgur.com/MfXu0.png) I want this image to fit screen by its height. It means that for wide-screen smartphones, I want my image to be fit by height and centered: ![enter image description here](https://i.stack.imgur.com/G8aXH.png) and for square-screen smartphones, I want my image to be cut: ![enter image description here](https://i.stack.imgur.com/84K02.png) I use `ImageView` for the image. What `scaleType` should I use? Looking at the second figure, I'd say to use `android:scaleType="centerInside"`. But looking at the third, I'd say to use `android:scaleType="centerCrop"`. What is correct?
2014/03/28
[ "https://Stackoverflow.com/questions/22714820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674548/" ]
You can have two layouts, one for each of your configurations. You can then load the proper one at the activity's onCreate() call.
Use `centerCrop` because `centerInside` doesn't scale an image in a view and you have to create the image with appropriate height to achieve wide-screened smartphones background filling. Or alternative you could use `fitCenter` to get uniformly scaled image by both axes which fills the all background.
22,714,820
I have an image to be used a background in activity: ![enter image description here](https://i.stack.imgur.com/MfXu0.png) I want this image to fit screen by its height. It means that for wide-screen smartphones, I want my image to be fit by height and centered: ![enter image description here](https://i.stack.imgur.com/G8aXH.png) and for square-screen smartphones, I want my image to be cut: ![enter image description here](https://i.stack.imgur.com/84K02.png) I use `ImageView` for the image. What `scaleType` should I use? Looking at the second figure, I'd say to use `android:scaleType="centerInside"`. But looking at the third, I'd say to use `android:scaleType="centerCrop"`. What is correct?
2014/03/28
[ "https://Stackoverflow.com/questions/22714820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/674548/" ]
When you fit one side of image to background, you will face with two problems, first one is screen width is bigger than image's width or screen height is bigger than image height.So you will have empty space. If you do not want to face with resolution problem and you want to fit both side of image to background, you need to use `centerCROP`.But as i said, if one side of image is not enough to fit background, image gets bigger till it will be filled.
Use `centerCrop` because `centerInside` doesn't scale an image in a view and you have to create the image with appropriate height to achieve wide-screened smartphones background filling. Or alternative you could use `fitCenter` to get uniformly scaled image by both axes which fills the all background.
50,050,858
So I have a recursive solution to the make change problem that works sometimes. It is: ``` def change(n, c): if (n == 0): return 1 if (n < 0): return 0; if (c + 1 <= 0 and n >= 1): return 0 return change(n, c - 1) + change(n - coins[c - 1], c); ``` where coins is my array of coins. For example [1,5,10,25]. n is the amount of coins, for example 1000, and c is the length of the coins array - 1. This solution works in some situations. But when I need it to run in under two seconds and I use: ``` coins: [1,5,10,25] n: 1000 ``` I get a: ``` RecursionError: maximum recursion depth exceeded in comparison ``` So my question is, what would be the best way to optimize this. Using some sort of flow control? I don't want to do something like. ``` # Set recursion limit sys.setrecursionlimit(10000000000) ``` UPDATE: I now have something like ``` def coinss(n, c): if n == 0: return 1 if n < 0: return 0 nCombos = 0 for c in range(c, -1, -1): nCombos += coinss(n - coins[c - 1], c) return nCombos ``` but it takes forever. it'd be ideal to have this run under a second.
2018/04/26
[ "https://Stackoverflow.com/questions/50050858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5906043/" ]
As suggested in the answers above you could use DP for a more optimal solution. Also your conditional check - `if (c + 1 <= 0 and n >= 1)` should be `if (c <= 1 ):` as n will always be >=1 and c <= 1 will prevent any calculations if the number of coins is lesser than or equal to 1.
While using recursion you will always run into this. If you set the recursion limit higher, you may be able to use your algorithm on a bigger number, but you will always be limited. The recursion limit is there to keep you from getting a stack overflow. The best way to solved for bigger change amounts would be to swap to an iterative approach. There are algorithms out there, wikipedia: <https://en.wikipedia.org/wiki/Change-making_problem>
50,050,858
So I have a recursive solution to the make change problem that works sometimes. It is: ``` def change(n, c): if (n == 0): return 1 if (n < 0): return 0; if (c + 1 <= 0 and n >= 1): return 0 return change(n, c - 1) + change(n - coins[c - 1], c); ``` where coins is my array of coins. For example [1,5,10,25]. n is the amount of coins, for example 1000, and c is the length of the coins array - 1. This solution works in some situations. But when I need it to run in under two seconds and I use: ``` coins: [1,5,10,25] n: 1000 ``` I get a: ``` RecursionError: maximum recursion depth exceeded in comparison ``` So my question is, what would be the best way to optimize this. Using some sort of flow control? I don't want to do something like. ``` # Set recursion limit sys.setrecursionlimit(10000000000) ``` UPDATE: I now have something like ``` def coinss(n, c): if n == 0: return 1 if n < 0: return 0 nCombos = 0 for c in range(c, -1, -1): nCombos += coinss(n - coins[c - 1], c) return nCombos ``` but it takes forever. it'd be ideal to have this run under a second.
2018/04/26
[ "https://Stackoverflow.com/questions/50050858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5906043/" ]
As suggested in the answers above you could use DP for a more optimal solution. Also your conditional check - `if (c + 1 <= 0 and n >= 1)` should be `if (c <= 1 ):` as n will always be >=1 and c <= 1 will prevent any calculations if the number of coins is lesser than or equal to 1.
Note that you have a bug here: ``` if (c + 1 <= 0 and n >= 1): ``` is like ``` if (c <= -1 and n >= 1): ``` So `c` can be 0 and pass to the next step where you pass `c-1` to the index, which works because python doesn't mind negative indexes but still false (`coins[-1]` yields `25`), so your solution sometimes prints 1 combination too much. I've rewritten your algorithm with recursive and stack approaches: Recursive (fixed, no need for `c` at init thanks to an internal recursive method, but still overflows the stack): ``` coins = [1,5,10,25] def change(n): def change_recurse(n, c): if n == 0: return 1 if n < 0: return 0; if c <= 0: return 0 return change_recurse(n, c - 1) + change_recurse(n - coins[c - 1], c) return change_recurse(n,len(coins)) ``` iterative/stack approach (not dynamic programming), doesn't recurse, just uses a "stack" to store the computations to perform: ``` def change2(n): def change_iter(stack): result = 0 # continue while the stack isn't empty while stack: # process one computation n,c = stack.pop() if n == 0: # one solution found, increase counter result += 1 if n > 0 and c > 0: # not found, request 2 more computations stack.append((n, c - 1)) stack.append((n - coins[c - 1], c)) return result return change_iter([(n,len(coins))]) ``` Both methods return the same values for low values of `n`. ``` for i in range(1,200): a,b = change(i),change2(i) if a != b: print("error",i,a,b) ``` the code above runs without any error prints. Now `print(change2(1000))` takes a few seconds but prints `142511` without blowing the stack.
60,749,076
After Applying a rotation or a translation matrix on the vertex array, the vertex buffer is not updated So how can i get the position of vertices after applying the matrix? here's the `onDrawFrame()` function ``` public void onDrawFrame(GL10 gl) { PositionHandle = GLES20.glGetAttribLocation(Program,"vPosition"); MatrixHandle = GLES20.glGetUniformLocation(Program,"uMVPMatrix"); ColorHandle = GLES20.glGetUniformLocation(Program,"vColor"); GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT|GLES20.GL_DEPTH_BUFFER_BIT ); Matrix.rotateM(RotationMatrix,0,-90f,1,0,0); Matrix.multiplyMM(vPMatrix,0,projectionMatrix,0,viewMatrix,0); Matrix.multiplyMM(vPMatrix,0,vPMatrix,0,RotationMatrix,0); GLES20.glUniformMatrix4fv(MatrixHandle, 1, false, vPMatrix, 0); GLES20.glUseProgram(Program); GLES20.glEnableVertexAttribArray(PositionHandle); GLES20.glVertexAttribPointer(PositionHandle,3,GLES20.GL_FLOAT,false,0,vertexbuffer); GLES20.glUniform4fv(ColorHandle,1,color,1); GLES20.glDrawArrays(GLES20.GL_TRIANGLES,0,6); GLES20.glDisableVertexAttribArray(PositionHandle); } ```
2020/03/18
[ "https://Stackoverflow.com/questions/60749076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13085596/" ]
The GPU doesn't normally write back transformed results anywhere the application can use them. It's possible in ES 3.0 with transform feedback, BUT it's very expensive. For touch event "hit" testing, you generally don't want to use the raw geometry. Generally use some simple proxy geometry, which can be transformed in software on the CPU.
Maybe you should try this: ``` private float[] modelViewMatrix = new float[16]; ... Matrix.rotateM(RotationMatrix, 0, -90f, 1, 0, 0); Matrix.multiplyMM(modelViewMatrix, 0, viewMatrix, 0, RotationMatrix, 0); Matrix.multiplyMM(vpMatrix, 0, projectionMatrix, 0, modelViewMatrix, 0); ``` You can use the vertex movement calculations in the CPU, and then use the GLU.gluProject() function to convert the coordinates of the vertex of the object in pixels of the screen. This data can be used when working with touch events. ``` private var view: IntArray = intArrayOf(0, 0, widthScreen, heightScreen) ... GLU.gluProject(modelX, modelY, modelZ, mvMatrix, 0, projectionMatrix, 0, view, 0, coordinatesWindow, 0) ... // coordinates in pixels of the screen val x = coordinatesWindow[0] val y = coordinatesWindow[1] ```
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
In order to help you migrate from beta4 to beta5, these are the following steps it took me, based on the research/findings. Environment =========== * PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` * PowerShell run: `dnvm install 1.0.0-beta5` * PowerShell run: `dnvm use 1.0.0-beta5 -p` (*not sure if its needed however i had to*) Project ======= * Open global.json and update sdk to 1.0.0-beta5 should look like this: ``` { "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-beta5" } } ``` * Open project.json: + Updated dependencies versions from beta4 to beta5 + Change **Configuration** dependency from: ``` "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4" ``` to ``` "Microsoft.Framework.Configuration": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5" ``` + Remove `Microsoft.VisualStudio.Web.BrowserLink.Loader` + Rename `_GlobalImport.cshtml` to `_ViewImports.cshtml` Startup.cs changes ------------------ * Change Configuration breaking changes + Change namespace from `using Microsoft.Framework.ConfigurationModel;` to `using Microsoft.Framework.Configuration;` + Change `Configuration.GetSubKey` to `Configuration.GetConfigurationSection` + Change CTOR to: ``` public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var configBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = configBuilder.Build(); } ``` + Remove `app.UseBrowserLink();` Project DNU CMDs ================ * Open PowerShell within **app root** * Run `dnu restore` * Run `dnu build` * Closing and reopening VS at this point helps sometimes. Myself found it quite difficult to upgrade an existing project, couldn't find all steps required all together. Hope it helps!
In case anyone is wondering how to update to ASP.NET 5 Beta 7, I found it useful to download the latest ASP.NET and Web Tools updates for Visual Studio 2015 and then create a new ASP.NET 5 project in Visual Studio. This will create a Beta 7 project with the project structure, code and referenced dependencies for you. You can then use this as a guide to upgrade any existing older Beta projects. For example here what my project.json looks like using all the Beta 7 dependencies: ``` { "webroot": "wwwroot", "userSecretsId": "aspnet5-WebApplication1-a433a0ef-3bed-4bc9-8086-8d18070fa2c1", "version": "1.0.0-*", "dependencies": { "EntityFramework.Commands": "7.0.0-beta7", "EntityFramework.SqlServer": "7.0.0-beta7", "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Google": "1.0.0-beta7", "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta7", "Microsoft.AspNet.Diagnostics": "1.0.0-beta7", "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta7", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta7", "Microsoft.AspNet.Mvc": "6.0.0-beta7", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7", "Microsoft.AspNet.Server.IIS": "1.0.0-beta7", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta7", "Microsoft.AspNet.StaticFiles": "1.0.0-beta7", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta7", "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7", "Microsoft.Framework.Configuration.Json": "1.0.0-beta7", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta7", "Microsoft.Framework.Logging": "1.0.0-beta7", "Microsoft.Framework.Logging.Console": "1.0.0-beta7", "Microsoft.Framework.Logging.Debug" : "1.0.0-beta7", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta7" }, "commands": { "web": "Microsoft.AspNet.Hosting --config hosting.ini", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules", "bower_components" ], "publishExclude": [ "node_modules", "bower_components", "**.xproj", "**.user", "**.vspscc" ], "scripts": { "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ] } } ``` At the time of writing, this is where you can download [the beta 7 updates for Visual Studio](http://go.microsoft.com/fwlink/?LinkId=623894). Ensure you get the file WebToolsExtensionsVS14.msi. Find more information about this Beta 7 release see the blog post [Announcing Availability of ASP.NET 5 Beta7](http://blogs.msdn.com/b/webdev/archive/2015/09/02/announcing-availability-of-asp-net-5-beta7.aspx)
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
In order to help you migrate from beta4 to beta5, these are the following steps it took me, based on the research/findings. Environment =========== * PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` * PowerShell run: `dnvm install 1.0.0-beta5` * PowerShell run: `dnvm use 1.0.0-beta5 -p` (*not sure if its needed however i had to*) Project ======= * Open global.json and update sdk to 1.0.0-beta5 should look like this: ``` { "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-beta5" } } ``` * Open project.json: + Updated dependencies versions from beta4 to beta5 + Change **Configuration** dependency from: ``` "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4" ``` to ``` "Microsoft.Framework.Configuration": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5" ``` + Remove `Microsoft.VisualStudio.Web.BrowserLink.Loader` + Rename `_GlobalImport.cshtml` to `_ViewImports.cshtml` Startup.cs changes ------------------ * Change Configuration breaking changes + Change namespace from `using Microsoft.Framework.ConfigurationModel;` to `using Microsoft.Framework.Configuration;` + Change `Configuration.GetSubKey` to `Configuration.GetConfigurationSection` + Change CTOR to: ``` public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var configBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = configBuilder.Build(); } ``` + Remove `app.UseBrowserLink();` Project DNU CMDs ================ * Open PowerShell within **app root** * Run `dnu restore` * Run `dnu build` * Closing and reopening VS at this point helps sometimes. Myself found it quite difficult to upgrade an existing project, couldn't find all steps required all together. Hope it helps!
After speaking with @davidfowl from the ASP.NET vNext team, he told me that Browser Link doesn't work in beta5 and should be removed.
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
After speaking with @davidfowl from the ASP.NET vNext team, he told me that Browser Link doesn't work in beta5 and should be removed.
[Microsoft.AspNet.Http and Microsoft.AspNet.Http.Core package names swapped](https://github.com/aspnet/Announcements/issues/7)
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
To complete, if you want to update from beta 4 to beta 6, see the Stephen Lautier's answer and to this after : **To update from beta 5 to beta 6 :** I did : * Open global.json and update sdk to "1.0.0-beta6" and save this file * Visual Studio 2015 proposes to download beta6, click on Yes In project.json : * change dnx451 (or dnx452) to dnx46 (To use Framework 4.6) * replace all "-beta5" with "-beta6" in this file * remove Microsoft.Framework.ConfigurationModel.UserSecrets In Startup.cs, if you use Session : * replace app.UseInMemorySession(...) with app.UseSession() * In ConfigureServices, add this : ``` services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); ``` * Right click on your Project > Properties > Debug > Add a new Environment Variable : > > **Name :** DNX\_IIS\_RUNTIME\_FRAMEWORK > > > **Value :** dnx46 > > > See that for more information : <http://jameschambers.com/2015/07/launching-an-asp-net-5-application-from-visual-studio-2015/> * In Package Manager Console, write this "dnu restore" and this "dnu build" * Restart Visual Studio My project work in beta6 after that, maybe there are other things to do.
After speaking with @davidfowl from the ASP.NET vNext team, he told me that Browser Link doesn't work in beta5 and should be removed.
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
To complete, if you want to update from beta 4 to beta 6, see the Stephen Lautier's answer and to this after : **To update from beta 5 to beta 6 :** I did : * Open global.json and update sdk to "1.0.0-beta6" and save this file * Visual Studio 2015 proposes to download beta6, click on Yes In project.json : * change dnx451 (or dnx452) to dnx46 (To use Framework 4.6) * replace all "-beta5" with "-beta6" in this file * remove Microsoft.Framework.ConfigurationModel.UserSecrets In Startup.cs, if you use Session : * replace app.UseInMemorySession(...) with app.UseSession() * In ConfigureServices, add this : ``` services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); ``` * Right click on your Project > Properties > Debug > Add a new Environment Variable : > > **Name :** DNX\_IIS\_RUNTIME\_FRAMEWORK > > > **Value :** dnx46 > > > See that for more information : <http://jameschambers.com/2015/07/launching-an-asp-net-5-application-from-visual-studio-2015/> * In Package Manager Console, write this "dnu restore" and this "dnu build" * Restart Visual Studio My project work in beta6 after that, maybe there are other things to do.
This is the thing: You updated the DNX from beta4 to beta5, and you want to run an MVC6 template inside Visual Studio RC (whose templates were built around beta4). In the first place, `"Microsoft.Framework.Configuration.Json"` doesn't exist in beta5 anymore. (you should definitely see this: <https://github.com/aspnet/announcements/issues?q=milestone%3A1.0.0-beta5> - breaking changes from beta4 to beta5). In order to see that your DNX was updated properly, build a new empty web project and simply add MVC/WebAPI (simple cases to check that it works). I haven't tried to run the MVC template yet, but I will try and come back to you.
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
In order to help you migrate from beta4 to beta5, these are the following steps it took me, based on the research/findings. Environment =========== * PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` * PowerShell run: `dnvm install 1.0.0-beta5` * PowerShell run: `dnvm use 1.0.0-beta5 -p` (*not sure if its needed however i had to*) Project ======= * Open global.json and update sdk to 1.0.0-beta5 should look like this: ``` { "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-beta5" } } ``` * Open project.json: + Updated dependencies versions from beta4 to beta5 + Change **Configuration** dependency from: ``` "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4" ``` to ``` "Microsoft.Framework.Configuration": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5" ``` + Remove `Microsoft.VisualStudio.Web.BrowserLink.Loader` + Rename `_GlobalImport.cshtml` to `_ViewImports.cshtml` Startup.cs changes ------------------ * Change Configuration breaking changes + Change namespace from `using Microsoft.Framework.ConfigurationModel;` to `using Microsoft.Framework.Configuration;` + Change `Configuration.GetSubKey` to `Configuration.GetConfigurationSection` + Change CTOR to: ``` public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var configBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = configBuilder.Build(); } ``` + Remove `app.UseBrowserLink();` Project DNU CMDs ================ * Open PowerShell within **app root** * Run `dnu restore` * Run `dnu build` * Closing and reopening VS at this point helps sometimes. Myself found it quite difficult to upgrade an existing project, couldn't find all steps required all together. Hope it helps!
To complete, if you want to update from beta 4 to beta 6, see the Stephen Lautier's answer and to this after : **To update from beta 5 to beta 6 :** I did : * Open global.json and update sdk to "1.0.0-beta6" and save this file * Visual Studio 2015 proposes to download beta6, click on Yes In project.json : * change dnx451 (or dnx452) to dnx46 (To use Framework 4.6) * replace all "-beta5" with "-beta6" in this file * remove Microsoft.Framework.ConfigurationModel.UserSecrets In Startup.cs, if you use Session : * replace app.UseInMemorySession(...) with app.UseSession() * In ConfigureServices, add this : ``` services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); ``` * Right click on your Project > Properties > Debug > Add a new Environment Variable : > > **Name :** DNX\_IIS\_RUNTIME\_FRAMEWORK > > > **Value :** dnx46 > > > See that for more information : <http://jameschambers.com/2015/07/launching-an-asp-net-5-application-from-visual-studio-2015/> * In Package Manager Console, write this "dnu restore" and this "dnu build" * Restart Visual Studio My project work in beta6 after that, maybe there are other things to do.
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
To complete, if you want to update from beta 4 to beta 6, see the Stephen Lautier's answer and to this after : **To update from beta 5 to beta 6 :** I did : * Open global.json and update sdk to "1.0.0-beta6" and save this file * Visual Studio 2015 proposes to download beta6, click on Yes In project.json : * change dnx451 (or dnx452) to dnx46 (To use Framework 4.6) * replace all "-beta5" with "-beta6" in this file * remove Microsoft.Framework.ConfigurationModel.UserSecrets In Startup.cs, if you use Session : * replace app.UseInMemorySession(...) with app.UseSession() * In ConfigureServices, add this : ``` services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); ``` * Right click on your Project > Properties > Debug > Add a new Environment Variable : > > **Name :** DNX\_IIS\_RUNTIME\_FRAMEWORK > > > **Value :** dnx46 > > > See that for more information : <http://jameschambers.com/2015/07/launching-an-asp-net-5-application-from-visual-studio-2015/> * In Package Manager Console, write this "dnu restore" and this "dnu build" * Restart Visual Studio My project work in beta6 after that, maybe there are other things to do.
[Microsoft.AspNet.Http and Microsoft.AspNet.Http.Core package names swapped](https://github.com/aspnet/Announcements/issues/7)
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
In order to help you migrate from beta4 to beta5, these are the following steps it took me, based on the research/findings. Environment =========== * PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` * PowerShell run: `dnvm install 1.0.0-beta5` * PowerShell run: `dnvm use 1.0.0-beta5 -p` (*not sure if its needed however i had to*) Project ======= * Open global.json and update sdk to 1.0.0-beta5 should look like this: ``` { "projects": [ "src", "test" ], "sdk": { "version": "1.0.0-beta5" } } ``` * Open project.json: + Updated dependencies versions from beta4 to beta5 + Change **Configuration** dependency from: ``` "Microsoft.Framework.ConfigurationModel.Json": "1.0.0-beta4" ``` to ``` "Microsoft.Framework.Configuration": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5" ``` + Remove `Microsoft.VisualStudio.Web.BrowserLink.Loader` + Rename `_GlobalImport.cshtml` to `_ViewImports.cshtml` Startup.cs changes ------------------ * Change Configuration breaking changes + Change namespace from `using Microsoft.Framework.ConfigurationModel;` to `using Microsoft.Framework.Configuration;` + Change `Configuration.GetSubKey` to `Configuration.GetConfigurationSection` + Change CTOR to: ``` public Startup(IHostingEnvironment env, IApplicationEnvironment appEnv) { // Setup configuration sources. var configBuilder = new ConfigurationBuilder(appEnv.ApplicationBasePath) .AddJsonFile("config.json") .AddEnvironmentVariables(); Configuration = configBuilder.Build(); } ``` + Remove `app.UseBrowserLink();` Project DNU CMDs ================ * Open PowerShell within **app root** * Run `dnu restore` * Run `dnu build` * Closing and reopening VS at this point helps sometimes. Myself found it quite difficult to upgrade an existing project, couldn't find all steps required all together. Hope it helps!
This is the thing: You updated the DNX from beta4 to beta5, and you want to run an MVC6 template inside Visual Studio RC (whose templates were built around beta4). In the first place, `"Microsoft.Framework.Configuration.Json"` doesn't exist in beta5 anymore. (you should definitely see this: <https://github.com/aspnet/announcements/issues?q=milestone%3A1.0.0-beta5> - breaking changes from beta4 to beta5). In order to see that your DNX was updated properly, build a new empty web project and simply add MVC/WebAPI (simple cases to check that it works). I haven't tried to run the MVC template yet, but I will try and come back to you.
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
To complete, if you want to update from beta 4 to beta 6, see the Stephen Lautier's answer and to this after : **To update from beta 5 to beta 6 :** I did : * Open global.json and update sdk to "1.0.0-beta6" and save this file * Visual Studio 2015 proposes to download beta6, click on Yes In project.json : * change dnx451 (or dnx452) to dnx46 (To use Framework 4.6) * replace all "-beta5" with "-beta6" in this file * remove Microsoft.Framework.ConfigurationModel.UserSecrets In Startup.cs, if you use Session : * replace app.UseInMemorySession(...) with app.UseSession() * In ConfigureServices, add this : ``` services.AddCaching(); services.AddSession(); services.ConfigureSession(o => { o.IdleTimeout = TimeSpan.FromSeconds(10); }); ``` * Right click on your Project > Properties > Debug > Add a new Environment Variable : > > **Name :** DNX\_IIS\_RUNTIME\_FRAMEWORK > > > **Value :** dnx46 > > > See that for more information : <http://jameschambers.com/2015/07/launching-an-asp-net-5-application-from-visual-studio-2015/> * In Package Manager Console, write this "dnu restore" and this "dnu build" * Restart Visual Studio My project work in beta6 after that, maybe there are other things to do.
In case anyone is wondering how to update to ASP.NET 5 Beta 7, I found it useful to download the latest ASP.NET and Web Tools updates for Visual Studio 2015 and then create a new ASP.NET 5 project in Visual Studio. This will create a Beta 7 project with the project structure, code and referenced dependencies for you. You can then use this as a guide to upgrade any existing older Beta projects. For example here what my project.json looks like using all the Beta 7 dependencies: ``` { "webroot": "wwwroot", "userSecretsId": "aspnet5-WebApplication1-a433a0ef-3bed-4bc9-8086-8d18070fa2c1", "version": "1.0.0-*", "dependencies": { "EntityFramework.Commands": "7.0.0-beta7", "EntityFramework.SqlServer": "7.0.0-beta7", "Microsoft.AspNet.Authentication.Cookies": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Facebook": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Google": "1.0.0-beta7", "Microsoft.AspNet.Authentication.MicrosoftAccount": "1.0.0-beta7", "Microsoft.AspNet.Authentication.Twitter": "1.0.0-beta7", "Microsoft.AspNet.Diagnostics": "1.0.0-beta7", "Microsoft.AspNet.Diagnostics.Entity": "7.0.0-beta7", "Microsoft.AspNet.Identity.EntityFramework": "3.0.0-beta7", "Microsoft.AspNet.Mvc": "6.0.0-beta7", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta7", "Microsoft.AspNet.Server.IIS": "1.0.0-beta7", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta7", "Microsoft.AspNet.StaticFiles": "1.0.0-beta7", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta7", "Microsoft.Framework.Configuration.Abstractions": "1.0.0-beta7", "Microsoft.Framework.Configuration.Json": "1.0.0-beta7", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta7", "Microsoft.Framework.Logging": "1.0.0-beta7", "Microsoft.Framework.Logging.Console": "1.0.0-beta7", "Microsoft.Framework.Logging.Debug" : "1.0.0-beta7", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta7" }, "commands": { "web": "Microsoft.AspNet.Hosting --config hosting.ini", "ef": "EntityFramework.Commands" }, "frameworks": { "dnx451": { }, "dnxcore50": { } }, "exclude": [ "wwwroot", "node_modules", "bower_components" ], "publishExclude": [ "node_modules", "bower_components", "**.xproj", "**.user", "**.vspscc" ], "scripts": { "prepublish": [ "npm install", "bower install", "gulp clean", "gulp min" ] } } ``` At the time of writing, this is where you can download [the beta 7 updates for Visual Studio](http://go.microsoft.com/fwlink/?LinkId=623894). Ensure you get the file WebToolsExtensionsVS14.msi. Find more information about this Beta 7 release see the blog post [Announcing Availability of ASP.NET 5 Beta7](http://blogs.msdn.com/b/webdev/archive/2015/09/02/announcing-availability-of-asp-net-5-beta7.aspx)
31,218,651
I have followed the steps [here](http://blogs.msdn.com/b/webdev/archive/2015/06/30/asp-net-5-beta5-now-available.aspx) to upgrade from ASP.NET 5 Beta 4 to Beta 5 but am getting an error at runtime when calling `application.UseBrowserLink();`: > > An exception of type 'System.TypeLoadException' occurred in > mscorlib.dll but was not handled in user code > > > Additional information: Could not load type > 'Microsoft.AspNet.Builder.IApplicationBuilder' from assembly > 'Microsoft.AspNet.Http, Version=1.0.0.0, Culture=neutral, > PublicKeyToken=null'. > > > These are the steps I followed: 1. Had VS 2015 RC already installed. 2. From PowerShell run: `$env:DNX_FEED="https://www.nuget.org/api/v2"` 3. From PowerShell run: `dnvm upgrade` 4. Added a Global.json file (I did not already have one). When I added it, it referred to Beta 5 already: ``` { "projects": [ "Source", "Tests" ], "sdk": { "version": "1.0.0-beta5-12103" } } ``` 5. Updated all packages in project.json to Beta 5. You can see a full version of my project.lock.json file [here](https://github.com/aspnet/Home/issues/719). ``` { "dependencies": { "Boilerplate.Web.Mvc6": "1.0.2", "Microsoft.AspNet.Diagnostics": "1.0.0-beta5", "Microsoft.AspNet.Mvc": "6.0.0-beta5", "Microsoft.AspNet.Mvc.TagHelpers": "6.0.0-beta5", "Microsoft.AspNet.Mvc.Xml": "6.0.0-beta5", "Microsoft.AspNet.Server.IIS": "1.0.0-beta5", "Microsoft.AspNet.Server.WebListener": "1.0.0-beta5", "Microsoft.AspNet.StaticFiles": "1.0.0-beta5", "Microsoft.AspNet.Tooling.Razor": "1.0.0-beta5", "Microsoft.Framework.CodeGenerators.Mvc": "1.0.0-beta5", "Microsoft.Framework.Configuration.EnvironmentVariables": "1.0.0-beta5", "Microsoft.Framework.Configuration.Json": "1.0.0-beta5", "Microsoft.Framework.Configuration.UserSecrets": "1.0.0-beta5", "Microsoft.Framework.Logging": "1.0.0-beta5", "Microsoft.Framework.Logging.Console": "1.0.0-beta5", "Microsoft.VisualStudio.Web.BrowserLink.Loader": "14.0.0-beta5", "Newtonsoft.Json": "6.0.6", "System.Runtime": "4.0.20-beta-23019" } "frameworks": { "dnx451": { "frameworkAssemblies": { "System.Net.Http": "4.0.0.0", "System.ServiceModel": "4.0.0.0" } }, "dnxcore50": { "dependencies": { "System.Net.Http": "4.0.0-beta-23019" } } } } ``` 6. The instructions then go on to say you should run the following commands but I believe VS 2015 RC does this for you `dnu restore` then `dnu build`. **UPDATE** It seems to be a problem with browser link, commenting the line out allows the site to work. It may be broken? Need to hunt around the aspnet GitHub issues.
2015/07/04
[ "https://Stackoverflow.com/questions/31218651", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212017/" ]
After speaking with @davidfowl from the ASP.NET vNext team, he told me that Browser Link doesn't work in beta5 and should be removed.
This is the thing: You updated the DNX from beta4 to beta5, and you want to run an MVC6 template inside Visual Studio RC (whose templates were built around beta4). In the first place, `"Microsoft.Framework.Configuration.Json"` doesn't exist in beta5 anymore. (you should definitely see this: <https://github.com/aspnet/announcements/issues?q=milestone%3A1.0.0-beta5> - breaking changes from beta4 to beta5). In order to see that your DNX was updated properly, build a new empty web project and simply add MVC/WebAPI (simple cases to check that it works). I haven't tried to run the MVC template yet, but I will try and come back to you.
80,053
I'm trying to prove why the mean of the distribution of sums of the top 3 out of 4 fair 6 sided dice is rolls 12.25. Anybody who's rolled a D&D character knows the idea. $r\_n = Rand([1,6])$ $x = \frac{\sum\_{i=1}^4{r\_i} - min(r\_i)}{3}$ Pardon the notation, I wasn't sure how to properly define the problem. So, I came to derive 12.25 with a computer program that just does several million iterations and comes up with something that's approaching 12.25. I just don't know why or how to prove it. I thought of splitting the interval [1,6] into 4 equal subsets and add the midpoint of the top 3. But that didn't work. Can someone explain why it's 12.25 and how to prove it?
2011/11/08
[ "https://math.stackexchange.com/questions/80053", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19075/" ]
We use the same idea as Ross Millikan. In order to bring out the structure, there will be as little calculation as possible. Let the random variable $X$ denote the smallest roll, and let $Y$ denote the sum of the three larger rolls. Then $$E(X)+E(Y)=E(X+Y)=14.$$ We calculate $E(X)$. From this, $E(Y)$ is easily found. Let $q\_1$ be the probability that $X\ge 1$, let $q\_2$ be the probability that $X\ge 2$, and so on. Then $P(X=1)=q\_1-q\_2$, $P(X=2)=q\_2-q\_3$, and so on until $P(X=6)=q\_6$. Thus $$E(X)=1\cdot(q\_1-q\_2)+2\cdot(q\_2-q\_3)+3\cdot(q\_3-q\_4)+4\cdot (q\_4-q\_5)+5\cdot (q\_5-q\_6) +6q\_6.$$ This simplifies to $$q\_1+q\_2+q\_3+q\_4+q\_5+q\_6.$$ But $$q\_i=\frac{(7-i)^4}{6^4},\qquad\text{and therefore}\qquad E(X)=\frac{1^4+2^4+3^4+4^4+5^4+6^4}{6^4}.$$ **Comment:** Let $W$ be a random variable that only takes on integer values. For any positive integer $n$, let $q\_n=P(W\ge n)$. Then $$E(W)=\sum\_{n=1}^\infty q\_n,$$ provided the sum is defined.
One approach is to find the number of rolls with each number as the lowest. There is only one roll with $6$ the minimum. There are $2^4-1=15$ with $5$ the minimum. This continues to the fact that there are $6^4-5^4=1296-625$ rolls with $1$ the minimum. The total of all the dice is $1296\*4\*3.5=18144$ The thrown out dice are $6\*1+5\*15+4\*65+3\*175+2\*369+1\*671=2275$ so the total score after throwouts is $15869$, giving an average of about $12.2446$
80,053
I'm trying to prove why the mean of the distribution of sums of the top 3 out of 4 fair 6 sided dice is rolls 12.25. Anybody who's rolled a D&D character knows the idea. $r\_n = Rand([1,6])$ $x = \frac{\sum\_{i=1}^4{r\_i} - min(r\_i)}{3}$ Pardon the notation, I wasn't sure how to properly define the problem. So, I came to derive 12.25 with a computer program that just does several million iterations and comes up with something that's approaching 12.25. I just don't know why or how to prove it. I thought of splitting the interval [1,6] into 4 equal subsets and add the midpoint of the top 3. But that didn't work. Can someone explain why it's 12.25 and how to prove it?
2011/11/08
[ "https://math.stackexchange.com/questions/80053", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19075/" ]
One approach is to find the number of rolls with each number as the lowest. There is only one roll with $6$ the minimum. There are $2^4-1=15$ with $5$ the minimum. This continues to the fact that there are $6^4-5^4=1296-625$ rolls with $1$ the minimum. The total of all the dice is $1296\*4\*3.5=18144$ The thrown out dice are $6\*1+5\*15+4\*65+3\*175+2\*369+1\*671=2275$ so the total score after throwouts is $15869$, giving an average of about $12.2446$
There are $6^4$ rolls for which the minimum is at least $1$, $5^4$ rolls for which the minimum is at least $2$, and so on. Thus the sum over all the minima is $1^4+2^4+3^4+4^4+5^4+6^4=2275$. It's a bit of an overkill, but if you like you can also calculate this sum using the general formula for the sum of the first $n$ fourth powers: $$\sum\_{k=1}^6k^4=\left.\frac{n(n+1)(2n+1)(3n^2+3n-1)}{30}\right|\_{n=6}=\frac{6\cdot7\cdot13\cdot125}{30}=2275\;.$$ As Ross shows in his answer, this leads to an average of about $12.2446$.
80,053
I'm trying to prove why the mean of the distribution of sums of the top 3 out of 4 fair 6 sided dice is rolls 12.25. Anybody who's rolled a D&D character knows the idea. $r\_n = Rand([1,6])$ $x = \frac{\sum\_{i=1}^4{r\_i} - min(r\_i)}{3}$ Pardon the notation, I wasn't sure how to properly define the problem. So, I came to derive 12.25 with a computer program that just does several million iterations and comes up with something that's approaching 12.25. I just don't know why or how to prove it. I thought of splitting the interval [1,6] into 4 equal subsets and add the midpoint of the top 3. But that didn't work. Can someone explain why it's 12.25 and how to prove it?
2011/11/08
[ "https://math.stackexchange.com/questions/80053", "https://math.stackexchange.com", "https://math.stackexchange.com/users/19075/" ]
We use the same idea as Ross Millikan. In order to bring out the structure, there will be as little calculation as possible. Let the random variable $X$ denote the smallest roll, and let $Y$ denote the sum of the three larger rolls. Then $$E(X)+E(Y)=E(X+Y)=14.$$ We calculate $E(X)$. From this, $E(Y)$ is easily found. Let $q\_1$ be the probability that $X\ge 1$, let $q\_2$ be the probability that $X\ge 2$, and so on. Then $P(X=1)=q\_1-q\_2$, $P(X=2)=q\_2-q\_3$, and so on until $P(X=6)=q\_6$. Thus $$E(X)=1\cdot(q\_1-q\_2)+2\cdot(q\_2-q\_3)+3\cdot(q\_3-q\_4)+4\cdot (q\_4-q\_5)+5\cdot (q\_5-q\_6) +6q\_6.$$ This simplifies to $$q\_1+q\_2+q\_3+q\_4+q\_5+q\_6.$$ But $$q\_i=\frac{(7-i)^4}{6^4},\qquad\text{and therefore}\qquad E(X)=\frac{1^4+2^4+3^4+4^4+5^4+6^4}{6^4}.$$ **Comment:** Let $W$ be a random variable that only takes on integer values. For any positive integer $n$, let $q\_n=P(W\ge n)$. Then $$E(W)=\sum\_{n=1}^\infty q\_n,$$ provided the sum is defined.
There are $6^4$ rolls for which the minimum is at least $1$, $5^4$ rolls for which the minimum is at least $2$, and so on. Thus the sum over all the minima is $1^4+2^4+3^4+4^4+5^4+6^4=2275$. It's a bit of an overkill, but if you like you can also calculate this sum using the general formula for the sum of the first $n$ fourth powers: $$\sum\_{k=1}^6k^4=\left.\frac{n(n+1)(2n+1)(3n^2+3n-1)}{30}\right|\_{n=6}=\frac{6\cdot7\cdot13\cdot125}{30}=2275\;.$$ As Ross shows in his answer, this leads to an average of about $12.2446$.
14,503,449
I have a large delimited txt file with two columns and about 17 million lines. I have imported it to the database, mistakenly one column in table had shorter size than the text from the file. i.e. varchar (4000) instead of varchar (7000) about 48 thousands records with longer text has been cut into 40k chars. How would I replace these without re-importing the files again? I am thinking if I could be able to filter from txt file only lines with certain length, and remove them, and try to insert update the longer lines. But How do I select all lines with certain length in a text file? or which program can do that. I am using MySQL DB and emEditor for large files text editing. Thanks.
2013/01/24
[ "https://Stackoverflow.com/questions/14503449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147622/" ]
Depending a bit on how this is connected to other infrastructure, my guess would be that the easiest and safest way of handeling it is just to drop and reimport the table... If that for some reason not is an option, I would write a script that goes through the text file, and either just updates the large text field unconditionally or checks if it is of a length that makes an update neccesary (ie > 4000 chars) If there might have been any changes to the table since the data was imported, it is important to check what will be overwritten and that the record really is the one you want to update (depending on how the table is indexed) Hope this gave you some starting points. You have my sympathy, been there done it...
You could also build a query that returns every record where that column contains 4000 bytes. Which are possibly the ones that were cut when you imported the file. With that set of records in hand, you could try to find them on the file if you have a line reference on the database table ofc. If there is too many, a simple script could do the trick.
2,312,431
I need to submit my hundreds of products to hundreds of websites. For most websites I need to select a directory/category for each product. But it seems each website has a different definition of categories. For example, some list laptops under computers/hardware, some under computers/laptop, some under /electronics/computers, some under eletctronics/PCs. It is so hard to automatically select a category for each product. Could you kindly give me some suggestions? Thank you so much!
2010/02/22
[ "https://Stackoverflow.com/questions/2312431", "https://Stackoverflow.com", "https://Stackoverflow.com/users/234118/" ]
Yes, it's hard. No one agrees on the categories. The Unix "rm" command ("remove") is spelled "del" in Windows. Why? People don't agree on something that simple and obvious. What kind of magic do you want? Your task requires a *person* to *think*. A person must (1) understand your products and (2) understand the web site categories and then (3) choose the right category based on the understanding. Think and make a judgement. Since the web site categories are just words, your software may have to guess and assume at some of the meanings. What does "household" or "consumer" mean? Only in context can you guess at the meaning.
I would try to build a graph with synonyms and generalizations. For example `Notebook` and `Laptop` are synonym. `Computer` generalizes them. `PC` is a synonym for `Computer`. `Electronics` generalizes `Computer` (and its synonym `PC`) again. Now, for a given product, look at the deepest level of the available categories and look for the most specific synonyms for that product from your graph. If there is no match, move one level up because they may have more specific categories then you graph - they may for example divide notebooks by brands. When you reach the root of the categories without a match move on to the first generalization from your graph and again search from the deepest category level upwards. This solution has still issues because for example categories may be divided by brand on a very high level or on a very deep level and you choose one option when building the graph. It is quite possible to handle such cases, too, but it will become much trickier.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
However if you really are completely stuck and have no choice but to host it in your WebApp, You could look at creating a `System.Timers.Timer` instance in your Global.asax.cs file. Wire up a Elapsed event as you normally would, and give it some code that does something along the lines of ``` protected void myTimer_Elapsed(object sender, EventArgs e) { if(System.DateTime.Now Falls in Some Configured Time-Window) //Do Stuff } ``` But as someone pointed out, its not guaranteed as IIS might be resetting during that period, in which case you'll miss it.
It's really not desirable to do, but you can do what Razzie is suggesting. I have seen it done many times. Although ugly, sometimes ya just have to do the ugly hacks. Using this method though, you have to make sure you application is not unloaded. So you need some sort of keep alive. I would suggest setting up a web monitoring tool that will constantly pull a page (aspx) to keep the application alive. These guys are free <http://mon.itor.us/>
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
However if you really are completely stuck and have no choice but to host it in your WebApp, You could look at creating a `System.Timers.Timer` instance in your Global.asax.cs file. Wire up a Elapsed event as you normally would, and give it some code that does something along the lines of ``` protected void myTimer_Elapsed(object sender, EventArgs e) { if(System.DateTime.Now Falls in Some Configured Time-Window) //Do Stuff } ``` But as someone pointed out, its not guaranteed as IIS might be resetting during that period, in which case you'll miss it.
I don't belive you, because source code of Quartz.Net (1.0 and 1.0.1) doesn't compile under Visual Studio.Net 2005 and 2008. The only way to get Quartz.Net is to use whole Spring.Net package, which compiles fine under VS.Net 2005 and 2008 Unless you could share some tips, how to compile and use quartz.dll in asp.net project! (web page of Quartz.Net and readme.txt doesn't provide any information on source coude compilation) Every tip is welcomed!
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
How about this: [Simulate a Windows Service using ASP.NET to run scheduled jobs](http://www.codeproject.com/KB/aspnet/ASPNETService.aspx). At one point this technique was [used on Stack Overflow](https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet), although I don't think it is any more. To be honest it seems like a nasty, error-prone hack to me, but if you're unable to run anything on the server except your website then something like this is probably your only option.
I had the same problem as you and I ended up with a programming a service that utilize Quartz.NET: <http://quartznet.sourceforge.net/> and connect to the same database as the website.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
I had the same problem as you and I ended up with a programming a service that utilize Quartz.NET: <http://quartznet.sourceforge.net/> and connect to the same database as the website.
I don't belive you, because source code of Quartz.Net (1.0 and 1.0.1) doesn't compile under Visual Studio.Net 2005 and 2008. The only way to get Quartz.Net is to use whole Spring.Net package, which compiles fine under VS.Net 2005 and 2008 Unless you could share some tips, how to compile and use quartz.dll in asp.net project! (web page of Quartz.Net and readme.txt doesn't provide any information on source coude compilation) Every tip is welcomed!
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
If you really have no control over the server (meaning, you cannot use an sql job, a scheduled task, or install a windows server) then you could use a [System.Threading.Timer](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) that you initialize in your Global.asax (e.g, on application startup) that invokes a certain method in your application every x minutes. This method would then query your database and see what notifications need to be send. This is really not a desirable approach though, as the timer is not guaranteed to always invoke as far as I know, since, like Peter says, your web application is not guaranteed to be alive at all times. However, depending on your requirements, it can still be a 'good enough' approach if you have no other options.
> > I don't belive you, because source > code of Quartz.Net (1.0 and 1.0.1) > doesn't compile under Visual > Studio.Net 2005 and 2008. The only way > to get Quartz.Net is to use whole > Spring.Net package, which compiles > fine under VS.Net 2005 and 2008 > > > Unless you could share some tips, how > to compile and use quartz.dll in > asp.net project! (web page of > Quartz.Net and readme.txt doesn't > provide any information on source > coude compilation) Every tip is > welcomed! > > > I had trouble at first as well, but this is because the necessary AsemblyInfo.cs is contained in the parent folder. Also, you'll need to add the three DLLs that are included.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
How about this: [Simulate a Windows Service using ASP.NET to run scheduled jobs](http://www.codeproject.com/KB/aspnet/ASPNETService.aspx). At one point this technique was [used on Stack Overflow](https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet), although I don't think it is any more. To be honest it seems like a nasty, error-prone hack to me, but if you're unable to run anything on the server except your website then something like this is probably your only option.
With ASP.NET you are not guaranteed that your app is alive at all times, and thus web applications as a host process for a scheduling solution is not feasible IMO. A Windows service is what you need for this scenario. You have full control on starting and stopping the process as well as ways of monitoring the application. Are you able to host such a service on a different machine? Even if the web application is running on a hosted server doesn't mean you have to run the scheduler on the same server.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
I had the same problem as you and I ended up with a programming a service that utilize Quartz.NET: <http://quartznet.sourceforge.net/> and connect to the same database as the website.
However if you really are completely stuck and have no choice but to host it in your WebApp, You could look at creating a `System.Timers.Timer` instance in your Global.asax.cs file. Wire up a Elapsed event as you normally would, and give it some code that does something along the lines of ``` protected void myTimer_Elapsed(object sender, EventArgs e) { if(System.DateTime.Now Falls in Some Configured Time-Window) //Do Stuff } ``` But as someone pointed out, its not guaranteed as IIS might be resetting during that period, in which case you'll miss it.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
How about this: [Simulate a Windows Service using ASP.NET to run scheduled jobs](http://www.codeproject.com/KB/aspnet/ASPNETService.aspx). At one point this technique was [used on Stack Overflow](https://blog.stackoverflow.com/2008/07/easy-background-tasks-in-aspnet), although I don't think it is any more. To be honest it seems like a nasty, error-prone hack to me, but if you're unable to run anything on the server except your website then something like this is probably your only option.
You need to have a job done at the server, but you have no good way of triggering it from ASP.NET? How about creating a webpage that will start your job, and have a timer run elsewhere (ie. on another computer) that requests that page. (Just hitting the page to trigger you jobs)
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
However if you really are completely stuck and have no choice but to host it in your WebApp, You could look at creating a `System.Timers.Timer` instance in your Global.asax.cs file. Wire up a Elapsed event as you normally would, and give it some code that does something along the lines of ``` protected void myTimer_Elapsed(object sender, EventArgs e) { if(System.DateTime.Now Falls in Some Configured Time-Window) //Do Stuff } ``` But as someone pointed out, its not guaranteed as IIS might be resetting during that period, in which case you'll miss it.
> > I don't belive you, because source > code of Quartz.Net (1.0 and 1.0.1) > doesn't compile under Visual > Studio.Net 2005 and 2008. The only way > to get Quartz.Net is to use whole > Spring.Net package, which compiles > fine under VS.Net 2005 and 2008 > > > Unless you could share some tips, how > to compile and use quartz.dll in > asp.net project! (web page of > Quartz.Net and readme.txt doesn't > provide any information on source > coude compilation) Every tip is > welcomed! > > > I had trouble at first as well, but this is because the necessary AsemblyInfo.cs is contained in the parent folder. Also, you'll need to add the three DLLs that are included.
781,300
We have a website where we need a scheduler to receive notifications (e-mail) on specific time. eg. a person setting reminder at 5 PM to attend the meeting at 4:45 PM, will receive email at 4:45 PM about same. As this site is hosted on shared server, we don't have any control over the server to run any SQL Job or scheduler application. Is there anything in asp.net which can help in this scenario?
2009/04/23
[ "https://Stackoverflow.com/questions/781300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/51635/" ]
With ASP.NET you are not guaranteed that your app is alive at all times, and thus web applications as a host process for a scheduling solution is not feasible IMO. A Windows service is what you need for this scenario. You have full control on starting and stopping the process as well as ways of monitoring the application. Are you able to host such a service on a different machine? Even if the web application is running on a hosted server doesn't mean you have to run the scheduler on the same server.
However if you really are completely stuck and have no choice but to host it in your WebApp, You could look at creating a `System.Timers.Timer` instance in your Global.asax.cs file. Wire up a Elapsed event as you normally would, and give it some code that does something along the lines of ``` protected void myTimer_Elapsed(object sender, EventArgs e) { if(System.DateTime.Now Falls in Some Configured Time-Window) //Do Stuff } ``` But as someone pointed out, its not guaranteed as IIS might be resetting during that period, in which case you'll miss it.
65,865,353
I have a really basic and simple question but for some reason I can't figure it out. I have the following code in python: ``` counter = 0 for el in mylist: if self.check_el(el): counter += 1 ``` I want to make it in one line. Is it something that possible to achieve?
2021/01/23
[ "https://Stackoverflow.com/questions/65865353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
Yeah, here is one option: ``` counter = sum(1 for el in mylist if self.check_el(el)) ```
``` sum(map(lambda el: bool(self.check_el(el)), my_list)) ``` Or if you know `check_el` always returns a bool: ``` sum(map(self.check_el, my_list)) ```
65,865,353
I have a really basic and simple question but for some reason I can't figure it out. I have the following code in python: ``` counter = 0 for el in mylist: if self.check_el(el): counter += 1 ``` I want to make it in one line. Is it something that possible to achieve?
2021/01/23
[ "https://Stackoverflow.com/questions/65865353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
Yeah, here is one option: ``` counter = sum(1 for el in mylist if self.check_el(el)) ```
``` counter = sum(int(self.check_el(el)) for el in mylist) ```
65,865,353
I have a really basic and simple question but for some reason I can't figure it out. I have the following code in python: ``` counter = 0 for el in mylist: if self.check_el(el): counter += 1 ``` I want to make it in one line. Is it something that possible to achieve?
2021/01/23
[ "https://Stackoverflow.com/questions/65865353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
Yeah, here is one option: ``` counter = sum(1 for el in mylist if self.check_el(el)) ```
I suggest ```py len(list(filter(self.check_el, mylist))) ``` It filters out all elemenents not fulfilling self.check\_el, converts the filter object into a list, and then takes the length of said list. If you want to iterate over the elements, `filter(self.check_el, mylist)` is iterable.
65,865,353
I have a really basic and simple question but for some reason I can't figure it out. I have the following code in python: ``` counter = 0 for el in mylist: if self.check_el(el): counter += 1 ``` I want to make it in one line. Is it something that possible to achieve?
2021/01/23
[ "https://Stackoverflow.com/questions/65865353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
``` sum(map(lambda el: bool(self.check_el(el)), my_list)) ``` Or if you know `check_el` always returns a bool: ``` sum(map(self.check_el, my_list)) ```
I suggest ```py len(list(filter(self.check_el, mylist))) ``` It filters out all elemenents not fulfilling self.check\_el, converts the filter object into a list, and then takes the length of said list. If you want to iterate over the elements, `filter(self.check_el, mylist)` is iterable.
65,865,353
I have a really basic and simple question but for some reason I can't figure it out. I have the following code in python: ``` counter = 0 for el in mylist: if self.check_el(el): counter += 1 ``` I want to make it in one line. Is it something that possible to achieve?
2021/01/23
[ "https://Stackoverflow.com/questions/65865353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9808098/" ]
``` counter = sum(int(self.check_el(el)) for el in mylist) ```
I suggest ```py len(list(filter(self.check_el, mylist))) ``` It filters out all elemenents not fulfilling self.check\_el, converts the filter object into a list, and then takes the length of said list. If you want to iterate over the elements, `filter(self.check_el, mylist)` is iterable.
65,624,819
I would like to consume messages from one kafka cluster and publish to another kafka cluster. Would like to know how to configure this using spring-kafka?
2021/01/08
[ "https://Stackoverflow.com/questions/65624819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7073189/" ]
Simply configure the consumer and producer factories with different `bootstrap.servers` properties. If you are using Spring Boot, see <https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#spring.kafka.consumer.bootstrap-servers> and <https://docs.spring.io/spring-boot/docs/current/reference/html/appendix-application-properties.html#spring.kafka.producer.bootstrap-servers> If you are creating your own factory `@Bean`s, set the properties there. <https://docs.spring.io/spring-kafka/docs/current/reference/html/#connecting>
you can use spring cloud stream kafka binders. create two stream one for consume and one for producing. for consumer ``` public interface InputStreamExample{ String INPUT = "consumer-in"; @Input(INPUT) MessageChannel readFromKafka(); } ``` for producer ``` public interface ProducerStreamExample{ String OUTPUT = "produce-out"; @Output(OUTPUT) MessageChannel produceToKafka(); } ``` for consuming message use: ``` @StreamListener(value = ItemStream.INPUT) public void processMessage(){ /* code goes here */ } ``` for producing ``` //here producerStreamExample is instance of ProducerStreamExample producerStreamExample.produceToKafka().send(/*message goes here*/); ``` Now configure consumer and producer cluster using binder, you can use consumer-in for consumer cluster and produce-out for producing cluster. properties file ``` spring.cloud.stream.binders.kafka-a.environment.spring.cloud.stream.kafka.binder.brokers:<consumer cluster> #other properties for this binders #bind kafka-a to consumer-in spring.cloud.stream.bindings.consumer-in.binder=kafka-a #kafka-a binding to consumer-in #similary other properties of consumer-in, like spring.cloud.stream.bindings.consumer-in.destination=<topic> spring.cloud.stream.bindings.consumer-in.group=<consumer group> #now configure cluster to produce spring.cloud.stream.binders.kafka-b.environment.spring.cloud.stream.kafka.binder.brokers:<cluster where to produce> spring.cloud.stream.bindings.produce-out.binder=kafka-b #here kafka-b, binding to produce-out #similary you can do other configuration like topic spring.cloud.stream.bindings.produce-out.destination=<topic> ``` Refer to this for more configuration: <https://cloud.spring.io/spring-cloud-stream-binder-kafka/spring-cloud-stream-binder-kafka.html>
50,236,904
I am developing a native script app using angular, and I need to access the native Android API. I tried to use `android.view` as mentioned in the native script documentation, but I get an error saying that view is not defined : [Native Script documentation](https://docs.nativescript.org/runtimes/android/metadata/accessing-packages) Here below is the declaration used to access the android object. ``` import { android } from "application"; ``` Can you help me please to find out why am I getting this error ?
2018/05/08
[ "https://Stackoverflow.com/questions/50236904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3532113/" ]
You don't have to import anything to access the native APIs. So to use `android.view` you'd just call it in your app like this: `const x = new android.view.ViewGroup.... // or whatever you're accessing`
As per Brad Martin response, there is no need to make any import. To use it in angular environment, add this line before the component declaration. ``` declare var android :any; ```
50,236,904
I am developing a native script app using angular, and I need to access the native Android API. I tried to use `android.view` as mentioned in the native script documentation, but I get an error saying that view is not defined : [Native Script documentation](https://docs.nativescript.org/runtimes/android/metadata/accessing-packages) Here below is the declaration used to access the android object. ``` import { android } from "application"; ``` Can you help me please to find out why am I getting this error ?
2018/05/08
[ "https://Stackoverflow.com/questions/50236904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3532113/" ]
You don't have to import anything to access the native APIs. So to use `android.view` you'd just call it in your app like this: `const x = new android.view.ViewGroup.... // or whatever you're accessing`
In the answer ( which also answered my issue ) there are two things to note: * The native variable that you can use `android` * The one that you import from `import { android } from "@nativescript/core/application";` when I used as the answer suggested I run into an issue where it now couldn't find the `addEventListener` in code: `android.addEventListener` So eventually I wrote something like this to differentiate between these two variables ``` import { android as Android, <= aliased android => Android AndroidActivityEventData, AndroidApplication } from '@nativescript/core/application'; Android.addEventListener(AndroidApplication.activityCreatedEvent, (event: AndroidActivityEventData) => { event.activity.getWindow().getDecorView().setLayoutDirection(android.view .View.LAYOUT_DIRECTION_RTL); }); ```
62,879,446
I am pulling in dependencies from a parent and need most of the dependencies in there. But I also wish to be able to exclude 2 dependencies entirely. I am not able to edit the parent thus this needs to be excluded from my POM file. Is this even possible? I've seen examples for overrides and quite a bit of suggestion to fix the parent POM which as mentioned, I can't do at this time. Using Maven 3.3.x My POM file ``` <parent> <groupId>com.company.stuff</groupId> <artifactId>our-parent</artifactId> <version>1.7</version> </parent> <!-- other dependencies and build and plugins --> ``` The parent in above pulls in following plugins which I wish to exclude entirely. ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-pmd-plugin</artifactId> <version>${some.version}</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${some.version}</version> </plugin> ``` Is there a way around this? Please advice. Thanks. Tried with Thiago's suggestion, same outcome. ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>${checkstyle.version}</version> <executions> <execution> <id>maven-checkstyle-plugin</id> <phase>none</phase> </execution> </executions> </plugin> </plugins> </build> ```
2020/07/13
[ "https://Stackoverflow.com/questions/62879446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401029/" ]
You should study the syntax of your expected matches to extract them correctly. To get the port number value, I'd use ``` regex reg("--riotclient-app-port=(\\d+)"); ``` This way, you do not even need to care about the number of digits you match since it will capture a number after a known string. If the auth token can only contain letters, digits, `_` or `-` you may use ``` regex reg1("remoting-auth-token=([\\w-]+)") ``` where `\w` matches a letter/digit/`_` and `-` matches a hyphen, `+` will match one or more occurrences. See the [C++ demo](https://ideone.com/oFZq84).
First, you need to escape your str value. Every double-quotes (") character must be escaped with (\") ``` string str = "C:/Riot Games/League of Legends/LeagueClientUx.exe\" \"--riotclient-auth-token=yvjM3_sRqdaFoETdKSt1bQ\" \"--riotclient-app-port=53201\" \"--no-rads\" \"--disable-self-update\" \"--region=EUW\" \"--locale=en_GB\" \"--remoting-auth-token=13bHJUl7M_u_CtoR7v8XeA\" \"--respawn-command=LeagueClient.exe\" \"--respawn-display-name=League of Legends\" \"--app-port=53230\" \"--install-directory=C:\Riot Games\League of Legends\" \"--app-name=LeagueClient\" \"--ux-name=LeagueClientUx\" \"--ux-helper-name=LeagueClientUxHelper\" \"--log-dir=LeagueClient Logs\" \"--crash-reporting=crashpad\" \"--crash-environment=EUW1\" \"--crash-pipe=\\.\pipe\crashpad_12076_CFZRMYHTBJGPBIUH\" \"--app-log-file-path=C:/Riot Games/League of Legends/Logs/LeagueClient Logs/2020-07-13T13-33-41_12076_LeagueClient.log\" \"--app-pid=12076\" \"--output-base-dir=C:\Riot Games\League of Legends\" \"--no-proxy-server"; ``` Second, use this pattern: ``` (?:--remoting-auth-token=)([^"]*) ``` You can access match group with index 1. To test regexp you can use this link: <https://regexr.com/58bpb>
51,650
I'm not an expert on theology but I've heard that Christianity is filled with inconsistencies and incongruencies. My question, if this is the case, is whether this is normal for the major theologies or it is a specific fault of Christianity.
2018/05/01
[ "https://philosophy.stackexchange.com/questions/51650", "https://philosophy.stackexchange.com", "https://philosophy.stackexchange.com/users/30032/" ]
On religious views inconsistency is not necessarily a fault, after all God is supposed to surpass human reason and logic. And many paradoxical notions come from general [monotheistic doctrines](https://plato.stanford.edu/entries/monotheism/), like creation from nothing, omnipotence, omnibenevolence and omniscience, that Christianity and Islam share. Buddhism is different, although some versions of it can be interpreted as mystical monotheism along [panentheist lines](https://en.wikipedia.org/wiki/Panentheism#Buddhism). We should note that there is no such thing as a monolith Christian theology, there are Catholic, Orthodox, and Protestant denominations, not to mention lesser ones, with multiple theological systems and philosophical interpretations each. On philosophical issues for Christianity specifically see [Philosophy and Christian Theology](https://plato.stanford.edu/entries/christiantheology-philosophy). The official philosophy/theology of the Catholic Church, [Thomism](https://en.wikipedia.org/wiki/Thomism), is considered quite rational and coherent as these things go, even rationalistic. There is the opposite extreme too, called [fideism](https://plato.stanford.edu/entries/fideism/), best known from Tertullian's anti-rationalist motto concerning articles of faith:"*It is to be believed, because it is absurd… it is certain, because it is impossible*". Islam also has rationalistic ([Kalam](https://en.wikipedia.org/wiki/Kalam)), mystical (Sufism) and fanatical (Wahhabism) versions. A version of rationalistic Islamic theology, Averroism, was one of chief influences on Thomism.
Christs teachings were not written down until some time after his death. Given the nature of that, his authority couldn't weigh in on the composition and editing of these. It took some 300 years to settle on the New Testament canon, and the final set is very open to dispute, especially inclusion of The Book of Revelation. There are big divergences between Eastern Orthodox interpretations based on original Greek writings, and Catholic iterpretations based on sometimes bad translations into Latin <https://en.m.wikipedia.org/wiki/Theological_differences_between_the_Catholic_Church_and_the_Eastern_Orthodox_Church> Very little Christian practice or theology is based on the words and teachings of Christ, but instead the disciples and later community (eg. hell, non biblical,from Norse word). The idea of 'progressive revelation' is essential for this, but poses it's own problems. Reform has happened by various council's, and after the division of the churches by different means within each, such as papal bulls. There is no definitive version of the new testament. It is not considered revealed directly from god, although the apostles experienced pentacost. Some Christian patriarchs have been considered to have final authority of interpretations. This should most directly be contrasted with Judaism, where interpretation is 'argued out' in rabbinic study, and the body of believers to some extent have sovereignty, even occassionally arguing with the deity. The core religious text is a single definitive one, considered to be the revealed word of god, though there are layers of interpretation open to different degrees of questioning. Mohammed was able to write his teachings down himself, revealed directly from god, so they are seen in Islam as unchallangeable (with the exception arguably of the gharaniq verses). They have final authority. But schools of jurisprudence have developed profoundly different interpretations. The core text of Buddhism the Tripitaka was composed by the early community based on sermons of the Buddha, and transmitted orally at first, like the Christian template - the worlds first type-printed book was a Buddhist text, but still over 1,000 years after Buddha. In the Therevada school, around 1/3 of Buddhists, focused on Sri Lanka, this is considered the definitive text, the Pali Canon. In the Mahayana school, focused in China & Tibet, it is authoratative, but other sutras are also revered, often more; and there isn't a clear definitive canon in any of the sub-schools. The Tripitaka is not directly revealed words, but guidance and discussion by a highly developed being (not technically a deity, though he preached to deities including the creator, Brahma). The key divisions are among schools of philosophy within Buddhism. There are substantial disputes between schools over which others have any validity or deserve any respect. There are high degrees of synchretism across the Buddhist world, especially given wedding and funeral rights are not found in the sutras. Texts, what authority they are considered to have, and the process of authoratative interpretation of them, are crucial to understanding different religions. In Christianity, the discovery of the Dead Sea Scrolls, the earliest written versions of many books of the old testament, and mainly contemporary to Jesus, pose various problems for modern Christianity. I really like the book by Barbara Thiering on this, Jesus The Man <https://www.goodreads.com/book/show/296402.Jesus_the_Man> There are big problems reconciling biblical records of events with Roman records, and this book does a lot to reconcile this, and to explain the doctrinal position against previous religious practices that have been recorded as miracles. Resolving these comes at significant cost to modern religious practices. The consistency of the bible has implications for all the Abrahamic faiths. It's a big topic <https://en.m.wikipedia.org/wiki/Internal_consistency_of_the_Bible> Many of the theological disputes or contradictions (eg. Problem of Evil, & theodicies against it) arise out of textual issues.
26,860,858
I have Genymotion emulator running on a different machine.I can connect to that emulator from my development machine (by **adb connect 192.168.0.105**).The GCM client app runs well in that remote machine's emulator. When I try to register that emulator into my dev server, it says "cant connect to 10.0.3.2...).If the adb is connected , why cant I connect to my dev server in another machine ? The registration stuff works WELL in a emulator in the same machine as local dev server. I set the root as follows in client app- ``` builder.setRootUrl("http://10.0.3.2:8080/_ah/api/")//also tried 192.168.0.100,which is my local dev server ip address ```
2014/11/11
[ "https://Stackoverflow.com/questions/26860858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625343/" ]
`du -h` displays sizes in human readable form. You can't sort them, so just apply it on the already sorted files: ``` du --max-depth=1 | sort -n | cut -f2 | xargs du --max-depth=0 -h ``` Note: Doesn't work for directories with spaces in their names. For such a case, replace the `xargs` with the (much slower) loop: ``` while read f ; do du --max-depth=0 -h "$f" ; done ```
I don't generally worry about human readable format, you can just use: ``` du -s * 2>/dev/null | sort -k1 -n ``` to get them in the correct order, then concentrate on the last few. If you *really* need them in human readable format, you can post-process the output of `du` with something like: ``` du -s * 2>/dev/null | sort -k1 -n | awk '{ if ($1>999999999) { $1 = int($1/1000000000)"G" } else { if ($1>999999) { $1 = int($1/1000000)"M" } else { if ($1>999) { $1 = int($1/1000)"K" } } } } {print $0}' ``` This modifies the first argument depending on its size, to be in GB, MB, KB or left alone, then prints the modified line.
26,860,858
I have Genymotion emulator running on a different machine.I can connect to that emulator from my development machine (by **adb connect 192.168.0.105**).The GCM client app runs well in that remote machine's emulator. When I try to register that emulator into my dev server, it says "cant connect to 10.0.3.2...).If the adb is connected , why cant I connect to my dev server in another machine ? The registration stuff works WELL in a emulator in the same machine as local dev server. I set the root as follows in client app- ``` builder.setRootUrl("http://10.0.3.2:8080/_ah/api/")//also tried 192.168.0.100,which is my local dev server ip address ```
2014/11/11
[ "https://Stackoverflow.com/questions/26860858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625343/" ]
`du -h` displays sizes in human readable form. You can't sort them, so just apply it on the already sorted files: ``` du --max-depth=1 | sort -n | cut -f2 | xargs du --max-depth=0 -h ``` Note: Doesn't work for directories with spaces in their names. For such a case, replace the `xargs` with the (much slower) loop: ``` while read f ; do du --max-depth=0 -h "$f" ; done ```
Since a picture is worth a thousand words, why not do it graphically, using something like <http://www.marzocca.net/linux/baobab/index.html> ? ![enter image description here](https://i.stack.imgur.com/LaMsQ.png) Also, of course remove unneeded package files, temp files, backup files, etc, using something like <https://apps.ubuntu.com/cat/applications/raring/linux-disk-cleaner/> Run it manually or as a cron jo0b.
26,860,858
I have Genymotion emulator running on a different machine.I can connect to that emulator from my development machine (by **adb connect 192.168.0.105**).The GCM client app runs well in that remote machine's emulator. When I try to register that emulator into my dev server, it says "cant connect to 10.0.3.2...).If the adb is connected , why cant I connect to my dev server in another machine ? The registration stuff works WELL in a emulator in the same machine as local dev server. I set the root as follows in client app- ``` builder.setRootUrl("http://10.0.3.2:8080/_ah/api/")//also tried 192.168.0.100,which is my local dev server ip address ```
2014/11/11
[ "https://Stackoverflow.com/questions/26860858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1625343/" ]
Since a picture is worth a thousand words, why not do it graphically, using something like <http://www.marzocca.net/linux/baobab/index.html> ? ![enter image description here](https://i.stack.imgur.com/LaMsQ.png) Also, of course remove unneeded package files, temp files, backup files, etc, using something like <https://apps.ubuntu.com/cat/applications/raring/linux-disk-cleaner/> Run it manually or as a cron jo0b.
I don't generally worry about human readable format, you can just use: ``` du -s * 2>/dev/null | sort -k1 -n ``` to get them in the correct order, then concentrate on the last few. If you *really* need them in human readable format, you can post-process the output of `du` with something like: ``` du -s * 2>/dev/null | sort -k1 -n | awk '{ if ($1>999999999) { $1 = int($1/1000000000)"G" } else { if ($1>999999) { $1 = int($1/1000000)"M" } else { if ($1>999) { $1 = int($1/1000)"K" } } } } {print $0}' ``` This modifies the first argument depending on its size, to be in GB, MB, KB or left alone, then prints the modified line.
8,822,475
To illustrate my problem, let's say I have an instance of Thing which has two text properties - 'foo' and 'bar'. I want to create a Panel to edit instances of Thing. The panel has two TextField components, one for the 'foo' property and one for the 'bar' property. I want to be able to call `setDefaultModel()` on my Panel with an instance of `IModel<Thing>` and for the TextField components to reference this model. How best to achieve this? Should I override the `Panel.setDefaultModel()` method to also call setModel() on the two TextField components? Or perhaps create anonymous ReadOnlyModels for the TextField components, overriding the `getObject()` method to retrieve the object from the containing Panel's model? Neither of these seem very elegant to me, so I was wondering if there's a better way?
2012/01/11
[ "https://Stackoverflow.com/questions/8822475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207753/" ]
You can use a `PropertyModel` for the textFields. Pass the `IModel<Thing>` into the constructor of the `PropertyModel` with `foo` as the property name: ``` add(new TextField("fooFieldId", new PropertyModel(thingModel, "foo"))); ``` The `PropertyModel` will figure out that the thingModel is a `Model` and call `getObject().getFoo()` etc. This assumes the `IModel<Thing>` instance doesn't change, only its underlying object which can be changed calling `setDefaultModelObject`.
Maybe I'm just missing the point, but I can't find a `Panel.setModel()` in the JavaDocs of neither [1.4](http://wicket.apache.org/apidocs/1.4/org/apache/wicket/markup/html/panel/Panel.html) nor [1.5](http://wicket.apache.org/apidocs/1.5/org/apache/wicket/markup/html/panel/Panel.html). If it's something you implemented maybe you could change it not to replace the model object but to call `model.setObject()` instead? *Disclaimer*: Can't really check right now, cause there is no wicket at work and my home machine suffered a video card breakdown earlier...
8,822,475
To illustrate my problem, let's say I have an instance of Thing which has two text properties - 'foo' and 'bar'. I want to create a Panel to edit instances of Thing. The panel has two TextField components, one for the 'foo' property and one for the 'bar' property. I want to be able to call `setDefaultModel()` on my Panel with an instance of `IModel<Thing>` and for the TextField components to reference this model. How best to achieve this? Should I override the `Panel.setDefaultModel()` method to also call setModel() on the two TextField components? Or perhaps create anonymous ReadOnlyModels for the TextField components, overriding the `getObject()` method to retrieve the object from the containing Panel's model? Neither of these seem very elegant to me, so I was wondering if there's a better way?
2012/01/11
[ "https://Stackoverflow.com/questions/8822475", "https://Stackoverflow.com", "https://Stackoverflow.com/users/207753/" ]
You can use a `PropertyModel` for the textFields. Pass the `IModel<Thing>` into the constructor of the `PropertyModel` with `foo` as the property name: ``` add(new TextField("fooFieldId", new PropertyModel(thingModel, "foo"))); ``` The `PropertyModel` will figure out that the thingModel is a `Model` and call `getObject().getFoo()` etc. This assumes the `IModel<Thing>` instance doesn't change, only its underlying object which can be changed calling `setDefaultModelObject`.
Maybe this would help? ``` public abstract class AbstractWrapModel<T> extends Object implements IWrapModel<T> ``` Simple base class for IWrapModel objects. See IComponentAssignedModel or IComponentInheritedModel so that you don't have to have empty methods like detach or setObject() when not used in the wrapper. The detach method calls the wrapped models detach.
244,170
I have the following MySQL query that is querying naughty ip addresses from the last 24 hours and ban count >= 2. I don't want them if they are in an extra naughty ban list from the last 7 days and ban count >= 5. The query takes 3 minutes to run. If I replace `@__cutOff_1` with the actual hard coded date inline in the query instead of a variable, the query takes 2 seconds to run. Is this a bug in MySQL? The query explainer looks like this: [![enter image description here](https://i.stack.imgur.com/pfqGg.png)](https://i.stack.imgur.com/pfqGg.png) I am using the latest MySQL x64 8.0 on Windows 10 x64 as of 2019-07-30. Submissions table has 8 million rows, ip addresses table 360K. All where clauses are indexed. ``` SET @__cutOff_0 = '2019-07-29'; SET @__minBanCount_1 = 2; SET @__cutOff_1 = '2019-07-23'; SELECT `i`.`IPAddress`, `i`.`BanCount`, MAX(`s`.`Timestamp`) AS `c` FROM `Submissions` AS `s` CROSS JOIN `IPAddresses` AS `i` WHERE (((`s`.`Timestamp` >= @__cutOff_0) AND (`i`.`BanCount` >= @__minBanCount_1)) AND (`s`.`IPAddressId` = `i`.`IPAddress`)) AND `i`.`IPAddress` NOT IN ( SELECT DISTINCT `i2`.`IPAddress` FROM `Submissions` AS `s2` INNER JOIN `IPAddresses` AS `i2` ON `s2`.`IPAddressId` = `i2`.`IPAddress` WHERE (`s2`.`Timestamp` >= @__cutOff_1) AND (`i2`.`BanCount` >= 5) ) GROUP BY `i`.`IPAddress`, `i`.`BanCount` ORDER BY `c` DESC ```
2019/07/31
[ "https://dba.stackexchange.com/questions/244170", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/46214/" ]
Posted a bug / feature request with Oracle, they say it is a known issue. So there are two work-arounds: 1] Only use hard-coded values in sub-queries, no parameters. Not really an option for me, but may be for some people. 2] Create a temporary data set and filter the outer query with it in code behind. This is the route I went with. I create a set of strings for the inner query using a separate query, then I filter the outer query with this set in code behind to produce the final set.
For clarity, change ``` CROSS JOIN `IPAddresses` AS `i` WHERE (`s`.`IPAddressId` = `i`.`IPAddress`) ``` To ``` JOIN `IPAddresses` AS `i` ON (`s`.`IPAddressId` = `i`.`IPAddress`) ``` Change ``` AND `i`.`IPAddress` NOT IN ( SELECT DISTINCT `i2`.`IPAddress` ... ) ``` to ``` AND NOT EXISTS ( SELECT 1 FROM AS `IPAddresses` AS `i2` ... WHERE ... AND `i2`.`IPAddress` = `i`.`IPAddress` ) ``` And have composite index: ``` Submissions: INDEX(IPAddressId, Timestamp) -- in this order ``` Please provide `SHOW CREATE TABLE` and `EXPLAIN FORMAT=JSON SELECT ...`. If none of my suggestions help, then jynus's workaround (prepared statements) may be best.
14,419,552
I'm new to xslt and i'm doing a chat application and I want to save the users sessions as xml files that appear with the user predefined color and font so I used xslt to make that happen but I don't know how to take the font from the xml and applay it in the html tag so it appears with the font that the user selected. ``` <xsl:choose> <xsl:when test="/body/msg[italic/text()='true']"> <i> <font family="/body/msg[font/text()] color="/body/msg/color"> <xsl:value-of select="from" /><p>: </p> <xsl:value-of select="content"/><br/> </font> </i> </xsl:when> <xsl:when test="/body/msg[bold/text()='true']"> <b> <font family="/body/msg[font/text()]" color="/body/msg/color"> <xsl:value-of select="from" /><p>: </p> <xsl:value-of select="content"/><br/> </font> </b> </xsl:when> <xsl:when test="/body/msg[bold/text()='true'] and /body/msg[italic/text()='true']"> <b> <i> <font family="/body/msg[font/text()]" color="/body/msg/color"> <xsl:value-of select="from" /><p>: </p> <xsl:value-of select="content"/><br/> </font> </i> </b> </xsl:when> </xsl:choose> ```
2013/01/19
[ "https://Stackoverflow.com/questions/14419552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993693/" ]
It's hard to guess without seeing your input format, however I think you are looking for attribute value templates (Using `{ }` in literal result element attribute values). If you change ``` <font family="/body/msg[font/text()]" color="/body/msg/color"> ``` to ``` <font family="{/body/msg[font/text()]}" color="{/body/msg/color}"> ``` Then the `family` and `color` attributes will get values by evaluating those XPaths, although the Xpath for family looks very suspect. The above would give the string value of the whole msg element, I suspect it should be more like `/body/msg/font` To extract the string value of the font element. (It's usually best to avoid using `text()` if possible)
Could I propose using an approach like this? When possible, it's a good idea to avoid repeating large parts of your code (this is known as the [DRY principle](http://en.wikipedia.org/wiki/Don%27t_repeat_yourself), and with the following, if you need to make a change to that `<font>` portion and the stuff inside it, you don't have to change it in three places. This also handles the case where neither `bold` nor `italic` are specified, which yours doesn't currently take into account: ``` <?xml version="1.0" encoding="utf-8"?> <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="xml" indent="yes"/> <xsl:template match="body"> <body> <xsl:apply-templates select="msg" /> </body> </xsl:template> <xsl:template match="msg"> <xsl:param name="formatting" select="bold | italic"/> <xsl:choose> <xsl:when test="$formatting[self::bold and . = 'true']"> <b> <xsl:apply-templates select="."> <xsl:with-param name="formatting" select="$formatting[not(self::bold)]" /> </xsl:apply-templates> </b> </xsl:when> <xsl:when test="$formatting[self::italic and . = 'true']"> <i> <xsl:apply-templates select="."> <xsl:with-param name="formatting" select="$formatting[not(self::italic)]" /> </xsl:apply-templates> </i> </xsl:when> <xsl:otherwise> <font family="{font}" color="{color}"> <xsl:value-of select="from" /> <p>: </p> <xsl:value-of select="content"/> <br/> </font> </xsl:otherwise> </xsl:choose> </xsl:template> </xsl:stylesheet> ``` When run on this input: ``` <root> <body> <msg> <bold>true</bold> <italic>false</italic> <font>Arial</font> <color>Blue</color> <from>Shelly</from> <content>Hey, how are you doing?</content> </msg> <msg> <bold>false</bold> <italic>true</italic> <font>Times New Roman</font> <color>Red</color> <from>Tom</from> <content>What's up?</content> </msg> <msg> <bold>false</bold> <italic>false</italic> <font>Courier</font> <color>Yellow</color> <from>Fred</from> <content>I've been trying to reach you</content> </msg> <msg> <bold>true</bold> <italic>true</italic> <font>Comic Sans</font> <color>Green</color> <from>Lisa</from> <content>Talk to you later.</content> </msg> </body> </root> ``` Produces: ``` <body> <b> <font family="Arial" color="Blue"> Shelly<p>: </p>Hey, how are you doing?<br /> </font> </b> <i> <font family="Times New Roman" color="Red"> Tom<p>: </p>What's up?<br /> </font> </i> <font family="Courier" color="Yellow"> Fred<p>: </p>I've been trying to reach you<br /> </font> <b> <i> <font family="Comic Sans" color="Green"> Lisa<p>: </p>Talk to you later.<br /> </font> </i> </b> </body> ```
6,108,044
Is it possible to load a dropdownlist in asp.NET just when the user click the DropDownList for the firs time? I will try to explain it. I have an aspx page with a DropDownList with one item. ``` ListItem listlt = new ListItem("UNDEFINED", "-1"); ddl.Items.Insert(0, listlt); ``` I want to load all data in the DropDownList when the user click on the DropDownList. This is because the dropdownlist has a lot of data and the load of the page is very slow. any ideas? thx in advance
2011/05/24
[ "https://Stackoverflow.com/questions/6108044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/468891/" ]
You can use PageMethods instead. ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.Services; public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [WebMethod] public static Dictionary<string, string> getItems() { return new Dictionary<string, string>(){ {"1","Item1"} ,{"2","Item2"}}; } } ``` ASPX ``` <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>jQuery to call page methods in ASP.NET</title> <script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script> </head> <body> <form id="Form1" runat="server"> <asp:ScriptManager EnablePageMethods="true" ID="ScriptManager1" runat="server"> </asp:ScriptManager> <script type="text/javascript"> $(document).ready(function() { $('select#<%= DropDownList1.ClientID %>').click(function() { if (this.options.length <= 0) { PageMethods.getItems(function(res) { //alert('e'); for (r in res) { //$(this).append($('<option value="'+ r+'">' + res[r] + '</option>')); //$(this).append($('<option></option>')); $('select#<%= DropDownList1.ClientID %>').append( $('<option></option>').val(r).html(res[r]) ); } }); } }); }); </script> <asp:DropDownList ID="DropDownList1" runat="server" /> </form> </body> </html> ```
use jquery [`load`](http://api.jquery.com/load/) ``` $("select#theDropdownID").click(function(){ $(this).load("thedropdownItems.html"); }); ``` And in `thedropdownItems.html` ``` <option value='foo'>foo</option> <option value='bar'>bar</option> .... ```
664,693
I used an app in Windows 7, I think called dimmer to make the screen change its contrast settings so I could dim it lower than the controls of the PC defaults such as function key or the power options in control panel. Are there any of these type apps for Ubuntu 15.04 or approved for the latest Ubuntu LTS version on a PC-laptop. My computer has the use of function keys that change its brightness. It uses a 0-8 step brightness scale where 0 is the least bright and 8 is the brightest. 0 is too bright for my comfort level especially at night Following the suggestion in an answer below I added the following to etc/default/grub: ``` GRUB_CMDLINE_LINUX="resume=UUID=8bcb4169-f5ab-4ab6-b644-23e528088d41 acpi_backlight=vendor" ``` and updated grub My screen brightness did not go any dimmer than it had before. Oddly the brightness level seems to go to level 2 brightness on a 0-8 scale every time I reboot which it did not do prior to the etc/default/grub change. I reverted my grub file back to previous settings. I've installed **Indicator-Brightness** but this app does not dim my desktop any further than my function keys do and there are no menus to configure it to do so. I actively pursued other related questions to find a solution and reporting results of that action here. Its a process that takes time. To those that have provided input, Thank you for being patient. There are many aspects to graphics, screen brightness, contrasts, color temp, gamma. I tried ``` xbacklight -set 50 xbacklight -dec 10 and 03 etc. ``` This never increased or decreased beyond the usual 0-8 steps the PC provides i.e. no difference than current function key levels. Interestingly a comment below my question by Serg Kolo (thanks :) led me to info on `xrandr` via the linked sources at the bottom of the information he provided concerning his script: ``` xrandr -q | grep " connected" xrandr --output LVDS1 --brightness 0.5 ``` I had no idea this was available and already installed - apparently. With the second command in terminal my screen went darker than it ever has. I then tested: ``` xrandr --output LVDS1 --brightness 0.9 ``` Which got me back to the usual lowest level. This appears to be changing contrast levels not brightness, which is exactly what I was asking about. A simple command in terminal is as good as an App. I have since studied [xrandr](http://www.x.org/wiki/Projects/XRandR/) so that I can get an idea of how that command works. Perhaps someone could explain xrandr in easy terms but until then please explore the information from the link above. Edit Sept 16 ------------ In good faith and collaboration I decided to try the script from Serg's answer below. Following his directions I was able to make this script work for me. I wish I knew how the script determines what the name of my screen is for the use of `xrandr` command but the good news is it works. Thank you Serg and all for your input
2015/08/23
[ "https://askubuntu.com/questions/664693", "https://askubuntu.com", "https://askubuntu.com/users/424690/" ]
Follow these steps exactly: 1. Open terminal via `Ctrl`-`Alt`-`T` 2. Create a folder for the script ``` mkdir -p ~/bin ``` 3. Open the file `~/bin/setup.sh` in `gedit`. ``` gedit ~/bin/setup.sh ``` 4. **Copy** over the code below **save** the file, **close** the editor. ``` #!/bin/sh # Author: Serg Kolo # Date: Mon Aug 24 , 2015 # Description: setup script for creating # launcher and setting up the Dimmer script DESKFILE="$HOME/bin/Dimmer.desktop" SCHEMA="com.canonical.Unity.Launcher" KEY="favorites" SCRIPTFILE="$HOME/bin/Dimmer.sh" createBinFolder() { if [ ! -e "$HOME/bin" ]; then mkdir "$HOME/bin" fi echo "created bin folder" } createLauncher() { OUTPUT="$(gsettings get $SCHEMA $KEY | awk -v file="$DESKFILE" -v sq="'" '{ sub(/\]/,""); print $0","sq"application://"file sq "]" }')" ; gsettings set $SCHEMA $KEY "$OUTPUT" ; echo "Launcher for Dimmer created" } createScriptFile() { touch "$SCRIPTFILE" chmod 755 "$SCRIPTFILE" echo "Created script file. Please copy over the code to \"$SCRIPTFILE\"" } createDeskFile() { printf "[Desktop Entry]\nName=Dimmer\nExec=%s\nType=Application\nTerminal=false" "$SCRIPTFILE" > "$DESKFILE" } createBinFolder createScriptFile createDeskFile createLauncher ``` 5. Make the file executable and start the setup script ``` chmod 755 ~/bin/setup.sh && ~/bin/setup.sh ``` That script will create `bin` folder and blank `Dimmer.sh` file. 6. Edit the file `Dimmer.sh` ``` gedit ~/bin/Dimmer.sh ``` 7. **Copy** the code below, **save** and **close** the editor ``` #!/bin/sh # Name: backlightscript # Author: Serg Kolo # Date: March 2 , 2015 # Description: Simple script to change screen brightness using xrandr # uncomment this for debugging as needed # set -x NEWVAL=$( zenity --scale --min-value=0 --max-value=7 --text="Enter number between 0 and 7" ) && brightness=$(($NEWVAL+2)) if [ "$NEWVAL" != "" ]; then xrandr --output "$( xrandr | awk '$2=="connected" {print $1}')" --brightness 0.$brightness fi ``` Now you should be able to double click on the launcher and get that dimmer app working.
If you edit the file /etc/default/grub and change the line: ``` GRUB_CMDLINE_LINUX="" ``` to ``` GRUB_CMDLINE_LINUX="acpi_backlight=vendor" ``` and then run ``` sudo update-grub ``` and reboot, you should have the ability to lower the screen backlight to completely black.
50,739,391
My websocket client needs to send over a large message containing a base64 encoded image. Now, this is quit slow at the moment, and I thought... well maybe I should increase the ReceiveBufferSize of my websocket server within ASP.NET Core 2.0. Unfortunately... it seems to completely ignore my set buffer size... Reading through the documentation this is the only way to set the ReceiveBufferSize, that I found: ``` WebSocketOptions webSocketOptions = new WebSocketOptions() { ReceiveBufferSize = 8192 }; app.UseWebSockets(webSocketOptions); ``` The connection starts using a ApiController passing the HttpContext to a 'Service' containing this method: ``` public async Task Register(string hub, HttpContext httpContext) { if (httpContext.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); await _websocketServer.StartJoinHubWithId(webSocket, "hub", hub); } } ``` And then passing it to a WebsocketHandler class which resides in a seperate written library, containing this method *Get ready for some eye bleach*: ``` private async Task ReadHandler(WebSocket socket, string hub, string clientId) { byte[] buffer = new byte[8192]; try { int mode = 0; string partialReceived = ""; while (socket.State == WebSocketState.Open) { _isrunning = true; WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { _isrunning = false; await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } else { if (result.EndOfMessage) { if (result.MessageType == 0) { string message = Encoding.UTF8.GetString(buffer, 0, result.Count); if (message.Length > 0) { if (message.Contains("PARTIAL-DATA,START")) { mode = 1; } else if (message.Contains("PARTIAL-DATA,END")) { OnWebsocketMessageReceived(partialReceived, hub, clientId); partialReceived = ""; mode = 0; } switch (mode) { case 0: if (!message.Contains("PARTIAL-DATA")) { OnWebsocketMessageReceived(message, hub, clientId); } break; case 1: if (message.Contains("PARTIAL-DATA,")) { if (!message.Contains("PARTIAL-DATA,START") && !message.Contains("PARTIAL-DATA,END")) { partialReceived = partialReceived + message.Substring(13); } } else { Debug.WriteLine( "ERROR, PARTIAL DATA DID NOT START WITH PREFIX: PARTIAL-DATA, OR HAS START OR END IN ITS PREFIX"); mode = 0; } break; } } } Array.Clear(buffer, 0, buffer.Length); } } } await Stop(hub, clientId); } catch (WebSocketException e) { Debug.WriteLine("Websocket client closed without calling abort."); Debug.WriteLine(e.ToString()); await Stop(hub, clientId); } } ``` In the end, it results in this: [![enter image description here](https://i.stack.imgur.com/naQHb.png)](https://i.stack.imgur.com/naQHb.png) And from previous testing, I can tell that only part of the send string is being received. This tells me that it still uses the default 4 kb buffer. And I have no clue on how to resolve this.
2018/06/07
[ "https://Stackoverflow.com/questions/50739391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4564466/" ]
In a browser environment, you can assign variables by setting a property of the `window` object: ```js for (let i = 0; i < 8; i++) { window["a"+i] = "something "+i; } console.log(a2, a3); ``` As for your code, use this: ``` window["a"+i] = $('[name="answer['+i+']"]:checked').val(); ``` In the `for` loop
What I can think of is this ``` var i; for (i = 1; i < 8; i++) { let a[i] = $('[name="answer['+i+']"]:checked').val(); } ```
50,739,391
My websocket client needs to send over a large message containing a base64 encoded image. Now, this is quit slow at the moment, and I thought... well maybe I should increase the ReceiveBufferSize of my websocket server within ASP.NET Core 2.0. Unfortunately... it seems to completely ignore my set buffer size... Reading through the documentation this is the only way to set the ReceiveBufferSize, that I found: ``` WebSocketOptions webSocketOptions = new WebSocketOptions() { ReceiveBufferSize = 8192 }; app.UseWebSockets(webSocketOptions); ``` The connection starts using a ApiController passing the HttpContext to a 'Service' containing this method: ``` public async Task Register(string hub, HttpContext httpContext) { if (httpContext.WebSockets.IsWebSocketRequest) { WebSocket webSocket = await httpContext.WebSockets.AcceptWebSocketAsync(); await _websocketServer.StartJoinHubWithId(webSocket, "hub", hub); } } ``` And then passing it to a WebsocketHandler class which resides in a seperate written library, containing this method *Get ready for some eye bleach*: ``` private async Task ReadHandler(WebSocket socket, string hub, string clientId) { byte[] buffer = new byte[8192]; try { int mode = 0; string partialReceived = ""; while (socket.State == WebSocketState.Open) { _isrunning = true; WebSocketReceiveResult result = await socket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); if (result.MessageType == WebSocketMessageType.Close) { _isrunning = false; await socket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); } else { if (result.EndOfMessage) { if (result.MessageType == 0) { string message = Encoding.UTF8.GetString(buffer, 0, result.Count); if (message.Length > 0) { if (message.Contains("PARTIAL-DATA,START")) { mode = 1; } else if (message.Contains("PARTIAL-DATA,END")) { OnWebsocketMessageReceived(partialReceived, hub, clientId); partialReceived = ""; mode = 0; } switch (mode) { case 0: if (!message.Contains("PARTIAL-DATA")) { OnWebsocketMessageReceived(message, hub, clientId); } break; case 1: if (message.Contains("PARTIAL-DATA,")) { if (!message.Contains("PARTIAL-DATA,START") && !message.Contains("PARTIAL-DATA,END")) { partialReceived = partialReceived + message.Substring(13); } } else { Debug.WriteLine( "ERROR, PARTIAL DATA DID NOT START WITH PREFIX: PARTIAL-DATA, OR HAS START OR END IN ITS PREFIX"); mode = 0; } break; } } } Array.Clear(buffer, 0, buffer.Length); } } } await Stop(hub, clientId); } catch (WebSocketException e) { Debug.WriteLine("Websocket client closed without calling abort."); Debug.WriteLine(e.ToString()); await Stop(hub, clientId); } } ``` In the end, it results in this: [![enter image description here](https://i.stack.imgur.com/naQHb.png)](https://i.stack.imgur.com/naQHb.png) And from previous testing, I can tell that only part of the send string is being received. This tells me that it still uses the default 4 kb buffer. And I have no clue on how to resolve this.
2018/06/07
[ "https://Stackoverflow.com/questions/50739391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4564466/" ]
In a browser environment, you can assign variables by setting a property of the `window` object: ```js for (let i = 0; i < 8; i++) { window["a"+i] = "something "+i; } console.log(a2, a3); ``` As for your code, use this: ``` window["a"+i] = $('[name="answer['+i+']"]:checked').val(); ``` In the `for` loop
``` for (var i = 0; i < 8; ++i) { a[i] = "whatever"; } ``` as posted in [JavaScript: Dynamically Creating Variables for Loops](https://stackoverflow.com/questions/6645067/javascript-dynamically-creating-variables-for-loops)