qid
int64 1
74.7M
| question
stringlengths 0
58.3k
| date
stringlengths 10
10
| metadata
list | response_j
stringlengths 2
48.3k
| response_k
stringlengths 2
40.5k
|
---|---|---|---|---|---|
2,541,201 |
What is the set $$ C:= \bigcap\_{n \in \mathbb{N}} \left[0, {1\over n}\right[$$
I guess the result will be that $C$ is an empty set, because the upper limit converges to $0$,
as the limit of ${1\over n}$ is $0$.
$$\left[0, 0\right[ = \emptyset $$
I tried to prove this with the Archimedean property:
Assume $C$ is non-empty:
$$\exists x\in \mathbb{R}: x \in \bigcap\_{n \in \mathbb{N}} \left[0, {1\over n}\right[ $$ which is equal to $$ \forall n \in \mathbb{N}: \left[0, {1\over n}\right[ $$ concluding that $x$ must be positive, therefore $n > 0$ and $x > 0$.
By looking for solutions I found that the following completes the proof by contradiction. $$ \forall n \in \mathbb{N}: n < {1\over n} $$
I still don't quite get how the last statement was made and how this applies the Archimedean property.
Any help would be greatly appreciated!
|
2017/11/28
|
[
"https://math.stackexchange.com/questions/2541201",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/-1/"
] |
I claim that $$C: = \bigcap\_{n \in \mathbb{N}} \left[0, \frac{1}{n}\right[ = \{0\}$$
**Proof**: Suppose, for the sake of reaching a contradiction, that there exists $\epsilon > 0$ such that $\epsilon \in \left[0, \frac{1}{n}\right[$ for all $n \in \mathbb{N}$. Then, $\epsilon < \frac{1}{n}$ for every $n \in \mathbb{N}$, contradicting the archimedian property of the real numbers. Hence $C$ can't contain any strictly positive real numbers. Clearly, $C$ can contain no negative real numbers (because $C$ is the intersection of positive intervals), and it is also obvious that $C$ contains $0$, since $0 \in \left[0, \frac{1}{n}\right[$ for all $n \in \mathbb{N}$ and we are done!
|
Here is a way to *calculate* the result.$%
\require{begingroup}
\begingroup
\newcommand{\calc}{\begin{align} \quad &}
\newcommand{\op}[1]{\\ #1 \quad & \quad \unicode{x201c}}
\newcommand{\hints}[1]{\mbox{#1} \\ \quad & \quad \phantom{\unicode{x201c}} }
\newcommand{\hint}[1]{\mbox{#1} \unicode{x201d} \\ \quad & }
\newcommand{\endcalc}{\end{align}}
\newcommand{\subcalch}[1]{\\ \quad & \quad #1 \\ \quad &}
\newcommand{\subcalc}{\quad \begin{aligned} \quad & \\ \bullet \quad & }
\newcommand{\endsubcalc}{\end{aligned} \\ \\ \cdot \quad &}
\newcommand{\Ref}[1]{\text{(#1)}}
\newcommand{\then}{\Rightarrow}
\newcommand{\when}{\Leftarrow}
\newcommand{\false}{\text{false}}
%$
Which $\;x\;$ are in this set of yours? Letting $\;n\;$ range over the positive integers, we have for all $\;x\;$
$$\calc
x \in \bigcap\_n \left[ 0 , \tfrac 1 n \right[
\op\equiv\hint{definition of $\;\bigcap\;$; definition of half-open interval}
\langle \forall n :: x \in \mathbb R \;\land\; 0 \le x < \tfrac 1 n \rangle
\op\equiv\hints{rightmost part: multiply both sides by $\;n\;$}\hint{-- work towards isolating $\;n\;$}
\langle \forall n :: x \in \mathbb R \;\land\; 0 \le x \;\land\; n\,x \lt 1 \rangle
\op\equiv\hints{rightmost part: divide both sides by $\;x\;$, special}\hint{case $\;x=0\;$ -- isolating $\;n\;$}
\langle \forall n :: x \in \mathbb R \;\land\; (x = 0 \;\lor\; (x > 0 \land n \lt \tfrac 1 x)) \rangle
\op\equiv\hints{logic: move all parts that don't have $\;n\;$ out of $\;\forall n\;$}\hint{-- to simplify}
x \in \mathbb R \;\land\; (x = 0 \;\lor\; (x > 0 \land \langle \forall n :: n \lt \tfrac 1 x \rangle))
\op\equiv\hint{choose, e.g., $\;n := \left\lceil \tfrac 1 x \right\rceil\;$ which is a positive integer}
x \in \mathbb R \;\land\; (x = 0 \;\lor\; (x > 0 \land \false))
\op\equiv\hint{logic: simplify}
x = 0
\endcalc$$
so we've proven
$$
\bigcap\_n \left[ 0 , \tfrac 1 n \right[ \;=\; \{0\}
$$
$%
\endgroup
%$
|
56,210,956 |
I really have two questions:
1. Why is this line okay-
`Result = Application.WorksheetFunction.CountIfs(Range("AF:AF"), "GroupA", Range("AJ:AJ"), "Passing")`
But this isn't?
`Result = Application.WorksheetFunction.CountIfs(Range("L:L"), "11", (Range("AF:AF"), "GroupA", Range("AJ:AJ"), "Passing")`
When I try to add that extra criteria to the front, I get an error that says there is an expected parenthesis in place of the comma at this part-
`(Range(:AF:AF"),`
When I add the extra criteria to the end, it doesn't seem to have a problem with it. Very grumpy little thing.
2. The reason I ask is that I've been stuck trying to add an argument to the code that uses OR statements, but I'm not sure of the proper syntax. I'm trying to count all students who are at a certain grade level that are in a certain group and who are "Passing."
I've tried several different things, including this:
`Result = Application.WorksheetFunction.CountIfs(Range("AF:AF"), "GroupA", Range("AJ:AJ"), "Passing", Range("L:L"), "<>" "7" Or "8")`
and this
`Result = Application.WorksheetFunction.CountIfs(Range("AF:AF"), "GroupA", Range("AJ:AJ"), "Passing", Range("L:L"), "9" Or "10" Or "11" Or "12")`
The last one was the closest I've gotten, as it actually gives a value of zero instead of an error in the code, but I'm still not quite there.
I also tried an if-then statement at the beginning to weed out the grade I needed initially, but that WAY didn't work and gave me all kinds of runtime errors that made my head hurt.
I know that the problem is in the OR arguments because this line works:
`AlgAdv = Application.WorksheetFunction.CountIfs(Range("AF:AF"), "GroupA", Range("AJ:AJ"), "Passing", Range("L:L"), "9")`
I saw several posts about countifs formulas within Excel, but fewer about countifs in VBA. Of those, I saw only one that referenced an OR argument but the answer was not clear to me.
Any recommendations?
|
2019/05/19
|
[
"https://Stackoverflow.com/questions/56210956",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10018052/"
] |
You can do something like this:
```
Result = Application.WorksheetFunction.CountIfs(Range("AF:AF"), "GroupA", _
Range("AJ:AJ"), "Passing", _
Range("L:L"), ">=9", _
Range("L:L"), "<=12")
```
|
I wonder if this link may help: <https://stackoverflow.com/a/8726792/11437092> (unless this is already one you've seen, of course).
It seems that you'd be able to use separate COUNTIF functions according to the number of OR arguments you need, and then simply add them together. May not be the most efficient way to do this, however.
|
58,802,772 |
```
TextInputType.numberWithOptions(decimal: true),
```
I'm using the above code as a `keyboardType` in my `TextFormField` but in some devices, the device doesn't display comma or dot. Screenshot is given below:
[](https://i.stack.imgur.com/k5FHS.png)
Thinking of using this package: <https://pub.dev/packages/virtual_keyboard>
Any idea on how to solve it?
This doesn't solve my problem because in my case, it's happening on Android.
[Flutter TextField with number keyboard, comma is needed instead of period (Only iOS)](https://stackoverflow.com/questions/55570414/flutter-textfield-with-number-keyboard-comma-is-needed-instead-of-period-only)
|
2019/11/11
|
[
"https://Stackoverflow.com/questions/58802772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9779791/"
] |
This parameter will solve the problem
```
keyboardType: TextInputType.numberWithOptions(decimal: true),
```
|
On iOS you have to enable the de (or any other locale than en\_US) locale in the ios build settings even for flutter apps.
1. Open the IOS folder in your flutter project
2. Inside the IOS folder open Runner.xcworkspace folder with xCode.
3. Click on the runner you will see bunch of option, click on info and under the Localization native development region select United States.
4. Rebuild the project
[Here is the image attached](https://i.stack.imgur.com/8cr2Z.png)
|
58,802,772 |
```
TextInputType.numberWithOptions(decimal: true),
```
I'm using the above code as a `keyboardType` in my `TextFormField` but in some devices, the device doesn't display comma or dot. Screenshot is given below:
[](https://i.stack.imgur.com/k5FHS.png)
Thinking of using this package: <https://pub.dev/packages/virtual_keyboard>
Any idea on how to solve it?
This doesn't solve my problem because in my case, it's happening on Android.
[Flutter TextField with number keyboard, comma is needed instead of period (Only iOS)](https://stackoverflow.com/questions/55570414/flutter-textfield-with-number-keyboard-comma-is-needed-instead-of-period-only)
|
2019/11/11
|
[
"https://Stackoverflow.com/questions/58802772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9779791/"
] |
This parameter will solve the problem
```
keyboardType: TextInputType.numberWithOptions(decimal: true),
```
|
It's a well known *Android* issue in Samsung Keyboards
<https://github.com/flutter/flutter/issues/61175>
### TLDR;
Usually the work-around is to fallback to text keyboard.
I developed a package with this work-around to easy get the keyboard vendor name and then make some crafty `if samsung then TextInputType.text`
package: keyboard\_name
However, it don't solves the problem.
### Long and ***cooler*** way
First: Format Inputters
*note: I didn't find a way to enable the comma*
Convert the inputted dot to comma and don't worry about the disabled comma
To do this you need to extend a Text Input Formatter
```dart
class CommaFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
String _text = newValue.text;
//This is only if you need signed numbers. Will convert the first '.'(dot) to '-'(minus)
//if (_text.isNotEmpty && _text[0] == '.')
// _text = _text.replaceFirst('.', '-');
return newValue.copyWith(
text: _text.replaceAll('.', ','),
);
}
}
```
Also, you can put another *smartass* regex to format after this one
```dart
TextFormField(
inputFormatters: [
CommaFormatter(),
FilteringTextInputFormatter.allow(
RegExp(
//r'^[-]{0,1}[0-9]*[,]?[0-9]*', //signed regex
r'^[0-9]*[,]?[0-9]*',
),
),
],
/.../
}
```
|
58,802,772 |
```
TextInputType.numberWithOptions(decimal: true),
```
I'm using the above code as a `keyboardType` in my `TextFormField` but in some devices, the device doesn't display comma or dot. Screenshot is given below:
[](https://i.stack.imgur.com/k5FHS.png)
Thinking of using this package: <https://pub.dev/packages/virtual_keyboard>
Any idea on how to solve it?
This doesn't solve my problem because in my case, it's happening on Android.
[Flutter TextField with number keyboard, comma is needed instead of period (Only iOS)](https://stackoverflow.com/questions/55570414/flutter-textfield-with-number-keyboard-comma-is-needed-instead-of-period-only)
|
2019/11/11
|
[
"https://Stackoverflow.com/questions/58802772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9779791/"
] |
It's a well known *Android* issue in Samsung Keyboards
<https://github.com/flutter/flutter/issues/61175>
### TLDR;
Usually the work-around is to fallback to text keyboard.
I developed a package with this work-around to easy get the keyboard vendor name and then make some crafty `if samsung then TextInputType.text`
package: keyboard\_name
However, it don't solves the problem.
### Long and ***cooler*** way
First: Format Inputters
*note: I didn't find a way to enable the comma*
Convert the inputted dot to comma and don't worry about the disabled comma
To do this you need to extend a Text Input Formatter
```dart
class CommaFormatter extends TextInputFormatter {
@override
TextEditingValue formatEditUpdate(
TextEditingValue oldValue,
TextEditingValue newValue,
) {
String _text = newValue.text;
//This is only if you need signed numbers. Will convert the first '.'(dot) to '-'(minus)
//if (_text.isNotEmpty && _text[0] == '.')
// _text = _text.replaceFirst('.', '-');
return newValue.copyWith(
text: _text.replaceAll('.', ','),
);
}
}
```
Also, you can put another *smartass* regex to format after this one
```dart
TextFormField(
inputFormatters: [
CommaFormatter(),
FilteringTextInputFormatter.allow(
RegExp(
//r'^[-]{0,1}[0-9]*[,]?[0-9]*', //signed regex
r'^[0-9]*[,]?[0-9]*',
),
),
],
/.../
}
```
|
On iOS you have to enable the de (or any other locale than en\_US) locale in the ios build settings even for flutter apps.
1. Open the IOS folder in your flutter project
2. Inside the IOS folder open Runner.xcworkspace folder with xCode.
3. Click on the runner you will see bunch of option, click on info and under the Localization native development region select United States.
4. Rebuild the project
[Here is the image attached](https://i.stack.imgur.com/8cr2Z.png)
|
54,237,641 |
Is there a way I can make asdf load all files (\*.lisp) in a directory without naming them all in my .asd file? Using wildcards in both directory or filename spec doesn't work. Can someone please help?
|
2019/01/17
|
[
"https://Stackoverflow.com/questions/54237641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10661741/"
] |
See [`DIRECTORY`](http://clhs.lisp.se/Body/f_dir.htm):
```
CL-USER> (directory "*.lisp")
=> ("a.lisp"
"b.lisp"
...)
```
Then, call [`LOAD`](http://clhs.lisp.se/Body/f_load.htm) for each file.
But then, you could also do:
```
CL-USER> (loop for f in * collect `(:file ,(pathname-name f)))
((:file "a") (:file "b"))
```
Then, you can copy that in your .asd file, so that your dependencies are a little more explicit.
|
The asdf repository comes with a asdf/contrib/wild-modules.lisp extension that does what you say. I'd still use package-inferred-system instead.
|
54,237,641 |
Is there a way I can make asdf load all files (\*.lisp) in a directory without naming them all in my .asd file? Using wildcards in both directory or filename spec doesn't work. Can someone please help?
|
2019/01/17
|
[
"https://Stackoverflow.com/questions/54237641",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10661741/"
] |
You could use the “package inferred system” extension of ASDF: <https://common-lisp.net/project/asdf/asdf/The-package_002dinferred_002dsystem-extension.html#The-package_002dinferred_002dsystem-extension>. You will have to adhere to a directory and file naming convention for this, but it is (superficially) a bit closer to how such things are organized in other languages.
I have to admit that I prefer the explicit layout in the asd file, though, because it keeps the concepts of systems, packages, and files clearly apart.
|
The asdf repository comes with a asdf/contrib/wild-modules.lisp extension that does what you say. I'd still use package-inferred-system instead.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
As shown in [this post](http://caraulean.com/blog/2012/08/30/visual-studio-2012-dark-theme-tip/), you can condense the code to a single style by using a trigger, since `DesignerProperties.IsInDesignMode` is an [attached property](http://msdn.microsoft.com/en-us/library/ms749011.aspx).
Actually, the code there isn't quite right. It defines an implicit style for `TargetType="{x:Type UserControl}"`, which would be ignored at runtime anyway because your UserControl is actually a derived class -- as [Metro Smurf](https://stackoverflow.com/a/5185385/933416) points out in his first point:
>
> The App.xaml will effect the UserControl at design time because a
> typed style is applied on an object automatically, but it is not
> applied to a derived object (UserControl in this case). So, at design
> time, VS thinks it should apply the style, but at runtime, it will be
> ignored.
>
>
>
The right way to do it would be to give it a key and apply it manually to your UserControls:
```
<Application
...
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework">
...
<Application.Resources>
...
<Style x:Key="DesignerBlackBackgroundStyle" TargetType="Control">
<Style.Triggers>
<Trigger Property="componentModel:DesignerProperties.IsInDesignMode"
Value="True">
<Setter Property="Background" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
```
and:
```
<UserControl x:Class="MyUserControl"
Style="{StaticResource ResourceKey=DesignerBlackBackgroundStyle}">
```
As a trigger, this has an extra benefit over setting the background in code-behind -- it will behave properly if the background is explicitly set somewhere else, such as from a containing UserControl:
```
<UserControl x:Class="ContainerUserControl" ...>
...
<local:MyUserControl Background="Gray" />
```
[Local values have precedence over style triggers](http://msdn.microsoft.com/en-CA/library/ms743230.aspx#listing), so on this screen the designer would use a gray background, whereas it would be black when designing `MyUserControl` stand-alone.
|
Set the background color of the usercontrol to black in the XAML, then set it to transparent in code.
**Edit:**
If you're not comfortable leaving the code this way, then you can revert this change before you release, once you are done with all the designer work, though there is no harm in leaving it in.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
In your XAML, set your background to black. Then in your user control, use the DesignerProperties to set the background at runtime:
**XAML**
```
<UserControl .... Background="Black" .... >
```
**Code Behind**
```
public YourUserControl()
{
InitializeComponent();
if( !System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Transparent;
}
}
```
---
**Alternate Method**
--------------------
**UserControl:**
In your user control, do not declare a background color:
```
<UserControl ... namespaces ...>
```
**UserControl Code Behind:**
In your user control's constructor, use the DesignTime method as above, but check to see if it is Design Mode (opposite check from other method):
```
public YourUserControl()
{
InitializeComponent();
if( System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Black;
}
}
```
**App.xaml:**
Finally, in your App.xaml, add a style to set a background color for UserControls:
```
<Application.Resources>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="Black" />
</Style>
</Application.Resources>
```
Here's what's happening:
1. The App.xaml will effect the UserControl at design time because a typed style is applied on an object automatically, but it is **not** applied to a derived object (UserControl in this case). So, at design time, VS thinks it should apply the style, but at runtime, it will be ignored.
2. The `GetIsInDesignMode` check will effect the UserControl when viewing the control in a Window that is using the UserControl because VS is compiling the UserControl at design time in order to render it in the Visual Designer.
HTH's
|
As shown in [this post](http://caraulean.com/blog/2012/08/30/visual-studio-2012-dark-theme-tip/), you can condense the code to a single style by using a trigger, since `DesignerProperties.IsInDesignMode` is an [attached property](http://msdn.microsoft.com/en-us/library/ms749011.aspx).
Actually, the code there isn't quite right. It defines an implicit style for `TargetType="{x:Type UserControl}"`, which would be ignored at runtime anyway because your UserControl is actually a derived class -- as [Metro Smurf](https://stackoverflow.com/a/5185385/933416) points out in his first point:
>
> The App.xaml will effect the UserControl at design time because a
> typed style is applied on an object automatically, but it is not
> applied to a derived object (UserControl in this case). So, at design
> time, VS thinks it should apply the style, but at runtime, it will be
> ignored.
>
>
>
The right way to do it would be to give it a key and apply it manually to your UserControls:
```
<Application
...
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework">
...
<Application.Resources>
...
<Style x:Key="DesignerBlackBackgroundStyle" TargetType="Control">
<Style.Triggers>
<Trigger Property="componentModel:DesignerProperties.IsInDesignMode"
Value="True">
<Setter Property="Background" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
```
and:
```
<UserControl x:Class="MyUserControl"
Style="{StaticResource ResourceKey=DesignerBlackBackgroundStyle}">
```
As a trigger, this has an extra benefit over setting the background in code-behind -- it will behave properly if the background is explicitly set somewhere else, such as from a containing UserControl:
```
<UserControl x:Class="ContainerUserControl" ...>
...
<local:MyUserControl Background="Gray" />
```
[Local values have precedence over style triggers](http://msdn.microsoft.com/en-CA/library/ms743230.aspx#listing), so on this screen the designer would use a gray background, whereas it would be black when designing `MyUserControl` stand-alone.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
In your XAML, set your background to black. Then in your user control, use the DesignerProperties to set the background at runtime:
**XAML**
```
<UserControl .... Background="Black" .... >
```
**Code Behind**
```
public YourUserControl()
{
InitializeComponent();
if( !System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Transparent;
}
}
```
---
**Alternate Method**
--------------------
**UserControl:**
In your user control, do not declare a background color:
```
<UserControl ... namespaces ...>
```
**UserControl Code Behind:**
In your user control's constructor, use the DesignTime method as above, but check to see if it is Design Mode (opposite check from other method):
```
public YourUserControl()
{
InitializeComponent();
if( System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Black;
}
}
```
**App.xaml:**
Finally, in your App.xaml, add a style to set a background color for UserControls:
```
<Application.Resources>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="Black" />
</Style>
</Application.Resources>
```
Here's what's happening:
1. The App.xaml will effect the UserControl at design time because a typed style is applied on an object automatically, but it is **not** applied to a derived object (UserControl in this case). So, at design time, VS thinks it should apply the style, but at runtime, it will be ignored.
2. The `GetIsInDesignMode` check will effect the UserControl when viewing the control in a Window that is using the UserControl because VS is compiling the UserControl at design time in order to render it in the Visual Designer.
HTH's
|
Set the background color of the usercontrol to black in the XAML, then set it to transparent in code.
**Edit:**
If you're not comfortable leaving the code this way, then you can revert this change before you release, once you are done with all the designer work, though there is no harm in leaving it in.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
Alternatively, as of VS 2013, you can do this in Tools -> Options -> Fonts and Colors, XAML UI Designer.
The editable foreground / background colors there are the colors of the checkerboard background. I just set them both to a darkish grey color that seems to work for both light and dark theme'd background stuff.
|
Set the background color of the usercontrol to black in the XAML, then set it to transparent in code.
**Edit:**
If you're not comfortable leaving the code this way, then you can revert this change before you release, once you are done with all the designer work, though there is no harm in leaving it in.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
As shown in [this post](http://caraulean.com/blog/2012/08/30/visual-studio-2012-dark-theme-tip/), you can condense the code to a single style by using a trigger, since `DesignerProperties.IsInDesignMode` is an [attached property](http://msdn.microsoft.com/en-us/library/ms749011.aspx).
Actually, the code there isn't quite right. It defines an implicit style for `TargetType="{x:Type UserControl}"`, which would be ignored at runtime anyway because your UserControl is actually a derived class -- as [Metro Smurf](https://stackoverflow.com/a/5185385/933416) points out in his first point:
>
> The App.xaml will effect the UserControl at design time because a
> typed style is applied on an object automatically, but it is not
> applied to a derived object (UserControl in this case). So, at design
> time, VS thinks it should apply the style, but at runtime, it will be
> ignored.
>
>
>
The right way to do it would be to give it a key and apply it manually to your UserControls:
```
<Application
...
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework">
...
<Application.Resources>
...
<Style x:Key="DesignerBlackBackgroundStyle" TargetType="Control">
<Style.Triggers>
<Trigger Property="componentModel:DesignerProperties.IsInDesignMode"
Value="True">
<Setter Property="Background" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
```
and:
```
<UserControl x:Class="MyUserControl"
Style="{StaticResource ResourceKey=DesignerBlackBackgroundStyle}">
```
As a trigger, this has an extra benefit over setting the background in code-behind -- it will behave properly if the background is explicitly set somewhere else, such as from a containing UserControl:
```
<UserControl x:Class="ContainerUserControl" ...>
...
<local:MyUserControl Background="Gray" />
```
[Local values have precedence over style triggers](http://msdn.microsoft.com/en-CA/library/ms743230.aspx#listing), so on this screen the designer would use a gray background, whereas it would be black when designing `MyUserControl` stand-alone.
|
Are you able to use Blend for designing? Blend has an option to switch between light and dark color schemes.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
Are you able to use Blend for designing? Blend has an option to switch between light and dark color schemes.
|
Set the XAML Designer background color to Gray.
Tools > Options> Fonts and Colors:
* Show settings for: XAML Designer,
* Display items: Artboard Background,
* Item foreground/background: Gray.
[](https://i.stack.imgur.com/NVkck.png)
Now you can see text in XAML Designer
[](https://i.stack.imgur.com/O7hGp.png)
It's a shame there is this inconvenience.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
In your XAML, set your background to black. Then in your user control, use the DesignerProperties to set the background at runtime:
**XAML**
```
<UserControl .... Background="Black" .... >
```
**Code Behind**
```
public YourUserControl()
{
InitializeComponent();
if( !System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Transparent;
}
}
```
---
**Alternate Method**
--------------------
**UserControl:**
In your user control, do not declare a background color:
```
<UserControl ... namespaces ...>
```
**UserControl Code Behind:**
In your user control's constructor, use the DesignTime method as above, but check to see if it is Design Mode (opposite check from other method):
```
public YourUserControl()
{
InitializeComponent();
if( System.ComponentModel.DesignerProperties.GetIsInDesignMode( this ) )
{
this.Background = Brushes.Black;
}
}
```
**App.xaml:**
Finally, in your App.xaml, add a style to set a background color for UserControls:
```
<Application.Resources>
<Style TargetType="{x:Type UserControl}">
<Setter Property="Background" Value="Black" />
</Style>
</Application.Resources>
```
Here's what's happening:
1. The App.xaml will effect the UserControl at design time because a typed style is applied on an object automatically, but it is **not** applied to a derived object (UserControl in this case). So, at design time, VS thinks it should apply the style, but at runtime, it will be ignored.
2. The `GetIsInDesignMode` check will effect the UserControl when viewing the control in a Window that is using the UserControl because VS is compiling the UserControl at design time in order to render it in the Visual Designer.
HTH's
|
Set the XAML Designer background color to Gray.
Tools > Options> Fonts and Colors:
* Show settings for: XAML Designer,
* Display items: Artboard Background,
* Item foreground/background: Gray.
[](https://i.stack.imgur.com/NVkck.png)
Now you can see text in XAML Designer
[](https://i.stack.imgur.com/O7hGp.png)
It's a shame there is this inconvenience.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
Alternatively, as of VS 2013, you can do this in Tools -> Options -> Fonts and Colors, XAML UI Designer.
The editable foreground / background colors there are the colors of the checkerboard background. I just set them both to a darkish grey color that seems to work for both light and dark theme'd background stuff.
|
As shown in [this post](http://caraulean.com/blog/2012/08/30/visual-studio-2012-dark-theme-tip/), you can condense the code to a single style by using a trigger, since `DesignerProperties.IsInDesignMode` is an [attached property](http://msdn.microsoft.com/en-us/library/ms749011.aspx).
Actually, the code there isn't quite right. It defines an implicit style for `TargetType="{x:Type UserControl}"`, which would be ignored at runtime anyway because your UserControl is actually a derived class -- as [Metro Smurf](https://stackoverflow.com/a/5185385/933416) points out in his first point:
>
> The App.xaml will effect the UserControl at design time because a
> typed style is applied on an object automatically, but it is not
> applied to a derived object (UserControl in this case). So, at design
> time, VS thinks it should apply the style, but at runtime, it will be
> ignored.
>
>
>
The right way to do it would be to give it a key and apply it manually to your UserControls:
```
<Application
...
xmlns:componentModel="clr-namespace:System.ComponentModel;assembly=PresentationFramework">
...
<Application.Resources>
...
<Style x:Key="DesignerBlackBackgroundStyle" TargetType="Control">
<Style.Triggers>
<Trigger Property="componentModel:DesignerProperties.IsInDesignMode"
Value="True">
<Setter Property="Background" Value="Black" />
</Trigger>
</Style.Triggers>
</Style>
```
and:
```
<UserControl x:Class="MyUserControl"
Style="{StaticResource ResourceKey=DesignerBlackBackgroundStyle}">
```
As a trigger, this has an extra benefit over setting the background in code-behind -- it will behave properly if the background is explicitly set somewhere else, such as from a containing UserControl:
```
<UserControl x:Class="ContainerUserControl" ...>
...
<local:MyUserControl Background="Gray" />
```
[Local values have precedence over style triggers](http://msdn.microsoft.com/en-CA/library/ms743230.aspx#listing), so on this screen the designer would use a gray background, whereas it would be black when designing `MyUserControl` stand-alone.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
Alternatively, as of VS 2013, you can do this in Tools -> Options -> Fonts and Colors, XAML UI Designer.
The editable foreground / background colors there are the colors of the checkerboard background. I just set them both to a darkish grey color that seems to work for both light and dark theme'd background stuff.
|
Are you able to use Blend for designing? Blend has an option to switch between light and dark color schemes.
|
5,183,801 |
I am currently working on a user control that has white text and a transparent background. Unfortunately because the XAML design view within VS2010 has a white background I cannot see anything that I am designing!
I have been through all the settings dialogs I can think of, but have been unable to find a setting that changes the background colour of the XAML designer.
Does anyone know how this can be done?
|
2011/03/03
|
[
"https://Stackoverflow.com/questions/5183801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/249933/"
] |
Are you able to use Blend for designing? Blend has an option to switch between light and dark color schemes.
|
Set the background color of the usercontrol to black in the XAML, then set it to transparent in code.
**Edit:**
If you're not comfortable leaving the code this way, then you can revert this change before you release, once you are done with all the designer work, though there is no harm in leaving it in.
|
31,245,674 |
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops `while($row = $result->fetch())` however how would I do the following with PDO prepared statements?
```
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
```
I've tried this but with no joy:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
```
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31245674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045858/"
] |
To properly count rows with PDO you have to do this -
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
```
But you would be better off using `LIMIT` in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the `for` condition just set the static number *unless* you're doing something weird, like possibly pagination.
|
What you could try is:
```
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);
```
|
31,245,674 |
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops `while($row = $result->fetch())` however how would I do the following with PDO prepared statements?
```
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
```
I've tried this but with no joy:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
```
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31245674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045858/"
] |
To properly count rows with PDO you have to do this -
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
```
But you would be better off using `LIMIT` in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the `for` condition just set the static number *unless* you're doing something weird, like possibly pagination.
|
You can try it this way:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
```
|
31,245,674 |
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops `while($row = $result->fetch())` however how would I do the following with PDO prepared statements?
```
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
```
I've tried this but with no joy:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
```
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31245674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045858/"
] |
To properly count rows with PDO you have to do this -
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$rows = $result->fetch(PDO::FETCH_NUM);
echo $rows[0];
```
But you would be better off using `LIMIT` in your query if all you want to do is get a static number of results.
In addition you're making your loop overly complex, there is no need to test for a range in the `for` condition just set the static number *unless* you're doing something weird, like possibly pagination.
|
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
```
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
```
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
|
31,245,674 |
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops `while($row = $result->fetch())` however how would I do the following with PDO prepared statements?
```
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
```
I've tried this but with no joy:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
```
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31245674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045858/"
] |
You can try it this way:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_rows = $result->fetchAll();
$loop_count = count($loop_rows);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
echo $loop_rows[$row]['field'];
}
```
|
What you could try is:
```
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);
```
|
31,245,674 |
I'm in the process of updating my old mysql database techniques to prepared pdo statements. I'm all good with while loops `while($row = $result->fetch())` however how would I do the following with PDO prepared statements?
```
$sql = "SELECT * FROM table WHERE id=".$id;
$result = mysql_query($sql) or die(mysql_error());
$loop_count = mysql_num_rows($result);
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = mysql_fetch_array($result);
echo $loop_row['field'];
}
```
I've tried this but with no joy:
```
$result = $conn->prepare("SELECT * FROM table WHERE id= ?");
$result->execute(array($id));
$loop_count = $result->rowCount();
for($row=0;$row<7 && $loop_count-->0;$row++)
{
// Get next row
$loop_row = $result->fetch();
echo $loop_row['field'];
}
```
Thanks!
UPDATE: The reason for using a for loop instead of a while loop is the ability to paginate the results, otherwise I would just put LIMIT 7 on the end of the SQL query.
|
2015/07/06
|
[
"https://Stackoverflow.com/questions/31245674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3045858/"
] |
As requested by the OP, here's an example of PDO prepared statements using LIMIT and OFFSET for pagination purposes. Please note i prefer to use bindValue() rather than passing parameters to execute(), but this is personal preference.
```
$pagesize = 7; //put this into a configuration file
$pagenumber = 3; // NOTE: ZERO BASED. First page is nr. 0.
//You get this from the $_REQUEST (aka: GET or POST)
$result = $conn->prepare("SELECT *
FROM table
WHERE id= :id
LIMIT :pagesize
OFFSET :offset");
$result->bindValue(':id', $id);
$result->bindValue(':pagesize', $pagesize);
$result->bindValue(':offset', $pagesize * $pagenumber);
$result->execute();
$rows = $result->fetchAll(PDO::FETCH_ASSOC);
```
This gives you the complete resultset of rows, limited to your required page. You need another query to calculate the total number of rows, of course.
|
What you could try is:
```
//Get your page number for example 2
$pagenum = 2;
//Calculate the offset
$offset = 7 * $pagenum;
//Create array
$data = array();
$result = $conn->prepare("SELECT * FROM table WHERE id= ? LIMIT 7 OFFSET ?");
$result->bind_param("ii", $id,$offset);
$result->execute();
$resultSet = $result->get_result();
while ($item = $resultSet->fetch_assoc())
{
$data[] = $item;
}
$result->close();
//echo resultSet you want
var_dump($data);
```
|
12,419,217 |
In my application I have class that is responsible for all database actions. It is called from main class and uses delegates to call methods after action is complete.
Because it is asynchronous I must use invoke on my GUI, so I've created a simple extensions method:
```
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T: Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
```
This works fine when I try to call it on textBox:
```
textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });
```
but when I try to call it on ToolStripStatusLabel or ToolStripProgressBar I get an error:
>
> The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as
> type parameter 'T' in the generic type or method
> 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is
> no implicit reference conversion from
> 'System.Windows.Forms.ToolStripStatusLabel' to
> 'System.Windows.Forms.Control'.
>
>
>
I know that this is probably a simple fix, but I just can handle it :/
|
2012/09/14
|
[
"https://Stackoverflow.com/questions/12419217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/965722/"
] |
This is because ToolStripItem (base for those two causing an error) is a Component and not a Control.
Try calling your extension method on the tool strip that owns them and adjust your delegate
methods.
|
I'd like to add up to the accepted solution. You can get the control from the component by using the GetCurrentParent method of the ToolStripStatusLabel.
Instead of doing `toolStripStatusLabel1.InvokeIfRequired`, do `toolStripStatusLabel1.GetCurrentParent().InvokeIfRequired`
|
12,419,217 |
In my application I have class that is responsible for all database actions. It is called from main class and uses delegates to call methods after action is complete.
Because it is asynchronous I must use invoke on my GUI, so I've created a simple extensions method:
```
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T: Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
```
This works fine when I try to call it on textBox:
```
textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });
```
but when I try to call it on ToolStripStatusLabel or ToolStripProgressBar I get an error:
>
> The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as
> type parameter 'T' in the generic type or method
> 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is
> no implicit reference conversion from
> 'System.Windows.Forms.ToolStripStatusLabel' to
> 'System.Windows.Forms.Control'.
>
>
>
I know that this is probably a simple fix, but I just can handle it :/
|
2012/09/14
|
[
"https://Stackoverflow.com/questions/12419217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/965722/"
] |
This is because ToolStripItem (base for those two causing an error) is a Component and not a Control.
Try calling your extension method on the tool strip that owns them and adjust your delegate
methods.
|
**Extension method using** `GetCurrentParent().InvokeRequired`
```
public static void ToolStripStatusInvokeAction<TControlType>(this TControlType control, Action<TControlType> del)
where TControlType : ToolStripStatusLabel
{
if (control.GetCurrentParent().InvokeRequired)
control.GetCurrentParent().Invoke(new Action(() => del(control)));
else
del(control);
}
```
**Calling the ToolStripStatusInvokeAction Extension:**
```
toolStripAppStatus.ToolStripStatusInvokeAction(t =>
{
t.Text= "it works!";
t.ForeColor = Color.Red;
});
```
|
12,419,217 |
In my application I have class that is responsible for all database actions. It is called from main class and uses delegates to call methods after action is complete.
Because it is asynchronous I must use invoke on my GUI, so I've created a simple extensions method:
```
public static void InvokeIfRequired<T>(this T c, Action<T> action)
where T: Control
{
if (c.InvokeRequired)
{
c.Invoke(new Action(() => action(c)));
}
else
{
action(c);
}
}
```
This works fine when I try to call it on textBox:
```
textBox1.InvokeIfRequired(c => { c.Text = "it works!"; });
```
but when I try to call it on ToolStripStatusLabel or ToolStripProgressBar I get an error:
>
> The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as
> type parameter 'T' in the generic type or method
> 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is
> no implicit reference conversion from
> 'System.Windows.Forms.ToolStripStatusLabel' to
> 'System.Windows.Forms.Control'.
>
>
>
I know that this is probably a simple fix, but I just can handle it :/
|
2012/09/14
|
[
"https://Stackoverflow.com/questions/12419217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/965722/"
] |
I'd like to add up to the accepted solution. You can get the control from the component by using the GetCurrentParent method of the ToolStripStatusLabel.
Instead of doing `toolStripStatusLabel1.InvokeIfRequired`, do `toolStripStatusLabel1.GetCurrentParent().InvokeIfRequired`
|
**Extension method using** `GetCurrentParent().InvokeRequired`
```
public static void ToolStripStatusInvokeAction<TControlType>(this TControlType control, Action<TControlType> del)
where TControlType : ToolStripStatusLabel
{
if (control.GetCurrentParent().InvokeRequired)
control.GetCurrentParent().Invoke(new Action(() => del(control)));
else
del(control);
}
```
**Calling the ToolStripStatusInvokeAction Extension:**
```
toolStripAppStatus.ToolStripStatusInvokeAction(t =>
{
t.Text= "it works!";
t.ForeColor = Color.Red;
});
```
|
63,532,236 |
I am having a situation with `strncmp` function in C, it is returning 0 even when the words do not match, in the example below, I am testing it with the letter 'R' and when running the code it returns 0 even when the compared word in the txt document is 'RUN'. Do you happen to know whether
Am I missing something in the strncmp function or somewhere else in my code?
Thank you for your input.
---
```c
bool lookup(string s);
int main(void) {
char *s;
s = "R";
if (lookup(s)) {
printf("Word found =)\n");
} else {
printf("Word not found =(\n");
}
}
// Looks up word, s, in txt document.
bool lookup(string s)
{
// TODO
char *wordtosearch;
wordtosearch = s;
int lenwordtosearch = strlen(wordtosearch);
char arraywordindic[50];
// Open txt file
FILE *file = fopen("text.txt", "r");
if (file == NULL)
{
printf("Cannot open file, please try again...\n");
return false;
}
while (!feof(file)) {
if (fgets(arraywordindic, 50, file) != NULL) {
char *wordindic;
wordindic = arraywordindic;
int result = strncmp(wordindic, wordtosearch, lenwordtosearch);
if (result == 0) {
printf("%i\n", result);
printf("%s\n", wordindic);
printf("%s\n", wordtosearch);
fclose(file);
return true;
}
}
}
fclose(file);
return false;
}
```
|
2020/08/22
|
[
"https://Stackoverflow.com/questions/63532236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9407139/"
] |
There are (at least) three ways to do this:
First, if it's on your path, you can simply rename it to `ctdir`.
Second, you can create an alias for it in your startup scripts (like `$HOME/.bashrc`):
```
alias ctdir='initialize_directory.sh'
```
Third, you can create a function to do the work (again, defining it in your startup scripts):
```
ctdir() {
initialize_directory.sh
}
```
Just remember to make sure you load up your modified startup scripts after making the changes. New shells should pick the changes up but you may need to re-source it manually from an existing shell (or just exit and restart).
|
Agreed with @paxdiablo, the best way is to create an alias.
Following steps will work in Linux:
1. Naming the alias.
Type the following at the command line:
`alias ctdir='initialize_directory.sh'`
2. Edit bashsrc file.
This file is usually present at your home directory.
Add at the alias mentioned in step 1 at the end of the bashsrc file to make them permanent and reusable in every session.
`vi ~/.bashsrc`
|
823,256 |
I'm trying to setup a sane development environment after joining a new company that has projects running on 3 different PHP versions, without resorting to VM's (like Vagrant) or containers. I really hate those solutions.
Since i'm pretty much a Linux newbie, i have no idea on how to do this properly. I've setup some bash scripts that are aliasing things around and it works, but i doubt that this is the best way of handling things and i'm pretty sure some package manager out there offers a good solution.
I need 3 PHP versions intalled: 5.6, 7.0 and 7.1. What i did was a custom compilation of each version and made a small scripts that aliases my /usr/bin/php to a different folder. I call my script: `select-php 7.1` and it aliases a bunch of stuff to the correct 7.1 folder.
Is there a package manager that helps do this in a better way? I'm pretty sure my solution is going to backfire soon.
|
2016/12/29
|
[
"https://serverfault.com/questions/823256",
"https://serverfault.com",
"https://serverfault.com/users/133672/"
] |
Nowadays we have many kinds of \*brew scripts. You could try `phpbrew` <https://github.com/phpbrew/phpbrew> for different PHP versions.
|
There will be third party packages for various versions of PHP for the common distros. The advantage is other people use these builds and may be able to assist. On Debian, a fairly popular repository is <https://www.dotdeb.org/>
Switching between versions could get tricky, especially around the web server integration. Even if the packages don't flat out conflict, you may have problems running both.
So be ready to spin up VMs or containers with each version. There are many ways to do that. If you don't have an automated way to create a reproducible build environment from a blank host, you probably should be exploring something like this anyway.
|
7,053,293 |
how to load a php file to just display the contents of the file, not executing it?
I want to see the contents on a web browser. But I can't find a way to load without it executing the contents.
thanks
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7053293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820259/"
] |
If you want nice colouring, try [highlight\_file()](http://php.net/manual/en/function.highlight-file.php).
|
A combination of [`fopen`](http://www.php.net/manual/en/function.fopen.php) and [`fpassthru`](http://www.php.net/manual/en/function.fpassthru.php) should do the trick. Don't forget to send appropriate headers first. Alternatively [`readfile`](http://www.php.net/manual/en/function.readfile.php).
|
7,053,293 |
how to load a php file to just display the contents of the file, not executing it?
I want to see the contents on a web browser. But I can't find a way to load without it executing the contents.
thanks
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7053293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820259/"
] |
If you're programming in php in order to view a PHP file, simply load the file into a string, then run it through [htmlentities](http://www.php.net/manual/en/function.htmlentities.php) before displaying it. It will escape all the html special characters and cause it to be displayed literally.
|
A combination of [`fopen`](http://www.php.net/manual/en/function.fopen.php) and [`fpassthru`](http://www.php.net/manual/en/function.fpassthru.php) should do the trick. Don't forget to send appropriate headers first. Alternatively [`readfile`](http://www.php.net/manual/en/function.readfile.php).
|
7,053,293 |
how to load a php file to just display the contents of the file, not executing it?
I want to see the contents on a web browser. But I can't find a way to load without it executing the contents.
thanks
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7053293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820259/"
] |
If you want nice colouring, try [highlight\_file()](http://php.net/manual/en/function.highlight-file.php).
|
If you're programming in php in order to view a PHP file, simply load the file into a string, then run it through [htmlentities](http://www.php.net/manual/en/function.htmlentities.php) before displaying it. It will escape all the html special characters and cause it to be displayed literally.
|
7,053,293 |
how to load a php file to just display the contents of the file, not executing it?
I want to see the contents on a web browser. But I can't find a way to load without it executing the contents.
thanks
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7053293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820259/"
] |
If you want nice colouring, try [highlight\_file()](http://php.net/manual/en/function.highlight-file.php).
|
If its just one large block, you could remove the tags..
otherwise, just rename the file to whatever.php.txt and load it in a browser..
|
7,053,293 |
how to load a php file to just display the contents of the file, not executing it?
I want to see the contents on a web browser. But I can't find a way to load without it executing the contents.
thanks
|
2011/08/13
|
[
"https://Stackoverflow.com/questions/7053293",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/820259/"
] |
If you're programming in php in order to view a PHP file, simply load the file into a string, then run it through [htmlentities](http://www.php.net/manual/en/function.htmlentities.php) before displaying it. It will escape all the html special characters and cause it to be displayed literally.
|
If its just one large block, you could remove the tags..
otherwise, just rename the file to whatever.php.txt and load it in a browser..
|
31,264,963 |
I am creating a Swing based GUI application. I want to run my jar file in ubuntu. And I dont want to install JRE in my system, but I have all jre files in a folder. So if I want to run jar/class file anything, I need to specify this folder path. How to do this?
|
2015/07/07
|
[
"https://Stackoverflow.com/questions/31264963",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5060185/"
] |
If you are using Eclipse you create a new runnable JAR file in the Eclipse workbench:
1. From the menu bar's File menu, select Export.
2. Expand the Java node and select Runnable JAR file. Click Next.
3. In the Opens the Runnable JAR export wizard Runnable JAR File Specification page, select a 'Java Application' launch configuration to use to create a runnable JAR.
4. In the Export destination field, either type or click Browse to select a location for the JAR file.
|
Use
`$jar cvf sample.jar classone.class classtwo.class`
|
48,702,276 |
How can I clear the application context after each test execution, with Junit5 and Spring Boot? I want all beans created in the test to be destroyed after its execution, since I am creating the same beans in multiple tests. I don't want to have one configuration class for all tests, but configuration class per test, as shown bellow.
```
@ExtendWith(SpringExtension.class)
@ContextConfiguration(classes = MyTest.ContextConfiguration.class)
public class MyTest{
...
public static class ContextConfiguration {
// beans defined here...
}
}
```
Putting `@DirtiesContext(classMode = BEFORE_CLASS)` doesn't work with Junit5.
|
2018/02/09
|
[
"https://Stackoverflow.com/questions/48702276",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4826329/"
] |
You have claimed twice that `@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)` does not work; however, the following shows that it works as documented.
```
import javax.annotation.PreDestroy;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInfo;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
class MyTest {
@Test
void test1(TestInfo testInfo) {
System.err.println(testInfo.getDisplayName());
}
@Test
void test2(TestInfo testInfo) {
System.err.println(testInfo.getDisplayName());
}
@Configuration
static class Config {
@Bean
MyComponent myComponent() {
return new MyComponent();
}
}
}
class MyComponent {
@PreDestroy
void destroy() {
System.err.println("Destroying " + this);
}
}
```
Executing the above test class results in output to *STDERR* similar to the following.
```
test1(TestInfo)
Destroying MyComponent@dc9876b
test2(TestInfo)
Destroying MyComponent@30b6ffe0
```
Thus, `@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)` is indeed how you "clear the application context after each test execution".
>
> Putting `@DirtiesContext(classMode = BEFORE_CLASS)` doesn't work with Junit5.
>
>
>
Based on my testing, `classMode = BEFORE_CLASS` works with TestNG, JUnit 4, and JUnit Jupiter (a.k.a., JUnit 5).
So, if that does not work in your test class, that would be a bug which you should [report to the Spring Team](https://jira.spring.io/secure/CreateIssue!default.jspa).
Do you have any example where you can demonstrate that not working?
FYI: using `classMode = BEFORE_CLASS` would only ever make sense if the context had already been created within the currently executing test suite. Otherwise, you are instructing Spring to close and remove an `ApplicationContext` from the cache that does not exist... just before Spring actually creates it.
Regards,
Sam (*author of the Spring TestContext Framework*)
|
According to the [docs](https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/test/annotation/DirtiesContext.html), try `@DirtiesContext(classMode = AFTER_EACH_TEST_METHOD)`
|
61,205,223 |
I have just written this code in which I have a form. You have to write your name, surname and country. You also have to choose your favourite colour. After that, you push a submit button so that you can see the data afterwards. I'm using the GET method with 1 page, but I have to use a second one with the POST method so that each echo is on that second page.
How could I do that? My code is:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Form</title>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<section>
<?php
if (isset($_GET["name"])){
$name = $_GET["name"];
if ($name != ""){
$surname = $_GET["surname"];
$country = $_GET["country"];
$colour = $_GET["colour"];
echo "<p>";
echo "<h2>Data</h2>";
echo $name . " " . $surname . "</br />";
echo $country . "<br />";
echo $colour;
echo "</p>";
}else
echo "<strong>Complete the blank spaces</strong>";
}else{
?>
<h1>Form</h1>
<form class="elegant" method="GET" action="?">
<fieldset>
<legend>Favourite colour</legend>
<div>
<label for="nombre">Name</label>
<input type="text" placeholder="Name" name="name"
id="name" />
</div>
<div>
<label for="surname">Surname</label>
<input type="text" placeholder="Surname" name="surname"
id="surname" size="50" />
</div>
<div>
<label for="country">Country</label>
<input type="text" placeholder="Country" name="country" id="country"
size="10" maxlength="9" />
</div>
<div>
<select name="colour" id="colour">
<option value="yellow" <?php if ($colour == "yellow" ) echo "selected" ?> >yellow</option>
<option value="red" <?php if ($colour == "red" ) echo "selected" ?> >red</option>
</div>
<input class="btn" type="submit" value="Save" />
</fieldset>
</form>
<?php
}
?>
</section>
</body>
</html>
```
I know i have to use a link to that second page, but that's all I know. Thanks in advance!
|
2020/04/14
|
[
"https://Stackoverflow.com/questions/61205223",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13045027/"
] |
Assuming your objects have a getter for the id `getId()`, then you can make use of the [`Comparator.comparing()`](https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#comparing-java.util.function.Function-) helper method, which creates a comparator for the provided lambda:
```
objectList.sort(Comparator.comparing(o -> yourMap.get(o.getId()));
```
This effectively the same as writing your own `Comparator` or writing your own compare method.
|
Something that may look overkilling but it could be more natural to define a new class
```
class IndexedElement implments Comparable<Integer> {
private final int index;
private final YourObject element;
public IndexedElement(int index, YourObject element) {
this.index = index;
this.element = element;
}
@Override
public int compareTo(Integer o) {
return this.getIndex().compareTo(o.getIndex()) ;
}
}
```
storing objects like that in a `TreeSet<IndexedElement>` you can automatically achieve the sorting and retrieving (TreeSet.ceiling(new IndexedElement(yourIndex, null)), just remember to Override the equals/hashCode in IndexedElement)
|
29,728,495 |
Is there a Rubier way to do
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
for empty arrays in Ruby, and empty relations in Rails
|
2015/04/19
|
[
"https://Stackoverflow.com/questions/29728495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972789/"
] |
You would use this for arrays that might be empty or even `nil`:
```
Array(arr).map(&:do_something)
```
For relations in Rails it is just the following, because Rails' relations do not return `nil`:
```
relation.map(&:do_something)
```
|
It's a good practice to avoid negative logic for a condition determination if possible. So instead of
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
you can write
```
if arr.present?
arr.map{|x| x.do_something}
end
```
Inclusion is always a faster operation than exclusion.
|
29,728,495 |
Is there a Rubier way to do
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
for empty arrays in Ruby, and empty relations in Rails
|
2015/04/19
|
[
"https://Stackoverflow.com/questions/29728495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972789/"
] |
You would use this for arrays that might be empty or even `nil`:
```
Array(arr).map(&:do_something)
```
For relations in Rails it is just the following, because Rails' relations do not return `nil`:
```
relation.map(&:do_something)
```
|
So if you have an array which may have nil values you can just use `Array#compact` which return array without nil values.
```
2.2.0 :013 > arr = [1, nil, "2"]
2.2.0 :014 > arr.compact
=> [1, "2"]
```
If the array is empty `#map` method won't have any side effects so you are safe and you don't have to check if array is empty.
|
29,728,495 |
Is there a Rubier way to do
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
for empty arrays in Ruby, and empty relations in Rails
|
2015/04/19
|
[
"https://Stackoverflow.com/questions/29728495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972789/"
] |
You would use this for arrays that might be empty or even `nil`:
```
Array(arr).map(&:do_something)
```
For relations in Rails it is just the following, because Rails' relations do not return `nil`:
```
relation.map(&:do_something)
```
|
You can shorten it to one line using `unless`. Also use [Symbol#to\_proc](https://stackoverflow.com/questions/14881125/what-does-to-proc-method-mean) instead of explicit block:
```
arr.map(&:do_something) unless arr.blank?
```
|
29,728,495 |
Is there a Rubier way to do
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
for empty arrays in Ruby, and empty relations in Rails
|
2015/04/19
|
[
"https://Stackoverflow.com/questions/29728495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972789/"
] |
You can shorten it to one line using `unless`. Also use [Symbol#to\_proc](https://stackoverflow.com/questions/14881125/what-does-to-proc-method-mean) instead of explicit block:
```
arr.map(&:do_something) unless arr.blank?
```
|
It's a good practice to avoid negative logic for a condition determination if possible. So instead of
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
you can write
```
if arr.present?
arr.map{|x| x.do_something}
end
```
Inclusion is always a faster operation than exclusion.
|
29,728,495 |
Is there a Rubier way to do
```
if !arr.blank?
arr.map{|x| x.do_something}
end
```
for empty arrays in Ruby, and empty relations in Rails
|
2015/04/19
|
[
"https://Stackoverflow.com/questions/29728495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/972789/"
] |
You can shorten it to one line using `unless`. Also use [Symbol#to\_proc](https://stackoverflow.com/questions/14881125/what-does-to-proc-method-mean) instead of explicit block:
```
arr.map(&:do_something) unless arr.blank?
```
|
So if you have an array which may have nil values you can just use `Array#compact` which return array without nil values.
```
2.2.0 :013 > arr = [1, nil, "2"]
2.2.0 :014 > arr.compact
=> [1, "2"]
```
If the array is empty `#map` method won't have any side effects so you are safe and you don't have to check if array is empty.
|
7,998,403 |
I have written a C# tool that will launch an application by running a command in the command prompt for me several times, one after the other. The piece of code doing this for me is as follows:
```
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
```
So I have this in a loop and all is good. However each time it executes a new command window is opened, which isnt ideal. Is there a way I can close the command window after the command has executed, or better still, not have the command window open at all? Any help is really appreciated!!
|
2011/11/03
|
[
"https://Stackoverflow.com/questions/7998403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678011/"
] |
Yes, you have to use the `ProcessStartInfo` class for doing this:
```
Process.Start(
new ProcessStartInfo("CMD.exe", strCmdText)
{
CreateNoWindow = true
});
```
|
Use `ProcessStartInfo` to start the process (`Start` has an overload that takes a `ProcessStartInfo`).
Set the following properties:
```
var psi = new ProcessStartInfo("cmd.exe", strCmdText);
psi.CreateNoWindow = true;
psi.UseShellExecute = false;
Process.Start(psi);
```
|
7,998,403 |
I have written a C# tool that will launch an application by running a command in the command prompt for me several times, one after the other. The piece of code doing this for me is as follows:
```
System.Diagnostics.Process.Start("CMD.exe", strCmdText);
```
So I have this in a loop and all is good. However each time it executes a new command window is opened, which isnt ideal. Is there a way I can close the command window after the command has executed, or better still, not have the command window open at all? Any help is really appreciated!!
|
2011/11/03
|
[
"https://Stackoverflow.com/questions/7998403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/678011/"
] |
Yes, you have to use the `ProcessStartInfo` class for doing this:
```
Process.Start(
new ProcessStartInfo("CMD.exe", strCmdText)
{
CreateNoWindow = true
});
```
|
ProcessStartInfo allows you to specify no window.
```
using (var p = new Process())
{
p.StartInfo = new ProcessStartInfo
{
FileName = "CMD.exe",
Arguments = strCmdText,
CreateNoWindow = true,
UseShellExecute = false
};
p.Start();
p.WaitForExit();
p.Close();
}
```
|
11,667,480 |
I am trying to test PBE encryption/decryption. I found that PBE generates same key with different salt and iteration count. Of course, the password used is same.
As what I understand, same password and different salt/iteration should get different keys.
Below is my test code:
```
import java.security.Key;
import java.security.SecureRandom;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
public class PBETest
{
public static void main(String[] args)
throws Exception
{
String algo = "PBEWithSHA1andDESede";
System.out.println("====== " + algo + " ======");
char[] password = "password".toCharArray();
SecureRandom rand = new SecureRandom();
byte[] salt = new byte[32];
rand.nextBytes(salt);
int iterationCount = rand.nextInt(2048);
//encryption key
PBEKeySpec encPBESpec = new PBEKeySpec(password, salt, iterationCount);
SecretKeyFactory encKeyFact = SecretKeyFactory.getInstance(algo);
Key encKey = encKeyFact.generateSecret(encPBESpec);
System.out.println("encryptioin iteration: " + iterationCount);
//decryption key
rand.nextBytes(salt);
iterationCount = rand.nextInt(2048);
PBEKeySpec decPBESpec = new PBEKeySpec(password, salt, iterationCount);
SecretKeyFactory decKeyFact = SecretKeyFactory.getInstance(algo);
Key decKey = decKeyFact.generateSecret(decPBESpec);
System.out.println("decryptioin iteration: " + iterationCount);
System.out.println("encryption key is same as decryption key? " + encKey.equals(decKey));
}
}
```
I am expecting the final output is a `false`.
Did I do anything wrong?
|
2012/07/26
|
[
"https://Stackoverflow.com/questions/11667480",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1554249/"
] |
You got spectacularly lucky, and your random salts and iteration counts just happened to match. Go directly to Las Vegas. Now. ;)
I googled for PBEWithSHA1andDESede and tracked down this example: <http://cryptofreek.org/2010/06/04/encrypting-and-decrypting-files-with-java> wherein he specifies the key alone with `new PBEKeySpec(password)` and creates a separate `PBEParameterSpec` using the salt and iteration count which is then passed to Cipher.init().
So, no, you did nothing wrong, you just stopped before the salt and count got stuffed into the cipher.
|
If you use `PBKDF2WithHmacSHA1` instead of `PBEWithSHA1andDESede` your assumption works as it supports salt. You just need to add a the `keyLength` parameter to `PBEKeySpec`:
```
String algo = "PBKDF2WithHmacSHA1";
```
...
```
PBEKeySpec decPBESpec = new PBEKeySpec( password, salt, iterationCount, 128 );
```
I have run a test and the result is: `false`.
However, note that for encryption and decryption to work properly you need to use the same salt and iteration count when generating the key.
|
69,457,828 |
I'm setting up a multi-language dropdown toggle without server side access. It's for a WordPress site with Twig integrated, so the usual WP niceties for handling things like getting the home and path URLs are not available. With those limitations, jQuery seems to be the most workable solution.
Here's what I have so far - this updates the href attributes in a dropdown menu for toggling between four sites: English (default, blog ID:1), German, French, and Spanish. The script below works well, but I'd like to reduce the repetition if I can. Putting the `.indexOf` items in an array duplicates the 2-letter country string in the URL, which is why the code is in this super repetitive state.
Ideally I'd like to have an if statement that checks for `/de`, `/fr`, and `/es` since those three blocks are nearly identical. Thanks in advance for any pointers.
```js
var langDropPathname = window.location.pathname.slice(3); // cut 2-letter country and slash from path for non-default sites
var langDropPathEN = window.location.pathname; // path for default site
var langDropDE = "/de";
var langDropFR = "/fr";
var langDropES = "/es";
if (window.location.href.indexOf("/de/") > -1) {
$(".langDropEN").attr('href', langDropPathname);
$(".langDropDE").attr('href', langDropDE+langDropPathname);
$(".langDropFR").attr('href', langDropFR+langDropPathname);
$(".langDropES").attr('href', langDropES+langDropPathname);
if ($("body").hasClass("error404")) {
document.location.href=langDropDE;
}
} else if (window.location.href.indexOf("/fr/") > -1) {
$(".langDropEN").attr('href', langDropPathname);
$(".langDropDE").attr('href', langDropDE+langDropPathname);
$(".langDropFR").attr('href', langDropFR+langDropPathname);
$(".langDropES").attr('href', langDropES+langDropPathname);
if ($("body").hasClass("error404")) {
document.location.href=langDropFR;
}
} else if (window.location.href.indexOf("/es/") > -1) {
$(".langDropEN").attr('href', langDropPathname);
$(".langDropDE").attr('href', langDropDE+langDropPathname);
$(".langDropFR").attr('href', langDropFR+langDropPathname);
$(".langDropES").attr('href', langDropES+langDropPathname);
if ($("body").hasClass("error404")) {
document.location.href=langDropES;
}
} else {
$(".langDropEN").attr('href', langDropPathEN);
$(".langDropDE").attr('href', langDropDE+langDropPathEN);
$(".langDropFR").attr('href', langDropFR+langDropPathEN);
$(".langDropES").attr('href', langDropES+langDropPathEN);
}
```
|
2021/10/05
|
[
"https://Stackoverflow.com/questions/69457828",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7823753/"
] |
Simply iterating over an array of `['/de', '/fr', '/es']` looks like it'd do the trick.
```
const langs = ['/de', '/fr', '/es'];
const lang = langs.find(substr => window.location.href.includes(substr));
const suffix = lang ? langDropPathname : langDropPathEN;
$(".langDropEN").attr('href', suffix);
$(".langDropDE").attr('href', langDropDE + suffix);
$(".langDropFR").attr('href', langDropFR + suffix);
$(".langDropES").attr('href', langDropES + suffix);
if ($("body").hasClass("error404") && lang) {
document.location.href = lang.slice(1);
}
```
I don't know the broader context of the code, but it'd be even better if you could put all of the languages together, instead of singling out a few specific ones. Perhaps something like
```
const langs = {
de: <content of langDropDE>
fr: <content of langDropFR>
...
}
```
for all languages, then
```
const langEntry = Object.entries(langs)
.find(entry => window.location.href.includes('/' + entry[0]));
```
and proceed from there, now that you have the matching language string and associaed `langDrop` in the found entry.
|
you can match with a regular Expression
```js
const
langDropPathEN = window.location.pathname // path for default site
, langDropPathname = langDropPathEN.slice(3) // cut 2-letter country and slash from path for non-default sites
, LangDrop = { DE: '/de', FR: '/fr', ES: '/es' }
, LangRegEx = new RegExp('/de/|/fr/|/es/')
;
let lang = window.location.href.match(LangRegEx)
if (!!lang)
{
$(".langDropEN").attr('href', langDropPathname);
$(".langDropDE").attr('href', langDrop.DE +langDropPathname);
$(".langDropFR").attr('href', langDrop.FR +langDropPathname);
$(".langDropES").attr('href', langDrop.ES +langDropPathname);
if ($("body").hasClass("error404"))
document.location.href = lang[0].slice(0,3);
}
else
{
$(".langDropEN").attr('href', langDropPathEN);
$(".langDropDE").attr('href', langDrop.DE +langDropPathEN);
$(".langDropFR").attr('href', langDrop.FR +langDropPathEN);
$(".langDropES").attr('href', langDrop.ES +langDropPathEN);
}
```
|
88,967 |
>
> Lethargic apprentices nesting dreary offices
>
> Foraging puzzles intermittently generally suffices
>
>
>
What is the one-word answer to the riddle above?
---
**HINT 1:**
>
> Convoluted as it is, the riddle is not meaningless and describes the answer.
>
>
>
**HINT 2:**
>
> What could be another "word" for the acrostic clue?
>
>
>
**HINT 3:**
>
> The wordplay tag means a pun is necessary to solve the puzzle.
>
>
>
|
2019/09/11
|
[
"https://puzzling.stackexchange.com/questions/88967",
"https://puzzling.stackexchange.com",
"https://puzzling.stackexchange.com/users/62211/"
] |
Here's a guess:
>
> **BOREDOM**
>
>
>
Because:
>
> This satisfies the acrostic "Land of pigs" -> "boar - dom".
>
>
>
> The riddle itself paints a picture of people who are bored at work/school, occasionally solving puzzles to relieve their boredom.
>
>
>
|
How about:
>
> **GUINEA**
>
>
>
The words of the riddle form:
>
> An acrostic, spelling out **LAND OF PIGS**
>
>
>
I then reason that:
>
> A country (‘land’) whose name might fit this cryptic clue is Guinea, as in ‘Guinea pigs’. Not sure right now how this might relate to the title though…
>
>
>
|
27,623,231 |
Can I replace the text in the Title of `ghci` window (i.e. *PowerShell.exe* or *cmd.exe* window title)?

|
2014/12/23
|
[
"https://Stackoverflow.com/questions/27623231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1306132/"
] |
The same way you execute any shell command - using `:!`.
```
> :!Title NewTitle
```
|
Using `System.Process.callCommand` from the `process` package, you can call the `title` executable:
```
> :m System.Process
> callCommand "title A new title for the console window"
```
|
26,266,279 |
I'm working to use custom checkbox styles with a checkbox which is dynamically generated by javascript for the Google Identity Toolkit. For example, we add this div:
```
<div id="gitkitWidgetDiv"></div>
```
And the Google Identity Toolkit script generates new html for that div.
I need to add a class to the HTML which is added by the javascript without any action by the user and I'm struggling to make it work. For example, here is my code:
```
$("#gitkitWidgetDiv").on('ready', ".gitkit-sign-in-options label", function() {
$(this).addClass('checkbox');
});
```
I've tried switching 'ready' for a few other options and also using the livequery plugin, but nothing is working for me. It works if I use an active event like 'click,' but I can't figure out how to do this when the page loads. Could someone please help? Thanks!
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26266279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234620/"
] |
prepare a SQL file with the `insert`-statements you need and run it in the `BootStrap.groovy`:
```
class BootStrap {
def dataSource
def init = { servletContext ->
Sql sql = new Sql( dataSource )
new File( pathToSql ).eachLine{ sql.executeInsert it }
sql.commit()
sql.close()
}
}
```
is simple enough, isn't it?
|
I would suggest you quite different approach. Create a service called e.g. **BootstrapInitialDataService** with one method called **initData()**. It's a good practice to extract an interface from that class (let's call it **InitialDataService**) so you can easily define different component bean for your development and production environments.
In this initData() method you can simply create all your domain objects, but remember to check first if they already exist in the database. When you do this, inject this service in Bootstrap.groovy and run initData() in the bootstrap's init closure:
```
class Bootstrap {
def initialDataService
def init = {
initialDataService.initData()
}
```
In the resources.groovy file you can explicitly define your initialDataService bean:
```
beans = {
//.... other beans definition goes here
initialDataService(your.package.BootstrapInitialDataService)
}
```
Thanks that when you decide to change your init data bootstrap logic you would simply define a new bean and replace the definition in the resources.groovy - the rest stays the same. You can even use an environment switch to inject different beans in different environments - that's very powerful advantage.
|
26,266,279 |
I'm working to use custom checkbox styles with a checkbox which is dynamically generated by javascript for the Google Identity Toolkit. For example, we add this div:
```
<div id="gitkitWidgetDiv"></div>
```
And the Google Identity Toolkit script generates new html for that div.
I need to add a class to the HTML which is added by the javascript without any action by the user and I'm struggling to make it work. For example, here is my code:
```
$("#gitkitWidgetDiv").on('ready', ".gitkit-sign-in-options label", function() {
$(this).addClass('checkbox');
});
```
I've tried switching 'ready' for a few other options and also using the livequery plugin, but nothing is working for me. It works if I use an active event like 'click,' but I can't figure out how to do this when the page loads. Could someone please help? Thanks!
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26266279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234620/"
] |
prepare a SQL file with the `insert`-statements you need and run it in the `BootStrap.groovy`:
```
class BootStrap {
def dataSource
def init = { servletContext ->
Sql sql = new Sql( dataSource )
new File( pathToSql ).eachLine{ sql.executeInsert it }
sql.commit()
sql.close()
}
}
```
is simple enough, isn't it?
|
You can just add code in BootStrap.groovy under
`{project}/grails-app/init/{project}/BootStrap.groovy`
For example:
```
class BootStrap {
def init = { servletContext ->
// create a driver a save it in db
def user = new User(name: "juan")
driver.save()
}
def destroy = {
}
}
```
|
26,266,279 |
I'm working to use custom checkbox styles with a checkbox which is dynamically generated by javascript for the Google Identity Toolkit. For example, we add this div:
```
<div id="gitkitWidgetDiv"></div>
```
And the Google Identity Toolkit script generates new html for that div.
I need to add a class to the HTML which is added by the javascript without any action by the user and I'm struggling to make it work. For example, here is my code:
```
$("#gitkitWidgetDiv").on('ready', ".gitkit-sign-in-options label", function() {
$(this).addClass('checkbox');
});
```
I've tried switching 'ready' for a few other options and also using the livequery plugin, but nothing is working for me. It works if I use an active event like 'click,' but I can't figure out how to do this when the page loads. Could someone please help? Thanks!
|
2014/10/08
|
[
"https://Stackoverflow.com/questions/26266279",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/234620/"
] |
I would suggest you quite different approach. Create a service called e.g. **BootstrapInitialDataService** with one method called **initData()**. It's a good practice to extract an interface from that class (let's call it **InitialDataService**) so you can easily define different component bean for your development and production environments.
In this initData() method you can simply create all your domain objects, but remember to check first if they already exist in the database. When you do this, inject this service in Bootstrap.groovy and run initData() in the bootstrap's init closure:
```
class Bootstrap {
def initialDataService
def init = {
initialDataService.initData()
}
```
In the resources.groovy file you can explicitly define your initialDataService bean:
```
beans = {
//.... other beans definition goes here
initialDataService(your.package.BootstrapInitialDataService)
}
```
Thanks that when you decide to change your init data bootstrap logic you would simply define a new bean and replace the definition in the resources.groovy - the rest stays the same. You can even use an environment switch to inject different beans in different environments - that's very powerful advantage.
|
You can just add code in BootStrap.groovy under
`{project}/grails-app/init/{project}/BootStrap.groovy`
For example:
```
class BootStrap {
def init = { servletContext ->
// create a driver a save it in db
def user = new User(name: "juan")
driver.save()
}
def destroy = {
}
}
```
|
1,063,795 |
I am trying to install Tensorflow with GPU support on Ubuntu 16.04 64x for an conda environment with Python 3.6.
I tried installing all the [GPU requirements](https://www.tensorflow.org/install/install_sources#common_installation_problems) and then running `pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/linux/gpu/tensorflow_gpu-1.10.0-cp36-cp36m-linux_x86_64.whl` from my conda environment.
However when I open a Python terminal and try `import tensorflow as tf` I get a `ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory`.
This is the state of the requirements:
* NVIDIA driver version: 384.130 (this is the output of `nvidia-smi`)
* CUDA compiler driver: `release 7.5, V7.5.17` (this the output of `nvcc -v`)
* CUDA: Version 9.2.148 (this is the output of `cat /usr/local/cuda/version.txt`). I am really confused because I read somewhere else that the CUDA version and the nvcc version should match.
* cuDNN: I think I have installed it? I downloaded the .deb package and I did `sudo dpkg -i /path/to/deb/file` followed by `sudo apt-get install -f`. But the internet tells me that executing `cat /usr/local/cuda/include/cudnn.h | grep CUDNN_MAJOR -A 2` should give me the cuDNN version and it complains that the file does not exist.
* CUPTI: I ran `export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/usr/local/cuda/extras/CUPTI/lib64` as indicated in the tensorflow requirements guide.
What should I try now?
---
Full error trace:
```
>>> import tensorflow
Traceback (most recent call last):
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/__init__.py", line 22, in <module>
from tensorflow.python import pywrap_tensorflow # pylint: disable=unused-import
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/__init__.py", line 49, in <module>
from tensorflow.python import pywrap_tensorflow
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 74, in <module>
raise ImportError(msg)
ImportError: Traceback (most recent call last):
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow.py", line 58, in <module>
from tensorflow.python.pywrap_tensorflow_internal import *
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 28, in <module>
_pywrap_tensorflow_internal = swig_import_helper()
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/site-packages/tensorflow/python/pywrap_tensorflow_internal.py", line 24, in swig_import_helper
_mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/imp.py", line 243, in load_module
return load_dynamic(name, filename, file)
File "/home/jsevillamol/anaconda3/envs/ctlearn/lib/python3.6/imp.py", line 343, in load_dynamic
return _load(spec)
ImportError: libcublas.so.9.0: cannot open shared object file: No such file or directory
```
|
2018/08/09
|
[
"https://askubuntu.com/questions/1063795",
"https://askubuntu.com",
"https://askubuntu.com/users/522473/"
] |
Cuda 9.0 can be installed with codes on the following tutorial
<https://www.tensorflow.org/install/gpu>
```
# Add NVIDIA package repository
sudo apt-key adv --fetch-keys http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/7fa2af80.pub
wget http://developer.download.nvidia.com/compute/cuda/repos/ubuntu1604/x86_64/cuda-repo-ubuntu1604_9.1.85-1_amd64.deb
sudo apt install ./cuda-repo-ubuntu1604_9.1.85-1_amd64.deb
wget http://developer.download.nvidia.com/compute/machine-learning/repos/ubuntu1604/x86_64/nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
sudo apt install ./nvidia-machine-learning-repo-ubuntu1604_1.0.0-1_amd64.deb
sudo apt update
# Install CUDA and tools. Include optional NCCL 2.x
sudo apt install cuda9.0 cuda-cublas-9-0 cuda-cufft-9-0 cuda-curand-9-0 \
cuda-cusolver-9-0 cuda-cusparse-9-0 libcudnn7=7.2.1.38-1+cuda9.0 \
libnccl2=2.2.13-1+cuda9.0 cuda-command-line-tools-9-0
# Optional: Install the TensorRT runtime (must be after CUDA install)
sudo apt update
sudo apt install libnvinfer4=4.1.2-1+cuda9.0
```
|
Fixed! Turns out that the TF distro installed by default does not support CUDA 9.2. I downgraded to CUDA 9.0 and now it is tentatively working.
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
**I would suggest the following:**
>
> 1. Add a height constraint to your collection view.
> 2. Set its priority to 999.
> 3. Set its constant to any value that makes it reasonably visible on the storyboard.
> 4. Change the bottom equal constraint of the collection view to greater or equal.
> 5. Connect the height constraint to an outlet.
> 6. Every time you reload the data on the collection view do the following:
>
>
>
*You may also want to consider the Inset of the collection view by adding it to the content size.*
**Code Sample:**
```
CGFloat height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
heightConstraint.constant = height
self.view.setNeedsLayout() Or self.view.layoutIfNeeded()
```
**Explanation: Extra, You don't have to read if you understand it. obviously!!**
The UI will try to reflect all the constraints no matter what are their priorities. Since there is a height constraint with lower priority of **(999)**, and a bottom constraint of type greater or equal. whenever, the height constraint constant is set to a value less than the parent view height the collection view will be equal to the given height, achieving both constraints.
But, when the height constraint constant set to a value more than the parent view height both constraints can't be achieved. Therefore, only the constraint with the higher priority will be achieved which is the greater or equal bottom constraint.
The following is just a guess from an experience. So, it achieves one constrant. But, it also tries to make the **error** in the resulted UI for the other un-achieved lower priority constraint **as lowest as possible**. Therefore, the collection view height will be equal to the parent view size.
|
first of all calculate number of cells than multiply it with height of cell and then return height in this method
```
collectionView.frame = CGRectMake (x,y,w,collectionView.collectionViewLayout.collectionViewContentSize.height); //objective c
//[collectionView reloadData];
collectionView.frame = CGRect(x: 0, y: 0, width: width, height: collectionView.collectionViewLayout.collectionViewContentSize.height) // swift
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
This seemed like the simplest solution for me.
```
class SelfSizingCollectionView: UICollectionView {
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
isScrollEnabled = false
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return contentSize
}
}
```
You may not need to override `reloadData`
|
If you set the height constraint of the collection view. Just observe the `contentSize` change in the viewDidLoad and update the constraint.
```
self.contentSizeObservation = collectionView.observe(\.contentSize, options: [.initial, .new]) { [weak self] collectionView, change in
guard let `self` = self else { return }
guard self.collectionView.contentSize != .zero else { return }
self.collectionViewHeightLayoutConstraint.constant = self.collectionView.contentSize.height
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
I ended up, by subclassing the `UICollectionView` and overriding some methods as follows.
* Returning `self.collectionViewLayout.collectionViewContentSize` for `intrinsicContentSize` makes sure, to always have the correct size
* Then just call it whenever it might change (like on `reloadData`)
Code:
```
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return self.collectionViewLayout.collectionViewContentSize
}
```
**But be aware, that you lose "cell re-using", if you display large sets of data, eventhough they don't fit on the screen.**
|
On your `UICollectionView` set your constraints such as `Trailing`, `Leading`, and `Bottom`:
[](https://i.stack.imgur.com/HXJeR.png)
If you look at my height constraint in more detail, as it is purely for storyboard look so I don't get errors, I have it to `Remove at build time`. The real height constraint is set in my code down below.
[](https://i.stack.imgur.com/nLGPO.png)
My code for `DrawerCollectionView`, which is set as the collection view `Custom Class`:
[](https://i.stack.imgur.com/Zt0ND.png)
```
import UIKit
class DrawerCollectionView: UICollectionView {
override func didMoveToSuperview() {
super.didMoveToSuperview()
heightAnchor.constraint(equalToConstant: contentSize.height).isActive = true
}
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
1) Set Fix Height of your CollectionView.
2) Create Outlet of this CollectionView Height Constant.
Like :
>
> IBOutlet NSLayoutConstraint \*constHeight;
>
>
>
3) Add below method in your .m file:
```
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGFloat height = collectionMenu.collectionViewLayout.collectionViewContentSize.height;
constHeight.constant = height;
}
```
|
1. Subclass UICollectionView as follows
2. Delete height constraint if any
3. Turn on Intrinsic Size
-
```
class ContentSizedCollectionView: UICollectionView {
override var contentSize:CGSize {
didSet {
invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
layoutIfNeeded()
return CGSize(width: UIView.noIntrinsicMetric, height: collectionViewLayout.collectionViewContentSize.height)
}
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
I ended up, by subclassing the `UICollectionView` and overriding some methods as follows.
* Returning `self.collectionViewLayout.collectionViewContentSize` for `intrinsicContentSize` makes sure, to always have the correct size
* Then just call it whenever it might change (like on `reloadData`)
Code:
```
override func reloadData() {
super.reloadData()
self.invalidateIntrinsicContentSize()
}
override var intrinsicContentSize: CGSize {
return self.collectionViewLayout.collectionViewContentSize
}
```
**But be aware, that you lose "cell re-using", if you display large sets of data, eventhough they don't fit on the screen.**
|
Do following.
1. first set height constrain for `UICollectionView`
2. here `calendarBaseViewHeight` is `UICollectionView` height Variable
3. call the function after reload the collection view
```
func resizeCollectionViewSize(){
calendarBaseViewHeight.constant = collectionView.contentSize.height
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
You have to set height constraint as equal to content size
```
HeightConstraint.constant = collection.contentSize.height
```
|
I have a multi-line, multi-selection `UICollectionView` subclass where the cells are of fixed height and left-aligned flowing from left to right. It's embedded in a vertical stack view that's inside a vertical scroll view. See the UI component below the label "Property Types".
[](https://i.stack.imgur.com/Hvkb5.jpg)
In order for the collection view to fit the height of its `contentSize`, here's what I had to do (note that this is all within the `UICollectionView` subclass):
1. Give the collection view a non-zero minimum height constraint of priority `999`. Auto-sizing the collection view to its content height simply won't work with zero height.
```
let minimumHeight = heightAnchor.constraint(greaterThanOrEqualToConstant: 1)
minimumHeight.priority = UILayoutPriority(999)
minimumHeight.isActive = true
```
2. Set the collection view's content hugging priority to `.required` for the vertical axis.
```
setContentHuggingPriority(.required, for: .vertical)
```
3. Calling `reloadData()` is followed by the following calls:
```
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
```
For example, I have a `setItems()` function in my subclass:
```
func setItems(_ items: [Item]) {
self.items = items
selectedIndices = []
reloadData()
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
```
4. Override `contentSize` and `intrinsicContentSize` as follows:
```
override var intrinsicContentSize: CGSize {
return contentSize
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
In Swift 5 and Xcode 10.2.1
My CollectionView name is **myCollectionView**
1. Fix height for your CollectionView
2. Create Outlet for your CollectionViewHeight
```
IBOutlet weak var myCollectionViewHeight: NSLayoutConstraint!
```
3. Use below code
```
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
myCollectionViewHeight.constant = height
self.view.layoutIfNeeded()
}
```
Dynamic width for cell based on text content...
[Dynamic cell width of UICollectionView depending on label width](https://stackoverflow.com/questions/23134986/dynamic-cell-width-of-uicollectionview-depending-on-label-width/68907152#68907152)
|
Do following.
1. first set height constrain for `UICollectionView`
2. here `calendarBaseViewHeight` is `UICollectionView` height Variable
3. call the function after reload the collection view
```
func resizeCollectionViewSize(){
calendarBaseViewHeight.constant = collectionView.contentSize.height
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
1) Set Fix Height of your CollectionView.
2) Create Outlet of this CollectionView Height Constant.
Like :
>
> IBOutlet NSLayoutConstraint \*constHeight;
>
>
>
3) Add below method in your .m file:
```
- (void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
CGFloat height = collectionMenu.collectionViewLayout.collectionViewContentSize.height;
constHeight.constant = height;
}
```
|
I was using a UICollectionView in UITableView cell. For me, the following solution worked.
In parent view of collection view, I updated the height constraint in `layoutSubviews` method like this
```
override func layoutSubviews() {
heightConstraint.constant = myCollectionView.collectionViewLayout.collectionViewContentSize.height
}
```
and then in `cellForRowAtIndexpath`, just before returning the cell, call this
```
cell.layoutIfNeeded()
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
I have a multi-line, multi-selection `UICollectionView` subclass where the cells are of fixed height and left-aligned flowing from left to right. It's embedded in a vertical stack view that's inside a vertical scroll view. See the UI component below the label "Property Types".
[](https://i.stack.imgur.com/Hvkb5.jpg)
In order for the collection view to fit the height of its `contentSize`, here's what I had to do (note that this is all within the `UICollectionView` subclass):
1. Give the collection view a non-zero minimum height constraint of priority `999`. Auto-sizing the collection view to its content height simply won't work with zero height.
```
let minimumHeight = heightAnchor.constraint(greaterThanOrEqualToConstant: 1)
minimumHeight.priority = UILayoutPriority(999)
minimumHeight.isActive = true
```
2. Set the collection view's content hugging priority to `.required` for the vertical axis.
```
setContentHuggingPriority(.required, for: .vertical)
```
3. Calling `reloadData()` is followed by the following calls:
```
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
```
For example, I have a `setItems()` function in my subclass:
```
func setItems(_ items: [Item]) {
self.items = items
selectedIndices = []
reloadData()
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
```
4. Override `contentSize` and `intrinsicContentSize` as follows:
```
override var intrinsicContentSize: CGSize {
return contentSize
}
override var contentSize: CGSize {
didSet {
invalidateIntrinsicContentSize()
setNeedsLayout()
layoutIfNeeded()
}
}
```
|
**Adjusting height of UICollectionView to the height of it's content size**
SWIFT 5
```
final class MyViewController: UIViewController {
// it's important to declare layout as separate constant due to late update in viewDidLayoutSubviews()
private let layout = UICollectionViewFlowLayout()
private lazy var collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupCollectionViewConstraints()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
updateFlowLayout()
}
private func setupCollectionView() {
view.addSubview(collectionView)
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "UICollectionViewCell")
collectionView.dataSource = self
}
private func setupCollectionViewConstraints() {
// your collectionView constraints setup
}
private func updateFlowLayout() {
let height = collectionView.collectionViewLayout.collectionViewContentSize.height
layout.itemSize = CGSize(width: view.frame.width, height: height)
layout.scrollDirection = .horizontal
layout.minimumInteritemSpacing = .zero
layout.minimumLineSpacing = .zero
layout.sectionInset = UIEdgeInsets.zero
}
}
extension MyViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {...}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {...}
}
```
|
42,437,966 |
I would like the UICollectionView (The red one) to shrink to the height of the content size in this case UICollectionViewCells(the yellow ones) because there is a lot of empty space. What I tried is to use:
```
override func layoutSubviews() {
super.layoutSubviews()
if !__CGSizeEqualToSize(bounds.size, self.intrinsicContentSize) {
self.invalidateIntrinsicContentSize()
}
}
override var intrinsicContentSize: CGSize {
return self.collection.contentSize
}
```
but `return self.collection.contentSize` always return (width, 0)
and for this reason it shrinks too much to value of height 30 (The value which I set in the XIB file for the height, although I have constaint >= 30).
[](https://i.stack.imgur.com/bJZra.png)
|
2017/02/24
|
[
"https://Stackoverflow.com/questions/42437966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4528594/"
] |
**I would suggest the following:**
>
> 1. Add a height constraint to your collection view.
> 2. Set its priority to 999.
> 3. Set its constant to any value that makes it reasonably visible on the storyboard.
> 4. Change the bottom equal constraint of the collection view to greater or equal.
> 5. Connect the height constraint to an outlet.
> 6. Every time you reload the data on the collection view do the following:
>
>
>
*You may also want to consider the Inset of the collection view by adding it to the content size.*
**Code Sample:**
```
CGFloat height = myCollectionView.collectionViewLayout.collectionViewContentSize.height
heightConstraint.constant = height
self.view.setNeedsLayout() Or self.view.layoutIfNeeded()
```
**Explanation: Extra, You don't have to read if you understand it. obviously!!**
The UI will try to reflect all the constraints no matter what are their priorities. Since there is a height constraint with lower priority of **(999)**, and a bottom constraint of type greater or equal. whenever, the height constraint constant is set to a value less than the parent view height the collection view will be equal to the given height, achieving both constraints.
But, when the height constraint constant set to a value more than the parent view height both constraints can't be achieved. Therefore, only the constraint with the higher priority will be achieved which is the greater or equal bottom constraint.
The following is just a guess from an experience. So, it achieves one constrant. But, it also tries to make the **error** in the resulted UI for the other un-achieved lower priority constraint **as lowest as possible**. Therefore, the collection view height will be equal to the parent view size.
|
Do following.
1. first set height constrain for `UICollectionView`
2. here `calendarBaseViewHeight` is `UICollectionView` height Variable
3. call the function after reload the collection view
```
func resizeCollectionViewSize(){
calendarBaseViewHeight.constant = collectionView.contentSize.height
}
```
|
27,733,180 |
I want to parse duration strings like
*1h30m40s* or *56m12s*
in PHP. I try the following the Regexp
```
^(\d+)h(\d+)m(\d+)s$
```
But it didn't work with strings like *56m12s*.
How can i make the the hours optional?
|
2015/01/01
|
[
"https://Stackoverflow.com/questions/27733180",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4130452/"
] |
You can place a [optional](http://www.regular-expressions.info/optional.html) non-capturing group around the given subpattern.
```
^(?:(\d+)h)?(\d+)m(\d+)s$
```
If you are just wanting to validate these strings, you can remove the unnecessary capture groups.
```
^(?:\d+h)?\d+m\d+s$
```
|
Use the `?` for zero or one occurrence. No need for parentheses in the other parts of the regex:
```
^(\d+h)?\d+m\d+s$
```
|
15,767,695 |
If I have the following...
```
List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");
List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");
```
How can I know if listA has everything listB has?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15767695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040634/"
] |
you could do it the raw (slow) way to make sure
```
bool contains_all = true;
foreach(String s in listA) {
if(!listB.Contains(s)) {
contains_all = false;
break;
}
}
```
although this does perform an exhaustive search on every element within the array
|
Try this:
```
bool result = listB.Intersect(listA).Count() == listB.Count;
```
And also this:
```
bool result2 = listB.Select(input => !listA.Contains(input)).Count() > 0;
```
|
15,767,695 |
If I have the following...
```
List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");
List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");
```
How can I know if listA has everything listB has?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15767695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040634/"
] |
Using [`Enumerable.Except`](http://msdn.microsoft.com/en-us/library/bb300779.aspx)
```
bool allBinA = !listB.Except(listA).Any();
```
[**Demo**](http://ideone.com/ZtNcDi)
|
Try this:
```
bool result = listB.Intersect(listA).Count() == listB.Count;
```
And also this:
```
bool result2 = listB.Select(input => !listA.Contains(input)).Count() > 0;
```
|
15,767,695 |
If I have the following...
```
List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");
List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");
```
How can I know if listA has everything listB has?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15767695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040634/"
] |
Using [`Enumerable.Except`](http://msdn.microsoft.com/en-us/library/bb300779.aspx)
```
bool allBinA = !listB.Except(listA).Any();
```
[**Demo**](http://ideone.com/ZtNcDi)
|
you could do it the raw (slow) way to make sure
```
bool contains_all = true;
foreach(String s in listA) {
if(!listB.Contains(s)) {
contains_all = false;
break;
}
}
```
although this does perform an exhaustive search on every element within the array
|
15,767,695 |
If I have the following...
```
List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");
List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");
```
How can I know if listA has everything listB has?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15767695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040634/"
] |
you could do it the raw (slow) way to make sure
```
bool contains_all = true;
foreach(String s in listA) {
if(!listB.Contains(s)) {
contains_all = false;
break;
}
}
```
although this does perform an exhaustive search on every element within the array
|
```
bool result = false;
if (listB.Count>listA.Count) result = listB.Intersect(listA).Count() == listB.Count;
else result = listA.Intersect(listB).Count() == listA.Count;
```
|
15,767,695 |
If I have the following...
```
List<string> listA = new List<string>();
listA.Add("a");
listA.Add("b");
listA.Add("c");
listA.Add("d");
List<string> listB = new List<string>();
listB.Add("b");
listB.Add("d");
```
How can I know if listA has everything listB has?
|
2013/04/02
|
[
"https://Stackoverflow.com/questions/15767695",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1040634/"
] |
Using [`Enumerable.Except`](http://msdn.microsoft.com/en-us/library/bb300779.aspx)
```
bool allBinA = !listB.Except(listA).Any();
```
[**Demo**](http://ideone.com/ZtNcDi)
|
```
bool result = false;
if (listB.Count>listA.Count) result = listB.Intersect(listA).Count() == listB.Count;
else result = listA.Intersect(listB).Count() == listA.Count;
```
|
52,101,758 |
In this example I'm iterating over all possible variations of a mask, which I store as a list of booleans
```
Nmax = 32
for num in range (2**Nmax):
bool_list = [bool(num & (1<<n)) for n in range(Nmax)]
# other stuff
```
However, the operation to generate `bool_list` is a bit of a bottleneck in the code - the rest is rather fast matrix multiplication. Is there a faster way to increment the number stored in `bool_list` than I'm doing?
|
2018/08/30
|
[
"https://Stackoverflow.com/questions/52101758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2584425/"
] |
You're just taking all combinations of (False, True) `Nmax` times. Hence,
```
from itertools
print(list(itertools.product(*[(False, True)]*Nmax)))
```
will display all the masks.
If you want to use it while iterating,
```
Nmax = 32
masks = itertools.product(*[(False, True)]*Nmax)
for mask in masks:
# Do stuff
```
Note that `mask` will be a tuple rather than a list.
|
For one, I think you can precompute the shifts:
```
Nmax = 32
shifts = [(1 << n) for n in range(Nmax)]
for num in range(2**Nmax):
bool_list = [bool(num & shift) for shift in shifts]
```
|
41,641,257 |
I want to pass value of a input to a parent component. Currently I'm sending the whole input's `ElementRef`from my child component. Is there an elegant way to doing this? I mean, I need to send only one number, not a whole reference.
**Child Component:**
```
import { Component, ViewChild } from '@angular/core';
@Component({
selector: 'app-action-dialog-content',
template: `
<md-input-container>
<input #amount md-input placeholder="Amount">
<span md-suffix>€</span>
</md-input-container>
`
})
export class ActionDialogContentComponent {
@ViewChild('amount') amount;
}
```
**Parent Component:**
```
import { Component, ViewChild } from '@angular/core';
import { ActionDialogContentComponent } from './../action-dialog-content/action-dialog-content.component';
@Component({
selector: 'app-action-dialog',
template: `
<app-action-dialog-content></app-action-dialog-content>
<md-dialog-actions>
<button md-raised-button (click)="sendData()">ADD</button>
</md-dialog-actions>
`
})
export class ActionDialogComponent {
@ViewChild(ActionDialogContentComponent) amountInput: ActionDialogContentComponent;
sendData() {
console.log(this.amountInput.amount.nativeElement.value);
}
}
```
|
2017/01/13
|
[
"https://Stackoverflow.com/questions/41641257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4661692/"
] |
You can use EventEmitter and Output from angular/core to emit data from the child component to the parent, which the parent component can then handle through event binding. See [child to parent component interaction](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent) in the Angular 2 guides.
From your example:
Child:
```
export class ActionDialogContentComponent {
amount: number;
@Output() amountChanged: new EventEmitter<number>();
changeAmount() { //Trigger this call from the child component's template
this.amountChanged.emit(this.amount);
}
}
```
Parent (note that the html event you are binding to matches the @Output property from the child component):
```
@Component({
selector: 'app-action-dialog',
template: `
<app-action-dialog-component (amountChanged)="onAmountChanged($event)"></app-action-dialog-component>
<md-dialog-actions>
<button md-raised-button (click)="sendData()">ADD</button>
</md-dialog-actions>
`
})
export class ActionDialogComponent {
onAmountChanged(amount: number) {
// do what you want with new value
}
}
```
|
you can use [EventEmitter](https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#child-to-parent) to do this code is from the link shared so it can be easily reference please check this [link](https://angular.io/docs/ts/latest/cookbook/component-communication.html#) for more detail
>
> **Child Component Code**
>
>
>
```
import { Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'my-voter',
template: `
<h4>{{name}}</h4>
<button (click)="vote(true)" [disabled]="voted">Agree</button>
<button (click)="vote(false)" [disabled]="voted">Disagree</button>
`
})
export class VoterComponent {
@Input() name: string;
@Output() onVoted = new EventEmitter<boolean>();
voted = false;
vote(agreed: boolean) {
this.onVoted.emit(agreed);
this.voted = true;
}
}
```
>
> **Parent Component Code**
>
>
>
```
import { Component } from '@angular/core';
@Component({
selector: 'vote-taker',
template: `
<h2>Should mankind colonize the Universe?</h2>
<h3>Agree: {{agreed}}, Disagree: {{disagreed}}</h3>
<my-voter *ngFor="let voter of voters"
[name]="voter"
(onVoted)="onVoted($event)">
</my-voter>
`
})
export class VoteTakerComponent {
agreed = 0;
disagreed = 0;
voters = ['Mr. IQ', 'Ms. Universe', 'Bombasto'];
onVoted(agreed: boolean) {
agreed ? this.agreed++ : this.disagreed++;
}
}
```
|
62,015,904 |
I wonder if there is a way to access object properties as keys returned by asyncData()?
```
data() {
return {
bookmark_btn: {
status: null,
loading: false
}
}
}
```
I tried access data object properties like below but didn't work.
```
async asyncData(){
let activity = await axios.get('data.json')
return { bookmark_btn.status: activity.status}
}
```
|
2020/05/26
|
[
"https://Stackoverflow.com/questions/62015904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Use new fetch method instead of asyncData present in **Nuxt >= 2.12** . this fetch method can have data properties.
```
async fetch() {
let activity = await axios.get('data.json')
this.$set(this.bookmark_btn, 'status', activity.status)
}
```
Check out more in official docs <https://nuxtjs.org/api/pages-fetch/>
Or to use old asyncData, remove data() from component as whatever asyncData will return, will append in data(). So you can try out this
```
async asyncData() {
let activity = await axios.get("data.json")
return {
bookmark_btn:{
status: activity.status,
loading: false
}
}
}
```
|
As mentioned before, because `asyncData` is a server rendered method you can't directly access your components `data`.
Previous solution works but I don't think it's how things are intended to work with Nuxt and it's complicated (using a 3rd party lib Vuex and messing around context object).
According to the [API](https://nuxtjs.org/guide/async-data), `asyncData` will be merged into your `data` after loading the client side, which means you will have access to the returning value object of your **page**.
This mean you can use it directly to change the state of your page when the server side finishes loading so you either use the reactivity of vue and use it directly or you use the value within the `mounted` property of your **page** which is the solution for your use case.
|
62,015,904 |
I wonder if there is a way to access object properties as keys returned by asyncData()?
```
data() {
return {
bookmark_btn: {
status: null,
loading: false
}
}
}
```
I tried access data object properties like below but didn't work.
```
async asyncData(){
let activity = await axios.get('data.json')
return { bookmark_btn.status: activity.status}
}
```
|
2020/05/26
|
[
"https://Stackoverflow.com/questions/62015904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
if you put data in store can you easily git this data to asyncData function
```js
export default {
state: () => ({
posts: [],
selectedPost: {},
page:3
}),
mutations: {
updatePosts(state, posts){
state.posts = posts;
},
updateSelectedPost(state, post){
state.selectedPost = post;
}
}
}
```
that was store file
```js
asyncData({$axios , store } ){
return $axios.$get(`http://localhost:3001/data?_page=${store.state.page}&_limit=20`)
.then( res =>{
store.commit("updatePosts", res);
})
},
```
that was index.vue file
|
As mentioned before, because `asyncData` is a server rendered method you can't directly access your components `data`.
Previous solution works but I don't think it's how things are intended to work with Nuxt and it's complicated (using a 3rd party lib Vuex and messing around context object).
According to the [API](https://nuxtjs.org/guide/async-data), `asyncData` will be merged into your `data` after loading the client side, which means you will have access to the returning value object of your **page**.
This mean you can use it directly to change the state of your page when the server side finishes loading so you either use the reactivity of vue and use it directly or you use the value within the `mounted` property of your **page** which is the solution for your use case.
|
52,488,834 |
I have a table in the code to print, which looks like this:

When I tried to print the table, it's print format looks like this:

I need to change the font size of the text in the print view, and also alter the column size in the print view. Also, if I can remove the border in the print view of the web table.
I have used javascript for printing the table. I have made use of the table ID.
```
<script type="text/javascript">
function PrintPage()
{
var TableToPrint = document.getElementById('thisIDisforprinting2');
newWin = window.open("");
newWin.document.write(TableToPrint.outerHTML);
newWin.print();
newWin.close();
}
</script>
```
|
2018/09/25
|
[
"https://Stackoverflow.com/questions/52488834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9186177/"
] |
you can add a css tag using document.write and style the table as you want using the "print" media query.
function PrintPage() {
```
var TableToPrint = document.getElementById('thisIDisforprinting2');
newWin = window.open("");
newWin.document.write(TableToPrint.outerHTML);
newWin.document.write('<style type="text/css"> @media print { #thisIDisforprinting2 { font-size: 24px; } }</style>');
newWin.print();
newWin.close();
}
```
Below a version that set the heigh of the columns and remove the borders
```
newWin.document.write('<style type="text/css"> @media print { #thisIDisforprinting2 { font-size: 24px; border: none; } #thisIDisforprinting2 td { height: 150px; border: none; } } </style>');
```
|
It looks like your Web page may use a width that exceeds the width limits for a printed page. You could try printing the page using the horizontal layout.
|
30,531,895 |
I'm trying to write a version of my C program in Ada. My C function call looks like this:
```c
void convert(const void* in, void* out){
MyType* convertedIn = (MyType*)in;
MyType* convertedOut = (MyType*)out;
//Assignments and operations to translate values across
//Example
convertedOut->meters = convertedIn->feet * 0.3048;
}
```
After searching, I was unable to find anything out there about type casting or any form of Object class or void pointer object for Ada. How would I implement a function like this in Ada?
If I can't implement the function in Ada, how would I wrap the c function with Ada?
I'm using Ada95
|
2015/05/29
|
[
"https://Stackoverflow.com/questions/30531895",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1189943/"
] |
```ada
type Example is tagged null record;
procedure Convert (From : in Example'Class;
To : out Example'Class) is
begin
null; -- Implement conversion here
end Convert;
```
|
I managed to get what I needed using System.Address and Ada.Unchecked\_Conversion. Below is my code:
```ada
with MyPackage;
type MyTypePtr is access MyType;
procedure Convert (From : in System.Address;
To : out System.Address) is
function ConvertAddressToMyType is new Ada.Unchecked_Conversion(
Source => System.Address;
Target => MyTypePtr);
begin
null; -- Implement conversion here
end Convert;
```
|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
Try this:
```
create table tbl1(id int primary key, dt datetime default current_timestamp);
```
Background:
>
> The DEFAULT constraint specifies a
> default value to use when doing an
> INSERT. The value may be NULL, a
> string constant, a number, or a
> constant expression enclosed in
> parentheses. The default value may
> also be one of the special
> case-independant keywords
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP. If the value is
> NULL, a string constant or number, it
> is inserted into the column whenever
> an INSERT statement that does not
> specify a value for the column is
> executed. If the value is
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP, then the current
> UTC date and/or time is inserted into
> the columns. For CURRENT\_TIME, the
> format is HH:MM:SS. For CURRENT\_DATE,
> YYYY-MM-DD. The format for
> CURRENT\_TIMESTAMP is "YYYY-MM-DD
> HH:MM:SS".
>
>
>
From <http://www.sqlite.org/lang_createtable.html>
|
```
... default (datetime(current_timestamp))
```
The expression following `default` must be in parentheses. This form is useful if you want to perform date arithmetic using [SQLite date and time functions or modifiers](http://www.sqlite.org/lang_datefunc.html).
|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
Try this:
```
create table tbl1(id int primary key, dt datetime default current_timestamp);
```
Background:
>
> The DEFAULT constraint specifies a
> default value to use when doing an
> INSERT. The value may be NULL, a
> string constant, a number, or a
> constant expression enclosed in
> parentheses. The default value may
> also be one of the special
> case-independant keywords
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP. If the value is
> NULL, a string constant or number, it
> is inserted into the column whenever
> an INSERT statement that does not
> specify a value for the column is
> executed. If the value is
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP, then the current
> UTC date and/or time is inserted into
> the columns. For CURRENT\_TIME, the
> format is HH:MM:SS. For CURRENT\_DATE,
> YYYY-MM-DD. The format for
> CURRENT\_TIMESTAMP is "YYYY-MM-DD
> HH:MM:SS".
>
>
>
From <http://www.sqlite.org/lang_createtable.html>
|
`CURRENT_TIMESTAMP` is a literal-value just like `'mystring'`
**column-constraint:**

**literal-value:**

|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
Try this:
```
create table tbl1(id int primary key, dt datetime default current_timestamp);
```
Background:
>
> The DEFAULT constraint specifies a
> default value to use when doing an
> INSERT. The value may be NULL, a
> string constant, a number, or a
> constant expression enclosed in
> parentheses. The default value may
> also be one of the special
> case-independant keywords
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP. If the value is
> NULL, a string constant or number, it
> is inserted into the column whenever
> an INSERT statement that does not
> specify a value for the column is
> executed. If the value is
> CURRENT\_TIME, CURRENT\_DATE or
> CURRENT\_TIMESTAMP, then the current
> UTC date and/or time is inserted into
> the columns. For CURRENT\_TIME, the
> format is HH:MM:SS. For CURRENT\_DATE,
> YYYY-MM-DD. The format for
> CURRENT\_TIMESTAMP is "YYYY-MM-DD
> HH:MM:SS".
>
>
>
From <http://www.sqlite.org/lang_createtable.html>
|
you can use the following query for using current date value in your table
```
create table tablename (date_field_name Created_on default CURRENT_DATE);
```
|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
```
... default (datetime(current_timestamp))
```
The expression following `default` must be in parentheses. This form is useful if you want to perform date arithmetic using [SQLite date and time functions or modifiers](http://www.sqlite.org/lang_datefunc.html).
|
`CURRENT_TIMESTAMP` is a literal-value just like `'mystring'`
**column-constraint:**

**literal-value:**

|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
```
... default (datetime(current_timestamp))
```
The expression following `default` must be in parentheses. This form is useful if you want to perform date arithmetic using [SQLite date and time functions or modifiers](http://www.sqlite.org/lang_datefunc.html).
|
you can use the following query for using current date value in your table
```
create table tablename (date_field_name Created_on default CURRENT_DATE);
```
|
2,614,496 |
I have the following table:
```
create table ARDebitDetail(ID_ARDebitDetail int identity,
ID_Hearing int, ID_AdvancedRatePlan int)
```
I am trying to get the latest ID\_AdvancedRatePlan based on a ID\_Hearing. By latest I mean with the largest ID\_ARDebitDetail. I have this query and it works fine.
```
select ID_AdvancedRatePlan
from ARDebitDetails
where ID_Hearing = 135878
and ID_ARDebitDetail =
( select max(ID_ARDebitDetail)
from ARDebitDetails
where ID_AdvancedRatePlan > 0 and ID_Hearing = 135878
)
```
However, it just looks ugly and smells bad. Is there a way to rewrite it in a more concise manner?
|
2010/04/10
|
[
"https://Stackoverflow.com/questions/2614496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9382/"
] |
`CURRENT_TIMESTAMP` is a literal-value just like `'mystring'`
**column-constraint:**

**literal-value:**

|
you can use the following query for using current date value in your table
```
create table tablename (date_field_name Created_on default CURRENT_DATE);
```
|
57,756,217 |
Is it possible to "fail" the release if there are nugget packages in pre-release versions?
Maybe there is a task already for this in Azure DevOps, or maybe there's a way to do it with Powershell?
|
2019/09/02
|
[
"https://Stackoverflow.com/questions/57756217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6950766/"
] |
You can read the `.csproj` file with PowerShell and check if pre-release exist, if yes make an error:
```
[xml]$csproj = Get-Content path/to/csproj/file # e.g. $(Agent.ReleaseDirectory)/myproject/myproject.csproj
$versions = $csproj.Projects.ItemGroup.PackageReference.Version
$versions.ForEach({
# Pre-releases are with '-' symbol, e.g. 1.0.0-beta
if($_ -match "(?<number>\d-)")
{
Write-Error "Pre-release exist: $_"
}
})
```
|
A solution (if you want to take packets from SLN file) for this can be the following:
```
Get-Content .\SolutionName.sln |
where { $_ -match "Project.+, ""(.+)""," } |
foreach { $matches[1] } |
% { Get-Content $_ -ErrorAction SilentlyContinue |
Find "<PackageReference Include" } |
Sort-Object -Unique |
% { if($_ -match "-test") { Write-Host "You're using a PreRelease Version for the following Package $($_)"} }
```
Change **SolutionName** with the name of your solution.
Change **-test** with the suffix of your prerelease package(in my case it was Version="4.1.2-test").
Or if you want to take nugets from **csproj** files recursively
```
get-childitem "$(get-location)" -recurse |
where {$_.extension -eq ".csproj"}|
% { Get-Content $_.FullName -ErrorAction SilentlyContinue |
Find "<PackageReference Include" } |
Sort-Object -Unique |
% { if($_ -match "-test") { Write-Error "You're using a PreRelease Version for the following Package $($_)"} }
```
Again, change the **-test** with what you need.
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
This code working for me.
```
applicationVariants.all { variant ->
variant.outputs.each { output ->
def project = "Your App Name"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType = variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date();
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
```
|
I also add a formatted date to my build. In first place I used some kind of "now" with `new Date()`, but this leads to trouble when starting the build with Android Studio, like in one of the comments above. I decided to use the timestamp of the latest commit. I found some inspiration here: <https://jdpgrailsdev.github.io/blog/2014/10/14/spring_boot_gradle_git_info.html>
Adding the timestamp is handled like below:
```
def getLatestCommitTimeStamp() {
def revision = 'git rev-list --max-count 1 --timestamp HEAD'.execute().text.trim()
def gitCommitMillis = java.util.concurrent.TimeUnit.SECONDS.toMillis(revision.split(' ').first() as long)
return new Date(gitCommitMillis).format("_HH.mm.ss_dd-MM-yyyy", TimeZone.getTimeZone('Europe/Berlin'))
}
```
My renaming part looks like this:
```
android.applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
def lastCommitFormattedDate = getLatestCommitTimeStamp()
variant.outputs.each { output ->
def alignedOutputFile = output.outputFile
def unalignedOutputFile = output.packageApplication.outputFile
// Customise APK filenames (to include build version)
if (variant.buildType.zipAlignEnabled) {
// normal APK
output.outputFile = new File(alignedOutputFile.parent, alignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
// 'unaligned' APK
output.packageApplication.outputFile = new File(unalignedOutputFile.parent, unalignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
This code working for me.
```
applicationVariants.all { variant ->
variant.outputs.each { output ->
def project = "Your App Name"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType = variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date();
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
```
|
This is mine hope to help you
```
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(
(String) file.parent,
(String) file.name.replace(
file.name,
// alter this string to change output file name
"APigLive_Android_" + variant.name + "_" + variant.versionName + "_" + releaseTime() + ".apk"
)
)
}
}
def releaseTime(){
return new Date().format("MM:dd:HH:mm", TimeZone.getTimeZone("GMT"))
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
I'm assuming that you want it in the format you specified, so here's one possible solution.
In your gradle file you can define a new function to get the date time string like you desire:
```
import java.text.DateFormat
import java.text.SimpleDateFormat
def getDateTime() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
return df.format(new Date());
}
```
Then for all variants you can simply run this:
```
android {
//...
buildTypes {
//...
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + getDateTime() + ".apk"))
}
}
}
}
```
Note that this doesn't really output the apk name like you posted, but I guess it's enough to help you out.
|
I also add a formatted date to my build. In first place I used some kind of "now" with `new Date()`, but this leads to trouble when starting the build with Android Studio, like in one of the comments above. I decided to use the timestamp of the latest commit. I found some inspiration here: <https://jdpgrailsdev.github.io/blog/2014/10/14/spring_boot_gradle_git_info.html>
Adding the timestamp is handled like below:
```
def getLatestCommitTimeStamp() {
def revision = 'git rev-list --max-count 1 --timestamp HEAD'.execute().text.trim()
def gitCommitMillis = java.util.concurrent.TimeUnit.SECONDS.toMillis(revision.split(' ').first() as long)
return new Date(gitCommitMillis).format("_HH.mm.ss_dd-MM-yyyy", TimeZone.getTimeZone('Europe/Berlin'))
}
```
My renaming part looks like this:
```
android.applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
def lastCommitFormattedDate = getLatestCommitTimeStamp()
variant.outputs.each { output ->
def alignedOutputFile = output.outputFile
def unalignedOutputFile = output.packageApplication.outputFile
// Customise APK filenames (to include build version)
if (variant.buildType.zipAlignEnabled) {
// normal APK
output.outputFile = new File(alignedOutputFile.parent, alignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
// 'unaligned' APK
output.packageApplication.outputFile = new File(unalignedOutputFile.parent, unalignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
I'm assuming that you want it in the format you specified, so here's one possible solution.
In your gradle file you can define a new function to get the date time string like you desire:
```
import java.text.DateFormat
import java.text.SimpleDateFormat
def getDateTime() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
return df.format(new Date());
}
```
Then for all variants you can simply run this:
```
android {
//...
buildTypes {
//...
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + getDateTime() + ".apk"))
}
}
}
}
```
Note that this doesn't really output the apk name like you posted, but I guess it's enough to help you out.
|
You can just add the code below inside the `defaultConfig` section located in `android` section.
```
setProperty("archivesBaseName", "yourData-$versionName " + (new Date().format("HH-mm-ss")))
```
Inspired by [enter link description here](https://stackoverflow.com/a/28992851/6940373)
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
This code working for me.
```
applicationVariants.all { variant ->
variant.outputs.each { output ->
def project = "Your App Name"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType = variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date();
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
```
|
An alternative solution is to set `$dateTime` property in `defaultConfig` as shown below:
```
defaultConfig {
setProperty("archivesBaseName", "Appname-$dateTime-v$versionName")
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
This code working for me.
```
applicationVariants.all { variant ->
variant.outputs.each { output ->
def project = "Your App Name"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType = variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date();
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
```
|
You can just add the code below inside the `defaultConfig` section located in `android` section.
```
setProperty("archivesBaseName", "yourData-$versionName " + (new Date().format("HH-mm-ss")))
```
Inspired by [enter link description here](https://stackoverflow.com/a/28992851/6940373)
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
I'm assuming that you want it in the format you specified, so here's one possible solution.
In your gradle file you can define a new function to get the date time string like you desire:
```
import java.text.DateFormat
import java.text.SimpleDateFormat
def getDateTime() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
return df.format(new Date());
}
```
Then for all variants you can simply run this:
```
android {
//...
buildTypes {
//...
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + getDateTime() + ".apk"))
}
}
}
}
```
Note that this doesn't really output the apk name like you posted, but I guess it's enough to help you out.
|
This is mine hope to help you
```
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(
(String) file.parent,
(String) file.name.replace(
file.name,
// alter this string to change output file name
"APigLive_Android_" + variant.name + "_" + variant.versionName + "_" + releaseTime() + ".apk"
)
)
}
}
def releaseTime(){
return new Date().format("MM:dd:HH:mm", TimeZone.getTimeZone("GMT"))
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
I'm assuming that you want it in the format you specified, so here's one possible solution.
In your gradle file you can define a new function to get the date time string like you desire:
```
import java.text.DateFormat
import java.text.SimpleDateFormat
def getDateTime() {
DateFormat df = new SimpleDateFormat("yyyyMMddHHmm");
return df.format(new Date());
}
```
Then for all variants you can simply run this:
```
android {
//...
buildTypes {
//...
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(file.parent, file.name.replace(".apk", "-" + getDateTime() + ".apk"))
}
}
}
}
```
Note that this doesn't really output the apk name like you posted, but I guess it's enough to help you out.
|
This code working for me.
```
applicationVariants.all { variant ->
variant.outputs.each { output ->
def project = "Your App Name"
def SEP = "_"
def flavor = variant.productFlavors[0].name
def buildType = variant.variantData.variantConfiguration.buildType.name
def version = variant.versionName
def date = new Date();
def formattedDate = date.format('ddMMyy_HHmm')
def newApkName = project + SEP + flavor + SEP + buildType + SEP + version + SEP + formattedDate + ".apk"
output.outputFile = new File(output.outputFile.parent, newApkName)
}
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
I also add a formatted date to my build. In first place I used some kind of "now" with `new Date()`, but this leads to trouble when starting the build with Android Studio, like in one of the comments above. I decided to use the timestamp of the latest commit. I found some inspiration here: <https://jdpgrailsdev.github.io/blog/2014/10/14/spring_boot_gradle_git_info.html>
Adding the timestamp is handled like below:
```
def getLatestCommitTimeStamp() {
def revision = 'git rev-list --max-count 1 --timestamp HEAD'.execute().text.trim()
def gitCommitMillis = java.util.concurrent.TimeUnit.SECONDS.toMillis(revision.split(' ').first() as long)
return new Date(gitCommitMillis).format("_HH.mm.ss_dd-MM-yyyy", TimeZone.getTimeZone('Europe/Berlin'))
}
```
My renaming part looks like this:
```
android.applicationVariants.all { variant ->
if (variant.buildType.name == 'release') {
def lastCommitFormattedDate = getLatestCommitTimeStamp()
variant.outputs.each { output ->
def alignedOutputFile = output.outputFile
def unalignedOutputFile = output.packageApplication.outputFile
// Customise APK filenames (to include build version)
if (variant.buildType.zipAlignEnabled) {
// normal APK
output.outputFile = new File(alignedOutputFile.parent, alignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
// 'unaligned' APK
output.packageApplication.outputFile = new File(unalignedOutputFile.parent, unalignedOutputFile.name.replace(".apk", "-v" + defaultConfig.versionName + "-" + variant.buildType.name.toUpperCase() + "-${gitSha}" + lastCommitFormattedDate + ".apk").replace("-" + variant.buildType.name, "").replace(project.name, "otherName"))
}
}
```
|
This is mine hope to help you
```
android.applicationVariants.all { variant ->
variant.outputs.each { output ->
def file = output.outputFile
output.outputFile = new File(
(String) file.parent,
(String) file.name.replace(
file.name,
// alter this string to change output file name
"APigLive_Android_" + variant.name + "_" + variant.versionName + "_" + releaseTime() + ".apk"
)
)
}
}
def releaseTime(){
return new Date().format("MM:dd:HH:mm", TimeZone.getTimeZone("GMT"))
}
```
|
29,006,403 |
I want to create a simple header/content/footer layout as was asked hundreds of times already, and I found one that I really like. I have create [a jsFiddle](http://jsfiddle.net/f5Lhsqdt/2/) that showcases the approach. Everything works fine except for the `<footer>` tag.
Basically, I have tried to use a `footerElement` definition analogous to
```
header.headerElement:before {
content: "";
display: inline-block;
height: 100%;
vertical-align: middle;
float: left;
}
```
to accomplish vertically aligned text elements and other stuff inside the `<footer>`, but it doesn't work. As I don't understand what the `:before` trick really does with the `headerElement` class, I think the problem lies in me just copying it and expecting it to work. But I can't find out on my own how to do the same in the footer. What do I have to change/add to get my stuff vertically aligned in the footer as well? It would suffice to accomplish this for text, as I don't think anything else (images) will be used there anyway.
Also, I noticed `color: red` does nothing if put inside the above `header.headerElement:before` block. Is this related to the problem?
|
2015/03/12
|
[
"https://Stackoverflow.com/questions/29006403",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726428/"
] |
An alternative solution is to set `$dateTime` property in `defaultConfig` as shown below:
```
defaultConfig {
setProperty("archivesBaseName", "Appname-$dateTime-v$versionName")
}
```
|
You can just add the code below inside the `defaultConfig` section located in `android` section.
```
setProperty("archivesBaseName", "yourData-$versionName " + (new Date().format("HH-mm-ss")))
```
Inspired by [enter link description here](https://stackoverflow.com/a/28992851/6940373)
|
67,132,971 |
How can I define a type that is the subclass of another class (including the static methods on the parent class)?
### Simplified Example
Let's say I have two abstract base classes and two concrete subclasses (one for each):
```js
abstract class BaseEntity {
foo?: string;
static init<T extends BaseEntity>(this: new () => T, data: Partial<T>): T {
return Object.assign(new this(), data);
}
}
class FooBarEntity extends BaseEntity {
bar?: string;
}
abstract class BasePrinter<T extends BaseEntity> {
constructor(
private entityClass: typeof BaseEntity // <-- This would work if BaseEntity weren't abstract.
// What should I do instead of this?
) {}
initAndPrint(data: Partial<T>) {
const entity = this.entityClass.init(data);
console.log(entity);
}
}
class FooBarPrinter extends BasePrinter<FooBarEntity> {
// ...
}
```
### Goal
I want to be able to do this:
```js
const myPrinter = new FooBarPrinter(FooBarEntity);
myPrinter.initAndPrint({ foo: 'FOO', bar: 'BAR' }); // FooBarEntity { foo: 'FOO', bar: 'BAR' }
```
I could just define a type that contains a function called `initAndPrint` but I'm hoping to figure out a more generic/universal approach if I can.
|
2021/04/16
|
[
"https://Stackoverflow.com/questions/67132971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5291/"
] |
Maybe you could try it with a generic type `BaseEntityConstructor` to represent the static part? (See for example this [blog post](https://www.javaer101.com/en/article/15573960.html))
If you define
```
interface BaseEntityConstructor<T extends BaseEntity> {
new (): T;
init(this: new () => T, data: Partial<T>): T
}
```
and replace `typeof BaseEntity` in the `BasePrinter` constructor with `BaseEntityConstructor<T>`:
```
abstract class BasePrinter<T extends BaseEntity> {
constructor(
private entityClass: BaseEntityConstructor<T>
) {}
..
}
```
the example type checks and runs okay.
[Playground Link](https://www.typescriptlang.org/play?#code/IYIwzgLgTsDGEAJYBthjAgQmgpgUQDsIBLCATwQG8AoBBAMwHtGB+ALgUimIIHMBuarU4RgJWAh6kAPABUEOAB4QcBACYZsYfEVJkAfAAoIAC2JgOBHAHcEhgJQIAvPoSyANAjVjgHAArAUCTAyHL69hzyNHR0UDgQAK5QBAgA8iAAVjjwAHRoYMS8BIZWtqbmDp7eovaCdAC+1I3UPCpQ9HA4WLiEJOQAwowEXAnwjFByCsqqGt3avXqu0QildhFugsJSEMZmFis2a86uHl4+-oHBobLhkU1CKPkIAGLM2FAL5FMq6po9ul9liBAuwRNw+IJmqAuHBEI90HMcH5wW1JkofrMtDo+gYqMJYEMRmMoIZhHQAA7cABuYi6qhx-VQ6A4WM+ZEGw2gowg4zCwkclEadC2BFIAEF1MjWoZqr4EAEgsQQmEBWSkITEPS9M4EOUwDktQMmfrtjKfLUhDF1cNGMgcDlkIxeIZDWQLQ17tR4RhXox3lKiDgoN8Zn9tAHUb73mylsIAPRxhA5ZOehMIADijBCDw1CAAtmQI0Gdaso4EiySyx8AW7NgWKzlthK1BHDJQGMwOAByZ6pVJdzzAqDdzBigBKXYQ9VqCDTVbZVA7jG7vf7g8CI-Hk8aQA)
|
So I ended up coming up with this:
```
type ConstructorType<T = any> = new (...args: any[]) => T;
type BaseEntityType<T> = ConstructorType<T> & {
[K in keyof typeof BaseEntity]: (typeof BaseEntity)[K]
}
```
Which basically defines a generic constructor function type `ConstructorType<T>` and then defines a combination of it with the static properties on BaseEntity to create a type that seems to work the way I expected.
Not sure if there are any egde cases or something I didn't account for, but so far it seems to work.
|
59,577,562 |
I am tring to use a map to get words from a string and map them to a widget.
I have tried this but my problem is the key for the words doe and sister get the same keys so i end up getting only one of them
String theText = "my name is doe from `http.doe.com`, my sister is selly. doe and saqil are not sister friends of koiter.";
```
wordsMap = Map.fromIterable(text.split(' '),
key: (v) => v,
value: (v) => TextSpan(text: v));
```
so I tried the code below
```
Map mapMyWord = {};
// var wordsMap;
var splitForSize = text.split(' ').toList();
for(var t = 0;t<= splitForSize.length-1;t++){
mapMyWord[t] = {'$t':TextSpan(text: splitForSize[t])};
}
```
but In the second code when I tried to access `mapMyWord.values.toList()` it returns a list of map data again
`[{0: TextSpan("my")}, {1: TextSpan("name")}, {2: TextSpan("is")}, {3: TextSpan("doe")}, {4: TextSpan("````http.codeish.com````,")}, ... ,{19: TextSpan("koiter")}]`
so my main problem is how to get the values from here.
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59577562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9398610/"
] |
You are forcing them to be a single column. Joining the two into a single string means Python no longer regards them as separate.
But try this instead:
```py
import csv
import operator
with open('bad_voice_ports.csv') as readfile, open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
readCSV = csv.reader(readfile)
writeCSV = csv.writer(writefile)
for row in sorted(readCSV, key=operator.itemgetter(1)):
bad_port = row[1][:4],row[4][2::]
print(bad_port)
writeCSV.writerow(bad_port)
```
If you want to include the number of times each key occurred, you can easily include that in the program, too. I would refactor slightly to separate the reading and the writing.
```py
import csv
import operator
from collections import Counter
with open('bad_voice_ports.csv') as readfile:
readCSV = csv.reader(readfile)
rows = []
counts = Counter()
for row in readCSV:
rows.append([row[1][:4], row[4][2::]])
counts[row[1][:4]] += 1
with open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
writeCSV = csv.writer(writefile)
for row in sorted(rows):
print(row)
writeCSV.writerow([counts[row[0]]] + row)
```
I would recommend to remove the header line from the CSV file entirely; throwing away (or separating out and prepending back) the first line should be an easy change if you want to keep it.
(Also, hard-coding input and output file names is problematic; maybe have the program read them from `sys.argv[1:]` instead.)
|
So my suggestion is failry simple. As i stated in a previous comment there is good documentation on CSV read and write in python here: <https://realpython.com/python-csv/>
As per an example, to read from a csv the columns you need you can simply do this:
```
>>> file = open('some.csv', mode='r')
>>> csv_reader = csv.DictReader(file)
>>> for line in csv_reader:
... print(line["Dslam_Name"] + " " + line["Ani"])
...
```
This would return:
```
aart-m1-m1 302xxxxxxxxx
```
Now you can just as easilly create a variable and store the column values there and later write them to a file or just open up a new file wile reading lines and writing the column values in there. I hope this helps you.
|
59,577,562 |
I am tring to use a map to get words from a string and map them to a widget.
I have tried this but my problem is the key for the words doe and sister get the same keys so i end up getting only one of them
String theText = "my name is doe from `http.doe.com`, my sister is selly. doe and saqil are not sister friends of koiter.";
```
wordsMap = Map.fromIterable(text.split(' '),
key: (v) => v,
value: (v) => TextSpan(text: v));
```
so I tried the code below
```
Map mapMyWord = {};
// var wordsMap;
var splitForSize = text.split(' ').toList();
for(var t = 0;t<= splitForSize.length-1;t++){
mapMyWord[t] = {'$t':TextSpan(text: splitForSize[t])};
}
```
but In the second code when I tried to access `mapMyWord.values.toList()` it returns a list of map data again
`[{0: TextSpan("my")}, {1: TextSpan("name")}, {2: TextSpan("is")}, {3: TextSpan("doe")}, {4: TextSpan("````http.codeish.com````,")}, ... ,{19: TextSpan("koiter")}]`
so my main problem is how to get the values from here.
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59577562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9398610/"
] |
You are forcing them to be a single column. Joining the two into a single string means Python no longer regards them as separate.
But try this instead:
```py
import csv
import operator
with open('bad_voice_ports.csv') as readfile, open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
readCSV = csv.reader(readfile)
writeCSV = csv.writer(writefile)
for row in sorted(readCSV, key=operator.itemgetter(1)):
bad_port = row[1][:4],row[4][2::]
print(bad_port)
writeCSV.writerow(bad_port)
```
If you want to include the number of times each key occurred, you can easily include that in the program, too. I would refactor slightly to separate the reading and the writing.
```py
import csv
import operator
from collections import Counter
with open('bad_voice_ports.csv') as readfile:
readCSV = csv.reader(readfile)
rows = []
counts = Counter()
for row in readCSV:
rows.append([row[1][:4], row[4][2::]])
counts[row[1][:4]] += 1
with open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
writeCSV = csv.writer(writefile)
for row in sorted(rows):
print(row)
writeCSV.writerow([counts[row[0]]] + row)
```
I would recommend to remove the header line from the CSV file entirely; throwing away (or separating out and prepending back) the first line should be an easy change if you want to keep it.
(Also, hard-coding input and output file names is problematic; maybe have the program read them from `sys.argv[1:]` instead.)
|
You can use `sorted`:
```
import csv
_h, *data = csv.reader(open('filename.csv'))
with open('new_csv.csv', 'w') as f:
write = csv.writer(f)
csv.writerows([_h, *sorted([(i[1], i[4]) for i in data], key=lambda x:x[0])])
```
|
59,577,562 |
I am tring to use a map to get words from a string and map them to a widget.
I have tried this but my problem is the key for the words doe and sister get the same keys so i end up getting only one of them
String theText = "my name is doe from `http.doe.com`, my sister is selly. doe and saqil are not sister friends of koiter.";
```
wordsMap = Map.fromIterable(text.split(' '),
key: (v) => v,
value: (v) => TextSpan(text: v));
```
so I tried the code below
```
Map mapMyWord = {};
// var wordsMap;
var splitForSize = text.split(' ').toList();
for(var t = 0;t<= splitForSize.length-1;t++){
mapMyWord[t] = {'$t':TextSpan(text: splitForSize[t])};
}
```
but In the second code when I tried to access `mapMyWord.values.toList()` it returns a list of map data again
`[{0: TextSpan("my")}, {1: TextSpan("name")}, {2: TextSpan("is")}, {3: TextSpan("doe")}, {4: TextSpan("````http.codeish.com````,")}, ... ,{19: TextSpan("koiter")}]`
so my main problem is how to get the values from here.
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59577562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9398610/"
] |
You are forcing them to be a single column. Joining the two into a single string means Python no longer regards them as separate.
But try this instead:
```py
import csv
import operator
with open('bad_voice_ports.csv') as readfile, open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
readCSV = csv.reader(readfile)
writeCSV = csv.writer(writefile)
for row in sorted(readCSV, key=operator.itemgetter(1)):
bad_port = row[1][:4],row[4][2::]
print(bad_port)
writeCSV.writerow(bad_port)
```
If you want to include the number of times each key occurred, you can easily include that in the program, too. I would refactor slightly to separate the reading and the writing.
```py
import csv
import operator
from collections import Counter
with open('bad_voice_ports.csv') as readfile:
readCSV = csv.reader(readfile)
rows = []
counts = Counter()
for row in readCSV:
rows.append([row[1][:4], row[4][2::]])
counts[row[1][:4]] += 1
with open('bad_voice_portsnew20200103SORTED.csv', 'w') as writefile:
writeCSV = csv.writer(writefile)
for row in sorted(rows):
print(row)
writeCSV.writerow([counts[row[0]]] + row)
```
I would recommend to remove the header line from the CSV file entirely; throwing away (or separating out and prepending back) the first line should be an easy change if you want to keep it.
(Also, hard-coding input and output file names is problematic; maybe have the program read them from `sys.argv[1:]` instead.)
|
After the help from @tripleee and @marxmacher my final code is
```
import csv
import operator
from collections import Counter
with open('bad_voice_ports.csv') as csv_file:
readCSV = csv.reader(csv_file, delimiter=',')
sortedlist = sorted(readCSV, key=operator.itemgetter(1))
line_count = 0
rows = []
counts = Counter()
for row in sortedlist:
Dslam = row[1][:4]
Ani = row[4][2:]
if line_count == 0:
print(row[1], row[4])
line_count += 1
else:
rows.append([row[1][:4], row[4][2::]])
counts[row[1][:4]] += 1
print(Dslam, Ani)
line_count += 1
for row in sorted(rows):
f = open("bad_voice_portsnew202001061917.xls","a+")
f.write(row[0] + '\t' + row[1] + '\t' + str(counts[row[0]]) + '\n')
f.close()
print('Total of Bad ports =', str(line_count-1))
```
As with this way the desired values/columns are extracted from the initial csv file and a new xls file is generated with the desired values stored in different columns and the total values per key are counted, along with the total of entries.
Thanks for all the help, please feel free for any improvement suggestions!
|
59,577,562 |
I am tring to use a map to get words from a string and map them to a widget.
I have tried this but my problem is the key for the words doe and sister get the same keys so i end up getting only one of them
String theText = "my name is doe from `http.doe.com`, my sister is selly. doe and saqil are not sister friends of koiter.";
```
wordsMap = Map.fromIterable(text.split(' '),
key: (v) => v,
value: (v) => TextSpan(text: v));
```
so I tried the code below
```
Map mapMyWord = {};
// var wordsMap;
var splitForSize = text.split(' ').toList();
for(var t = 0;t<= splitForSize.length-1;t++){
mapMyWord[t] = {'$t':TextSpan(text: splitForSize[t])};
}
```
but In the second code when I tried to access `mapMyWord.values.toList()` it returns a list of map data again
`[{0: TextSpan("my")}, {1: TextSpan("name")}, {2: TextSpan("is")}, {3: TextSpan("doe")}, {4: TextSpan("````http.codeish.com````,")}, ... ,{19: TextSpan("koiter")}]`
so my main problem is how to get the values from here.
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59577562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9398610/"
] |
So my suggestion is failry simple. As i stated in a previous comment there is good documentation on CSV read and write in python here: <https://realpython.com/python-csv/>
As per an example, to read from a csv the columns you need you can simply do this:
```
>>> file = open('some.csv', mode='r')
>>> csv_reader = csv.DictReader(file)
>>> for line in csv_reader:
... print(line["Dslam_Name"] + " " + line["Ani"])
...
```
This would return:
```
aart-m1-m1 302xxxxxxxxx
```
Now you can just as easilly create a variable and store the column values there and later write them to a file or just open up a new file wile reading lines and writing the column values in there. I hope this helps you.
|
You can use `sorted`:
```
import csv
_h, *data = csv.reader(open('filename.csv'))
with open('new_csv.csv', 'w') as f:
write = csv.writer(f)
csv.writerows([_h, *sorted([(i[1], i[4]) for i in data], key=lambda x:x[0])])
```
|
59,577,562 |
I am tring to use a map to get words from a string and map them to a widget.
I have tried this but my problem is the key for the words doe and sister get the same keys so i end up getting only one of them
String theText = "my name is doe from `http.doe.com`, my sister is selly. doe and saqil are not sister friends of koiter.";
```
wordsMap = Map.fromIterable(text.split(' '),
key: (v) => v,
value: (v) => TextSpan(text: v));
```
so I tried the code below
```
Map mapMyWord = {};
// var wordsMap;
var splitForSize = text.split(' ').toList();
for(var t = 0;t<= splitForSize.length-1;t++){
mapMyWord[t] = {'$t':TextSpan(text: splitForSize[t])};
}
```
but In the second code when I tried to access `mapMyWord.values.toList()` it returns a list of map data again
`[{0: TextSpan("my")}, {1: TextSpan("name")}, {2: TextSpan("is")}, {3: TextSpan("doe")}, {4: TextSpan("````http.codeish.com````,")}, ... ,{19: TextSpan("koiter")}]`
so my main problem is how to get the values from here.
|
2020/01/03
|
[
"https://Stackoverflow.com/questions/59577562",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9398610/"
] |
After the help from @tripleee and @marxmacher my final code is
```
import csv
import operator
from collections import Counter
with open('bad_voice_ports.csv') as csv_file:
readCSV = csv.reader(csv_file, delimiter=',')
sortedlist = sorted(readCSV, key=operator.itemgetter(1))
line_count = 0
rows = []
counts = Counter()
for row in sortedlist:
Dslam = row[1][:4]
Ani = row[4][2:]
if line_count == 0:
print(row[1], row[4])
line_count += 1
else:
rows.append([row[1][:4], row[4][2::]])
counts[row[1][:4]] += 1
print(Dslam, Ani)
line_count += 1
for row in sorted(rows):
f = open("bad_voice_portsnew202001061917.xls","a+")
f.write(row[0] + '\t' + row[1] + '\t' + str(counts[row[0]]) + '\n')
f.close()
print('Total of Bad ports =', str(line_count-1))
```
As with this way the desired values/columns are extracted from the initial csv file and a new xls file is generated with the desired values stored in different columns and the total values per key are counted, along with the total of entries.
Thanks for all the help, please feel free for any improvement suggestions!
|
You can use `sorted`:
```
import csv
_h, *data = csv.reader(open('filename.csv'))
with open('new_csv.csv', 'w') as f:
write = csv.writer(f)
csv.writerows([_h, *sorted([(i[1], i[4]) for i in data], key=lambda x:x[0])])
```
|
40,056 |
I'm curious about the process of getting a Xbox 360 dev-kit.
What are the requirements? Do you have to have a track record in game development. Can indie gamers get one. How much does it cost? Is there special hardware?
|
2012/10/16
|
[
"https://gamedev.stackexchange.com/questions/40056",
"https://gamedev.stackexchange.com",
"https://gamedev.stackexchange.com/users/4568/"
] |
Basically, [RTFM](http://www.xbox.com/en-US/developers/faq#developer).
So either you work for a *certified Xbox 360 publisher*, and/or you're already in contact with a *Developer Account Manager*, but that would mean that you're already an established developer so you wouldn't be asking this question.
Or you request to join the *Registered Developers Program* that allows indies to access devkits and the XDK. This is done simply via email. This seems to be less restrictive, but you'll still have to prove that you can make proper games (e.g. you have "personnel with significant previous professional game development industry experience"), sign an NDA, and probably purchase a devkit.
|
You need to have money and you need to have a publisher with several published AAA titles.
It is indeed a special piece of hardware - nowadays not so much because of the actual hardware (which is slightly different), but because it gives you more freedom when running games (dev mode, debugging, etc.)
It's pretty pointless for indies anyway. However if you only want to experiment with native 360 stuff and not release a game, I believe there are some legally gray areas that allow you to do that.
|
283,587 |
I am working on CSV import to add custom attribute data for Products. I have created a custom attribute as "slide\_link". I am unable to add only SKU and slide\_link in CSV for adding data of attribute in the product.
Please provide a solution for above.
|
2019/07/29
|
[
"https://magento.stackexchange.com/questions/283587",
"https://magento.stackexchange.com",
"https://magento.stackexchange.com/users/73013/"
] |
Please analyse below demo its working to update price and qty using sku ( specific SKU ) via CSV, I hope its helpful to you.. ( its just idea how to work in magento2 )
```
<?php
use Magento\Framework\App\Bootstrap;
require __DIR__ . '/app/bootstrap.php';
$params = $_SERVER;
$bootstrap = Bootstrap::create(BP, $params);
$obj = $bootstrap->getObjectManager();
$state = $obj->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');
$productRepository = $obj->get('Magento\Catalog\Model\ProductRepository');
$stockRegistry = $obj->get('Magento\CatalogInventory\Api\StockRegistryInterface');
$csv = "csvfilename.csv";
if (!empty($argv) && sizeof($argv) > 1) {
$csv = $argv[1];
}
if (($handle = fopen($csv, "r")) !== FALSE) {
while (($data = fgetcsv($handle, 2000, "\t")) !== FALSE) {
$num = count($data);
if ($num < 1) {
continue;
}
$sku = trim($data[0]);
if ($num < 2) {
echo "Skipping: " . $sku . " not enough fields\n";
continue;
}
$qty = trim($data[1]);
$price = trim($data[2]);
try {
$product = $productRepository->get($sku);
} catch (\Exception $e) {
echo "Error: Invalid SKU, ".$sku."\n";
continue;
}
if ($product->getPrice() != $price) {
$product->setPrice($price);
$product->save();
}
try {
$stockItem = $stockRegistry->getStockItemBySku($sku);
} catch (\Exception $e) {
echo "Error: Invalid stock SKU, ".$sku."\n";
continue;
}
if ($stockItem->getQty() != $qty) {
$stockItem->setQty($qty);
if ($qty > 0) {
$stockItem->setIsInStock(1);
}
$stockRegistry->updateStockItemBySku($sku, $stockItem);
}
}
fclose($handle);
}
```
|
I am not sure why stock info is present in code of previous answer. There are easier, and surely faster, ways to update attributes values (but depending by the attribute type it could need some extra code)
Using **\Magento\Catalog\Model\ResourceModel\Product\Action** & **\Magento\Catalog\Model\Product\Attribute\Repository**
You can just do
```
$product = $this->_productRepository->get($sku);
$this->_action->updateAttributes(
array($product->getId()),
array('YOUR_ATTRIBUTE_CODE' => $YOUR_ATTRIBUTE_VALUE),
1
);
```
That last parameter is **store\_id**, in this example: 1
|
42,233,977 |
I want to save this data in JSON format without using PHP ,when user give the value and press send ,its data add in JSON so that ,I can use this JSON as Database.
```
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>
```
Thank you so much for your help :) in advance
|
2017/02/14
|
[
"https://Stackoverflow.com/questions/42233977",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4345342/"
] |
You can iterate through your form and collect it's values in an array, which you can encode in JSON format.
```
<!DOCTYPE html>
<html>
<body>
<form action="action_page.php">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<input type="submit" value="Submit" onclick="logJsonInputs()">
</form>
<script type="text/javascript">
function logJsonInputs() {
var nameFormElements = document.getElementById("name_form").elements;
var inputs = [];
for(var i = 0; i < nameFormElements.length; i++) {
var element = nameFormElements[i];
inputs[element.name] = element.value;
}
var jsonInputs = JSON.stringify(inputs);
console.log(jsonInputs);
}
</script>
</body>
</html>
```
|
```
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script type="text/javascript">
function stringifyForm(formObject)
{
var jsonObject = {};
var inputElements = formObject.getElementsByTagName("input");
inputElements = Array.prototype.slice.apply(inputElements); //Because I want to use forEach and getElementsByTagName returns an object.
inputElements.forEach(function(e,i,a)
{
if (e.type != "submit")
{
jsonObject[e.name] = e.value;
}
}
);
$.post("https://www.apiaas.com/consume.php",
{
"data":jsonObject
},
function(data)
{
console.log(data);
}
);
}
function jquerySolution(formObject)
{
var jsonObject = JSON.stringify( $(formObject).serializeArray() );
$.post("https://www.apiaas.com/consume.php",
{
"data":jsonObject
},
function(data)
{
console.log(data);
}
);
}
</script>
</head>
<body>
<form onsubmit="jquerySolution(this);return false;">
First name:<br>
<input type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
```
|
1,519,002 |
Background
----------
I want to obtain the `pid` of a specific Terminal window.
```
ps -A | grep -w Terminal.app | grep -v grep | awk '{print $1}'
```
However, the above grabs the `pid` of the entire application and not of a specific tab or window that is running.
In Linux, one could execute the following:
```
x-terminal-emulator -e "cd $HOME ; sleep 10"
ps ax | \
grep -v "grep" | \
grep "sh -c" | grep "cd $HOME ; sleep 10" \
xargs | \
cut -d ' ' -f 1
```
Issue
-----
Given the below `terminal` bash command, which opens a new terminal window and closes it much like `x-terminal-emulator` does.
**How would I attempt to grab the `pid` of the window opened via the `terminal` command using `ps` like in the Linux example?**
`terminal`:
```
#!/bin/bash
# Open new terminal window from the command line using v3 syntax for applescript as needed in terminal Version 3+
# This script blocks until the cmd is executed in the new terminal window then closes the new terminal window.
#
# Usage:
# terminal Opens the current directory in a new terminal window
# terminal [PATH] Open PATH in a new terminal window
# terminal [CMD] Open a new terminal window and execute CMD
# terminal [PATH] [CMD] Opens a new terminal window @ the PATH and executes CMD
#
# Example:
# terminal ~/Code/HelloWorld ./setup.sh
#
# Mac OS only
[ "$(uname -s)" != "Darwin" ] && {
echo 'Mac OS Only'
return
}
function terminal() {
local cmd=""
local wd="$PWD"
local args="$*"
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
if [ -d "$1" ]; then
wd="$1"
args="${*:2}"
fi
if [ -n "$args" ]; then
cmd="$args"
fi
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
osascript <<-EOF
tell application "Terminal" to tell the front window
set w to do script "cd $wd; $cmd"
repeat
delay 1
if not busy of w then exit repeat
end repeat
close it
end tell
EOF
}
terminal "$@"
```
|
2020/01/21
|
[
"https://superuser.com/questions/1519002",
"https://superuser.com",
"https://superuser.com/users/684201/"
] |
Use `echo $$`. Mac OS is a unixy box and so $$ is an alias for myPid.
As you can see I am first showing all the shells (I use zsh) running at the moment. Below that you can see that `echo $$` shows the PID of the pre-existing shell and not something new.
`~ % ps aux | grep zsh
ram 30724 0.8 0.0 4869828 5888 s003 S 9:28AM 0:00.35 -zsh
ram 29765 0.0 0.0 4868884 8 s002 S+ 5:12PM 0:00.40 -zsh
ram 29654 0.0 0.0 5028628 8 s001 S+ 4:52PM 0:00.49 -zsh
ram 8001 0.0 0.0 4793028 8 s000 S+ 13Jan20 0:00.70 -zsh
ram 30782 0.0 0.0 4258888 200 s003 R+ 9:29AM 0:00.00 egrep --color=auto zsh`
`~ % echo $$
30724
~ %`
|
Invoking your *terminal.sh* script using `./terminal.sh "cd $HOME ; sleep 1000"` you can get the PID of the window opened which is running the `sleep` command using this:
```
ps ax | \
grep 'sleep 1000' | \
grep -v grep | \
grep -v ./terminal.sh | \
awk '{print $1}'
```
If you try `ps ax | grep 'sleep 1000'` (or whatever command *terminal.sh* is running) you will see 3 returned:
```
A1398% ps ax | grep 'sleep 1000'
8263 s000 S+ 0:00.01 /bin/bash ./terminal.sh cd /Users/XXXX ; sleep 1000
8272 s004 R+ 0:00.00 grep sleep 1000
8270 s005 S+ 0:00.00 sleep 1000
```
The first is the command running in the window where *terminal.sh* is running, the second is the current window running `ps ax | grep 'sleep 1000'` and the last is the window actually opened by the *terminal.sh* command.
To get your windows PID therefore additionally exclude `grep` and `terminal.sh`
---
In the picture below:
1. iTerm window showing `ps ax | grep s00` before calling *terminal.sh*
2. iTerm window running `./terminal.sh "cd $HOME ; sleep 1000"`
3. Terminal window opened by `terminal.sh` if none already open.
4. Terminal window opened by `terminal.sh` running `sleep` or whatever the passed command.
5. iTerm window run showing `ps ax | grep s00` after. `ps ax | grep 'sleep 1000' | grep -v grep | grep -v terminal.sh | awk '{print $1}'` shows window 4.
[](https://i.stack.imgur.com/uBPvp.jpg)
Note that your *terminal.sh* command will open an extra terminal window (3) if none are already open. This window is *not* closed again on completion by the script although window (4) is.
|
22,114,292 |
In swing application, I am using `DefaultTableCellRenderer` to flash the table cell when the cell time is equal to system time. I wrote if statement to compare cell time with `hh:mm` , If both time are equal, time cells backgroung will blink on the table rows. It is blinking 60 secs only still if statement is true, But i want to continue blinking **same cell** after false if statement.
I got the position value of blinking cell like (0,2) and (1,2). from this integer, how can i set continues blink after false if statement or Is there any other way? Thank you.
My Code is here :
I added table method and inner class.
```
public void table() throws SQLException
{
Connection c=null;
PreparedStatement pre;
try
{
Class.forName("com.mysql.jdbc.Driver");
c=DriverManager.getConnection("jdbc:mysql://localhost:3306/telecaller_database", "root", "root");
Statement st= c.createStatement();
DateFormat df=new SimpleDateFormat(" dd/MM/yyyy");
Calendar cl=Calendar.getInstance();
Date dt1=cl.getTime();
String str1=df.format(dt1);
System.out.println("today date is "+str1);
pre=c.prepareStatement("Select name,phoneno,time from components where date=?");
pre.setString(1,str1);
ArrayList<String> arl=new ArrayList<String>();
ResultSet rs=pre.executeQuery();
ResultSetMetaData md=rs.getMetaData();
System.out.println("result set data "+pre);
int column=md.getColumnCount();
System.out.println(column);
for(int i=1;i<=column;i++)
{
columns.addElement(md.getColumnName(i));
}
while(rs.next())
{
arl.add(rs.getString(1));
System.out.println(arl);
Vector row=new Vector(column);
for(int j=1;j<=column;j++)
{
row.addElement(rs.getString(j));
}
rows.addElement(row);
}
rs.close();
st.close();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
final JTable table=new JTable(rows,columns);
Border bd2=BorderFactory.createLineBorder(Color.black,1);
table.setBorder(bd2);
table.setDefaultRenderer(Object.class, (TableCellRenderer) new MyFlashingCellRenderer2());
final long startTime = System.currentTimeMillis();
Thread thread = new Thread()
{
public void run()
{
while(true)
{
long now = System.currentTimeMillis();
long second = (now -startTime) / 1000;
// System.out.println(second);
color = second / 2 * 2 == second ? Color.red : Color.yellow;
color1= second / 2 * 2 == second ? Color.green : Color.blue;
// System.out.println(second/2*2);
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
table.tableChanged(new TableModelEvent(table.getModel()));
//table.setBackground(color1);
}
});
try
{
Thread.sleep(1000);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
};
thread.start();
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setBounds(14,20,345,400);
jp1.add(scrollPane);
}
public class MyFlashingCellRenderer extends DefaultTableCellRenderer
{
public int cellr;
public int cellc;
public Component getTableCellRendererComponent(JTable table, Object rows1, boolean isSelected, boolean hasFocus, int row, int column)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, rows1, isSelected, hasFocus, row, column);
String timeformat = " h:mm a";
SimpleDateFormat obDateFormat = new SimpleDateFormat(timeformat);
Calendar time = Calendar.getInstance();
String time1=obDateFormat.format(time.getTime()).toString();
//System.out.println("metod "+cellr+cellc);
if (time1.equals(rows1))
{
cellr=row;
cellc=column;
System.out.println("time "+time1+" row "+rows1);
getTableCellRendererComponent2(table, rows1, isSelected, hasFocus, row, column);
}
else if(!time1.equals(rows1))
{
label.setBackground(null);
}
return label;
}
public Component getTableCellRendererComponent2(JTable table, Object rows1, boolean isSelected,
boolean hasFocus, int x, int y)
{
JLabel label = (JLabel)super.getTableCellRendererComponent(table, rows1, isSelected, hasFocus, x, y);
label.setBackground(color);
System.out.println("outer method "+cellr+cellc);
x=cellr; y=cellc; // potition of blinking cell
System.out.println("x and y "+x+y);
return label;
}
}
```
|
2014/03/01
|
[
"https://Stackoverflow.com/questions/22114292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2034750/"
] |
The code is indeed rather confusing. For example, it is not clear what the *condition* for the blinking should be. At the moment, it seems like the condition is that a particular cell displays the current time (as obtained from a calendar instance). However, making this decision in the `CellRenderer` is highly dubious. Instead, this decision should be made from outside, since it actually depends on the model data.
The implementation of the thread that controls the actual blinking is not very elegant. This could more easily be solved with a Swing `Timer`. (The thread only puts a task on the event queue, anyhow).
Additionally, changing the background of a table cell renderer component is fairly independent of the component itself.
However, I created a small example of how I would tackle this problem. I tried to mimic your original intention as far as possible: The sample creates a table that contains Strings of time (Calendar instances) that are a few seconds in the future, randomly permuted. It creates a timer that regularly checks whether any time limits has been exceeded. When the time has beed exceeded, the corresponding table cell starts to blink.
The blinking itself is handled by a special `BlinkCellRenderer`. Since this cell renderer *only* has to switch the background color of a cell, it just uses a delegate cell renderer which provides the actual cell renderer component, and sets the background color of this component according to the current blinking state. It also allows adding and removing cells that should currently be blinking.
Of course, this could be extended and implemented in a more sophisticated and versatile way, but maybe it serves as an inspiration, at least.
```
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTable;
import javax.swing.JToggleButton;
import javax.swing.SwingUtilities;
import javax.swing.Timer;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableCellRenderer;
public class BlingBlingTable
{
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
createAndShowGUI();
}
});
}
private static void createAndShowGUI()
{
JFrame f = new JFrame();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.getContentPane().add(createMainPanel());
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
private static JPanel createMainPanel()
{
JPanel mainPanel = new JPanel(new BorderLayout());
final JTable table = createTable();
TableCellRenderer delegate = new DefaultTableCellRenderer();
final BlinkCellRenderer blinkCellRenderer =
new BlinkCellRenderer(table, delegate);
table.setDefaultRenderer(Object.class, blinkCellRenderer);
mainPanel.add(table, BorderLayout.CENTER);
createBlinkChecker(table, blinkCellRenderer);
final JToggleButton blinkButton = new JToggleButton("Random blink");
blinkButton.addActionListener(new ActionListener()
{
int r;
int c;
@Override
public void actionPerformed(ActionEvent e)
{
if (blinkButton.isSelected())
{
r = (int)(Math.random() * table.getRowCount());
c = (int)(Math.random() * table.getColumnCount());
blinkCellRenderer.addBlinkingCell(r, c);
}
else
{
blinkCellRenderer.removeBlinkingCell(r, c);
}
}
});
mainPanel.add(blinkButton, BorderLayout.SOUTH);
return mainPanel;
}
// Creates a table that contains strings that represent
// points in time that are a few seconds in the future
private static JTable createTable()
{
Vector<Vector<String>> rowDatas = new Vector<Vector<String>>();
int rs = 3;
int cs = 3;
for (int r=0; r<rs; r++)
{
Vector<String> rowData = new Vector<String>();
for (int c=0; c<cs; c++)
{
Calendar time = Calendar.getInstance();
time.add(Calendar.SECOND, (c+(r * cs))*4);
rowData.add(createTimeString(time));
}
Collections.shuffle(rowData);
rowDatas.add(rowData);
}
Collections.shuffle(rowDatas);
Vector<String> columnData = new Vector<String>();
for (int c=0; c<3; c++)
{
columnData.add("Column "+c);
}
return new JTable(rowDatas, columnData);
}
// Creates a timer that regularly updates the blinking
// state of all cells of the given table
private static void createBlinkChecker(
final JTable table, final BlinkCellRenderer blinkCellRenderer)
{
Timer timer = new Timer(500, new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
updateBlinkingState(table, blinkCellRenderer);
}
});
timer.setInitialDelay(0);
timer.start();
}
// Updates the blinking state of the specified cell
// in the given table, using the #shouldBlink
// method below
private static void updateBlinkingState(
JTable table, BlinkCellRenderer blinkCellRenderer)
{
for (int r=0; r<table.getRowCount(); r++)
{
for (int c=0; c<table.getColumnCount(); c++)
{
if (shouldBlink(table, r, c))
{
blinkCellRenderer.addBlinkingCell(r, c);
}
else
{
blinkCellRenderer.removeBlinkingCell(r, c);
}
}
}
}
// Returns whether the specified cell in the given
// table should currently blink
private static boolean shouldBlink(JTable table, int r, int c)
{
Object value = table.getValueAt(r, c);
Calendar cellTime = parseTime(String.valueOf(value));
Calendar currentTime = Calendar.getInstance();
cellTime.set(Calendar.YEAR,
currentTime.get(Calendar.YEAR));
cellTime.set(Calendar.MONTH,
currentTime.get(Calendar.MONTH));
cellTime.set(Calendar.DAY_OF_MONTH,
currentTime.get(Calendar.DAY_OF_MONTH));
long difference =
currentTime.getTimeInMillis() -
cellTime.getTimeInMillis();
// Blink for 10 seconds
long blinkDurationInMS = 10000;
return
difference >= 0 &&
difference < blinkDurationInMS;
}
// The time format that will be used for creating
// strings from calendar instances and for parsing
private static final String TIME_FORMAT = " h:mm:ss a";
private static final DateFormat DATE_FORMAT =
new SimpleDateFormat(TIME_FORMAT);
// Creates a string containing the given time
// in a particular format
private static String createTimeString(Calendar time)
{
String timeString = DATE_FORMAT.format(time.getTime());
return timeString;
}
// Parse the time from the given string
private static Calendar parseTime(String timeString)
{
Calendar calendar = Calendar.getInstance();
try
{
calendar.setTime(DATE_FORMAT.parse(timeString));
}
catch (ParseException e)
{
e.printStackTrace();
}
return calendar;
}
/**
* A TableCellRenderer which can let particular cells of
* a JTable blink. That is, it switches the background
* color at a regular interval and triggers a repaint
* of the table. The cell renderer components whose
* background is switched are provided by a delegate
* cell renderer
*/
public static class BlinkCellRenderer extends DefaultTableCellRenderer
{
/**
* Serial UID
*/
private static final long serialVersionUID = 6896646544236592534L;
/**
* Simple class storing the coordinates of a
* particular table cell
*/
static class Cell
{
final int r;
final int c;
Cell(int r, int c)
{
this.r = r;
this.c = c;
}
@Override
public int hashCode()
{
return 31 * c + r;
}
@Override
public boolean equals(Object object)
{
if (object instanceof Cell)
{
Cell cell = (Cell)object;
return r == cell.r && c == cell.c;
}
return false;
}
}
/**
* The delegate cell renderer that provides the
* cell renderer components
*/
private final TableCellRenderer delegate;
/**
* The set of cells that are currently blinking
*/
private final Set<Cell> blinkingCells = new HashSet<Cell>();
/**
* The current blinking state (that is, whether
* the cells should be highlighted or not)
*/
private boolean blinkingState = true;
/**
* Creates a BlinkCellRenderer that will let cells of
* the given table blink. The cell renderer components
* are provided by the given delegate
*
* @param table The table
* @param delegate The delegate
*/
BlinkCellRenderer(final JTable table, TableCellRenderer delegate)
{
this.delegate = delegate;
int delayMS = 250;
Timer blinkingTimer = new Timer(delayMS, new ActionListener()
{
boolean timerBlinkingState = true;
@Override
public void actionPerformed(ActionEvent e)
{
blinkingState = timerBlinkingState;
table.repaint();
timerBlinkingState = !timerBlinkingState;
}
});
blinkingTimer.setInitialDelay(0);
blinkingTimer.start();
}
/**
* Add the cell with the given coordinates to the
* set of cells that are currently blinking
*
* @param r The row
* @param c The column
*/
void addBlinkingCell(int r, int c)
{
blinkingCells.add(new Cell(r, c));
}
/**
* Remove the cell with the given coordinates from the
* set of cells that are currently blinking
*
* @param r The row
* @param c The column
*/
void removeBlinkingCell(int r, int c)
{
blinkingCells.remove(new Cell(r,c));
}
/**
* Removes all blinking cells
*/
void clearBlinkingCells()
{
blinkingCells.clear();
}
@Override
public Component getTableCellRendererComponent(
JTable table, Object value, boolean isSelected,
boolean hasFocus, int row, int column)
{
Component component =
delegate.getTableCellRendererComponent(
table, value, isSelected, hasFocus, row, column);
Cell cell = new Cell(row, column);
if (blinkingState && blinkingCells.contains(cell))
{
component.setBackground(Color.RED);
}
else
{
component.setBackground(null);
}
return component;
}
}
}
```
EDIT: Added a functionality to specify the duration for which the cells should keep blinking (`blinkDurationInMS` is the duration how long the cell will blink, in milliseconds)
|
Create another column of data to store in the TableModel that contains a Boolean value. The data should only be in the model, but the column should NOT be displayed in the JTable.
Then your logic can set the Boolean value to Boolean.TRUE whenever the times are the same. Once the value is true you never set it false. The renderer can now check the Boolean value to do the blinking for the cell and the blinking should continue fore ever.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.